Ejemplo n.º 1
0
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            BuildTasksUtility.LogInputParam(log, nameof(CurrentProjectTargetFramework), CurrentProjectTargetFramework);
            BuildTasksUtility.LogInputParam(log, nameof(AnnotatedProjectReferences),
                                            AnnotatedProjectReferences == null
                    ? ""
                    : string.Join(";", AnnotatedProjectReferences.Select(p => p.ItemSpec)));

            if (AnnotatedProjectReferences == null)
            {
                return(!Log.HasLoggedErrors);
            }

            var frameworkToMatch = NuGetFramework.Parse(CurrentProjectTargetFramework);

            if (frameworkToMatch.IsUnsupported)
            {
                log.LogError(string.Format(Strings.UnsupportedTargetFramework, CurrentProjectTargetFramework));
                return(false);
            }

            AssignedProjects = new ITaskItem[AnnotatedProjectReferences.Length];
            for (var index = 0; index < AnnotatedProjectReferences.Length; index++)
            {
                AssignedProjects[index] = AssignPropertiesForSingleReference(AnnotatedProjectReferences[index], frameworkToMatch);
            }

            BuildTasksUtility.LogOutputParam(log, nameof(AssignedProjects), string.Join(";", AssignedProjects.Select(p => p.ItemSpec)));

            return(!Log.HasLoggedErrors);
        }
Ejemplo n.º 2
0
        private async Task <bool> ExecuteAsync(Common.ILogger log)
        {
            if (RestoreGraphItems.Length < 1 && !HideWarningsAndErrors)
            {
                log.LogWarning(Strings.NoProjectsProvidedToTask);
                return(true);
            }

            // Convert to the internal wrapper
            var wrappedItems = RestoreGraphItems.Select(MSBuildUtility.WrapMSBuildItem);

            var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems);

            return(await BuildTasksUtility.RestoreAsync(
                       dependencyGraphSpec : dgFile,
                       interactive : Interactive,
                       recursive : RestoreRecursive,
                       noCache : RestoreNoCache,
                       ignoreFailedSources : RestoreIgnoreFailedSources,
                       disableParallel : RestoreDisableParallel,
                       force : RestoreForce,
                       forceEvaluate : RestoreForceEvaluate,
                       hideWarningsAndErrors : HideWarningsAndErrors,
                       restorePC : RestorePackagesConfig,
                       log : log,
                       cancellationToken : _cts.Token));
        }
        public override bool Execute()
        {
            var logger = new MSBuildLogger(Log);

            BuildTasksUtility.LogInputParam(logger, nameof(CurrentProjectTargetFramework), CurrentProjectTargetFramework);

            BuildTasksUtility.LogInputParam(logger, nameof(FallbackTargetFrameworks),
                                            FallbackTargetFrameworks == null
                    ? ""
                    : string.Join(";", FallbackTargetFrameworks.Select(p => p)));

            BuildTasksUtility.LogInputParam(logger, nameof(AnnotatedProjectReferences),
                                            AnnotatedProjectReferences == null
                    ? ""
                    : string.Join(";", AnnotatedProjectReferences.Select(p => p.ItemSpec)));

            if (AnnotatedProjectReferences == null)
            {
                return(!Log.HasLoggedErrors);
            }

            var fallbackNuGetFrameworks = new List <NuGetFramework>();

            // validate current project framework
            var errorMessage = string.Format(Strings.UnsupportedTargetFramework, CurrentProjectTargetFramework);

            if (!TryParseFramework(CurrentProjectTargetFramework, errorMessage, logger, out var projectNuGetFramework))
            {
                return(false);
            }

            if (FallbackTargetFrameworks != null &&
                FallbackTargetFrameworks.Length > 0)
            {
                foreach (var fallbackFramework in FallbackTargetFrameworks)
                {
                    // validate ATF project frameworks
                    errorMessage = string.Format(Strings.UnsupportedFallbackFramework, fallbackFramework);
                    if (!TryParseFramework(fallbackFramework, errorMessage, logger, out var nugetFramework))
                    {
                        return(false);
                    }
                    else
                    {
                        fallbackNuGetFrameworks.Add(nugetFramework);
                    }
                }
            }

            AssignedProjects = new ITaskItem[AnnotatedProjectReferences.Length];
            for (var index = 0; index < AnnotatedProjectReferences.Length; index++)
            {
                AssignedProjects[index] = AssignNearestFrameworkForSingleReference(AnnotatedProjectReferences[index], projectNuGetFramework, fallbackNuGetFrameworks, logger);
            }

            BuildTasksUtility.LogOutputParam(logger, nameof(AssignedProjects), string.Join(";", AssignedProjects.Select(p => p.ItemSpec)));

            return(!Log.HasLoggedErrors);
        }
Ejemplo n.º 4
0
        public override bool Execute()
        {
            // Log inputs
            var log = new MSBuildLogger(Log);

            log.LogDebug($"(in) ProjectUniqueName '{ProjectUniqueName}'");
            log.LogDebug($"(in) TargetFrameworks '{TargetFrameworks}'");
            log.LogDebug($"(in) ProjectReferences '{string.Join(";", ProjectReferences.Select(p => p.ItemSpec))}'");
            log.LogDebug($"(in) ParentProjectPath '{ParentProjectPath}'");

            var entries = new List <ITaskItem>();

            // Filter obvious duplicates without considering OS case sensitivity.
            // This will be filtered further when creating the spec.
            var seen = new HashSet <string>(StringComparer.Ordinal);

            var parentDirectory = Path.GetDirectoryName(ParentProjectPath);

            foreach (var project in ProjectReferences)
            {
                var refOutput = BuildTasksUtility.GetPropertyIfExists(project, "ReferenceOutputAssembly");

                // Match the same behavior as NuGet.targets
                // ReferenceOutputAssembly == '' OR ReferenceOutputAssembly == 'true'
                if (string.IsNullOrEmpty(refOutput) ||
                    Boolean.TrueString.Equals(refOutput, StringComparison.OrdinalIgnoreCase))
                {
                    // Get the absolute path
                    var referencePath = Path.GetFullPath(Path.Combine(parentDirectory, project.ItemSpec));

                    if (!seen.Add(referencePath))
                    {
                        // Skip already processed projects
                        continue;
                    }

                    var properties = new Dictionary <string, string>();
                    properties.Add("ProjectUniqueName", ProjectUniqueName);
                    properties.Add("Type", "ProjectReference");
                    properties.Add("ProjectPath", referencePath);
                    properties.Add("ProjectReferenceUniqueName", referencePath);

                    if (!string.IsNullOrEmpty(TargetFrameworks))
                    {
                        properties.Add("TargetFrameworks", TargetFrameworks);
                    }

                    BuildTasksUtility.CopyPropertyIfExists(project, properties, "IncludeAssets");
                    BuildTasksUtility.CopyPropertyIfExists(project, properties, "ExcludeAssets");
                    BuildTasksUtility.CopyPropertyIfExists(project, properties, "PrivateAssets");

                    entries.Add(new TaskItem(Guid.NewGuid().ToString(), properties));
                }
            }

            RestoreGraphItems = entries.ToArray();

            return(true);
        }
        /// <summary>
        /// Read a metadata property from each item and split the values.
        /// Nulls and empty values are ignored.
        /// </summary>
        private static IEnumerable <string> GetPropertyValues(ITaskItem[] items, string key)
        {
            if (items == null)
            {
                return(Enumerable.Empty <string>());
            }

            return(items.SelectMany(e => MSBuildStringUtility.Split(BuildTasksUtility.GetPropertyIfExists(e, key))));
        }
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            log.LogDebug($"(in) ProjectPath '{ProjectPath}'");
            log.LogDebug($"(in) DotnetCliToolReferences '{string.Join(";", DotnetCliToolReferences.Select(p => p.ItemSpec))}'");

            var entries = new List <ITaskItem>();

            foreach (var msbuildItem in DotnetCliToolReferences)
            {
                if (string.IsNullOrEmpty(msbuildItem.ItemSpec))
                {
                    throw new InvalidDataException($"Invalid DotnetCliToolReference in {ProjectPath}");
                }

                var uniqueName = $"{msbuildItem.ItemSpec}-{Guid.NewGuid().ToString()}";

                // Create top level project
                var properties = new Dictionary <string, string>();
                properties.Add("ProjectUniqueName", uniqueName);
                properties.Add("Type", "ProjectSpec");
                properties.Add("ProjectPath", ProjectPath);
                properties.Add("ProjectName", $"DotnetCliToolReference-{msbuildItem.ItemSpec}");
                BuildTasksUtility.AddPropertyIfExists(properties, "Sources", RestoreSources);
                BuildTasksUtility.AddPropertyIfExists(properties, "FallbackFolders", RestoreFallbackFolders);
                BuildTasksUtility.AddPropertyIfExists(properties, "PackagesPath", RestorePackagesPath);
                properties.Add("TargetFrameworks", ToolFramework);
                properties.Add("ProjectStyle", ProjectStyle.DotnetCliTool.ToString());
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "Version");

                entries.Add(new TaskItem(Guid.NewGuid().ToString(), properties));

                // Add reference to package
                var packageProperties = new Dictionary <string, string>();
                packageProperties.Add("ProjectUniqueName", uniqueName);
                packageProperties.Add("Type", "Dependency");
                packageProperties.Add("Id", msbuildItem.ItemSpec);
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, packageProperties, "Version", "VersionRange");
                packageProperties.Add("TargetFrameworks", ToolFramework);

                entries.Add(new TaskItem(Guid.NewGuid().ToString(), packageProperties));

                // Add restore spec to ensure this is executed during restore
                var restoreProperties = new Dictionary <string, string>();
                restoreProperties.Add("ProjectUniqueName", uniqueName);
                restoreProperties.Add("Type", "RestoreSpec");

                entries.Add(new TaskItem(Guid.NewGuid().ToString(), restoreProperties));
            }

            RestoreGraphItems = entries.ToArray();

            return(true);
        }
Ejemplo n.º 7
0
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            log.LogDebug($"(in) ProjectUniqueName '{ProjectUniqueName}'");
            log.LogDebug($"(in) TargetFrameworks '{TargetFrameworks}'");
            log.LogDebug($"(in) PackageReferences '{string.Join(";", PackageReferences.Select(p => p.ItemSpec))}'");

            var entries = new List <ITaskItem>();
            var seenIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (var msbuildItem in PackageReferences)
            {
                var packageId = msbuildItem.ItemSpec;

                if (string.IsNullOrEmpty(packageId) || !seenIds.Add(packageId))
                {
                    // Skip empty or already processed ids
                    continue;
                }

                var properties = new Dictionary <string, string>();
                properties.Add("ProjectUniqueName", ProjectUniqueName);
                properties.Add("Type", "Dependency");
                properties.Add("Id", packageId);
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "Version", "VersionRange");
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "VersionOverride");

                if (!string.IsNullOrEmpty(TargetFrameworks))
                {
                    properties.Add("TargetFrameworks", TargetFrameworks);
                }

                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "IncludeAssets");
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "ExcludeAssets");
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "PrivateAssets");
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "NoWarn");
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "IsImplicitlyDefined");
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "GeneratePathProperty");
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "Aliases");

                entries.Add(new TaskItem(Guid.NewGuid().ToString(), properties));
            }

            RestoreGraphItems = entries.ToArray();

            return(true);
        }
Ejemplo n.º 8
0
        public override bool Execute()
        {
#if DEBUG
            var debugRestoreTask = Environment.GetEnvironmentVariable("DEBUG_RESTORE_GRAPH_TASK");
            if (!string.IsNullOrEmpty(debugRestoreTask) && debugRestoreTask.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase))
            {
                Debugger.Launch();
            }
#endif

            if (RestoreGraphItems.Length < 1)
            {
                Log.LogWarning("Unable to find a project to restore!");
                return(true);
            }

            var log = new MSBuildLogger(Log);

            log.LogDebug($"(in) RestoreGraphItems Count '{RestoreGraphItems?.Count() ?? 0}'");
            log.LogDebug($"(in) RestoreGraphOutputPath '{RestoreGraphOutputPath}'");
            log.LogDebug($"(in) RestoreRecursive '{RestoreRecursive}'");

            // Convert to the internal wrapper
            var wrappedItems = RestoreGraphItems.Select(GetMSBuildItem);

            // Create file
            var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems);

            // Add all child projects
            if (RestoreRecursive)
            {
                BuildTasksUtility.AddAllProjectsForRestore(dgFile);
            }

            var fileInfo = new FileInfo(RestoreGraphOutputPath);
            fileInfo.Directory.Create();

            // Save file
            log.LogMinimal($"Writing {fileInfo.FullName}");

            dgFile.Save(fileInfo.FullName);

            return(true);
        }
Ejemplo n.º 9
0
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            log.LogDebug($"(in) ProjectUniqueName '{ProjectUniqueName}'");
            log.LogDebug($"(in) TargetFrameworks '{TargetFrameworks}'");
            log.LogDebug($"(in) PackageDownloads '{string.Join(";", PackageDownloads.Select(p => p.ItemSpec))}'");

            var entries = new List <ITaskItem>();
            var seenIds = new HashSet <Tuple <string, string> >(new CustomEqualityComparer());

            foreach (var msbuildItem in PackageDownloads)
            {
                var packageId = msbuildItem.ItemSpec;

                var properties = new Dictionary <string, string>();
                properties.Add("ProjectUniqueName", ProjectUniqueName);
                properties.Add("Type", "DownloadDependency");
                properties.Add("Id", packageId);
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "Version", "VersionRange");

                properties.TryGetValue("VersionRange", out var versionRange);

                var key = new Tuple <string, string>(packageId, versionRange);

                if (string.IsNullOrEmpty(packageId) || !seenIds.Add(key))
                {
                    // Skip duplicate id/version combinations
                    continue;
                }

                if (!string.IsNullOrEmpty(TargetFrameworks))
                {
                    properties.Add("TargetFrameworks", TargetFrameworks);
                }

                entries.Add(new TaskItem(Guid.NewGuid().ToString(), properties));
            }

            RestoreGraphItems = entries.ToArray();

            return(true);
        }
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            // item -> string
            var all   = AllProjects?.Select(e => e.ItemSpec).ToArray() ?? Array.Empty <string>();
            var valid = ValidProjects?.Select(e => e.ItemSpec).ToArray() ?? Array.Empty <string>();

            // log inputs
            BuildTasksUtility.LogInputParam(log, nameof(AllProjects), all);
            BuildTasksUtility.LogInputParam(log, nameof(ValidProjects), valid);

            // Log warnings for invalid projects
            foreach (var path in all.Except(valid, PathUtility.GetStringComparerBasedOnOS()))
            {
                var message = MSBuildRestoreUtility.GetWarningForUnsupportedProject(path);
                log.Log(message);
            }

            return(true);
        }
Ejemplo n.º 11
0
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            log.LogDebug($"(in) ProjectUniqueName '{ProjectUniqueName}'");
            log.LogDebug($"(in) TargetFrameworks '{TargetFrameworks}'");
            log.LogDebug($"(in) FrameworkReferences '{string.Join(";", FrameworkReferences.Select(p => p.ItemSpec))}'");

            var entries = new List <ITaskItem>();
            var seenIds = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (var msbuildItem in FrameworkReferences)
            {
                var frameworkReference = msbuildItem.ItemSpec;

                if (string.IsNullOrEmpty(frameworkReference) || !seenIds.Add(frameworkReference))
                {
                    // Skip empty or already processed ids
                    continue;
                }

                var properties = new Dictionary <string, string>();
                properties.Add("ProjectUniqueName", ProjectUniqueName);
                properties.Add("Type", "FrameworkReference");
                properties.Add("Id", frameworkReference);

                if (!string.IsNullOrEmpty(TargetFrameworks))
                {
                    properties.Add("TargetFrameworks", TargetFrameworks);
                }
                BuildTasksUtility.CopyPropertyIfExists(msbuildItem, properties, "PrivateAssets");

                entries.Add(new TaskItem(Guid.NewGuid().ToString(), properties));
            }

            RestoreGraphItems = entries.ToArray();

            return(true);
        }
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            // Log Inputs
            BuildTasksUtility.LogInputParam(log, nameof(HasPackageReferenceItems), HasPackageReferenceItems.ToString());
            BuildTasksUtility.LogInputParam(log, nameof(MSBuildProjectDirectory), MSBuildProjectDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(MSBuildProjectName), MSBuildProjectName);
            BuildTasksUtility.LogInputParam(log, nameof(ProjectJsonPath), ProjectJsonPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreProjectStyle), RestoreProjectStyle);

            var result = BuildTasksUtility.GetProjectRestoreStyle(RestoreProjectStyle, HasPackageReferenceItems, ProjectJsonPath, MSBuildProjectDirectory, MSBuildProjectName, log);

            IsPackageReferenceCompatibleProjectStyle = result.IsPackageReferenceCompatibleProjectStyle;
            ProjectStyle = result.ProjectStyle;

            // Log Outputs
            BuildTasksUtility.LogOutputParam(log, nameof(IsPackageReferenceCompatibleProjectStyle), IsPackageReferenceCompatibleProjectStyle.ToString());
            BuildTasksUtility.LogOutputParam(log, nameof(ProjectStyle), ProjectStyle.ToString());

            return(!Log.HasLoggedErrors);
        }
Ejemplo n.º 13
0
        public override bool Execute()
        {
            if (RestoreGraphItems.Length < 1)
            {
                Log.LogWarning("Unable to find a project to restore!");
                return(true);
            }

            var log = new MSBuildLogger(Log);

            log.LogDebug($"(in) RestoreGraphItems Count '{RestoreGraphItems?.Count() ?? 0}'");
            log.LogDebug($"(in) RestoreGraphOutputPath '{RestoreGraphOutputPath}'");
            log.LogDebug($"(in) RestoreRecursive '{RestoreRecursive}'");

            // Convert to the internal wrapper
            var wrappedItems = RestoreGraphItems.Select(GetMSBuildItem);

            // Create file
            var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems);

            // Add all child projects
            if (RestoreRecursive)
            {
                BuildTasksUtility.AddAllProjectsForRestore(dgFile);
            }

            var fileInfo = new FileInfo(RestoreGraphOutputPath);

            fileInfo.Directory.Create();

            // Save file
            log.LogMinimal($"Writing {fileInfo.FullName}");

            dgFile.Save(fileInfo.FullName);

            return(true);
        }
Ejemplo n.º 14
0
        private async Task <bool> ExecuteAsync(Common.ILogger log)
        {
            if (RestoreGraphItems.Length < 1)
            {
                log.LogWarning(Strings.NoProjectsProvidedToTask);
                return(true);
            }

            // Set user agent and connection settings.
            ConfigureProtocol();

            // Convert to the internal wrapper
            var wrappedItems = RestoreGraphItems.Select(MSBuildUtility.WrapMSBuildItem);

            //var graphLines = RestoreGraphItems;
            var providerCache = new RestoreCommandProvidersCache();

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache             = RestoreNoCache;
                cacheContext.IgnoreFailedSources = RestoreIgnoreFailedSources;

                // Pre-loaded request provider containing the graph file
                var providers = new List <IPreLoadedRestoreRequestProvider>();

                var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems);

                if (dgFile.Restore.Count < 1)
                {
                    // Restore will fail if given no inputs, but here we should skip it and provide a friendly message.
                    log.LogMinimal(Strings.NoProjectsToRestore);
                    return(true);
                }

                // Add all child projects
                if (RestoreRecursive)
                {
                    BuildTasksUtility.AddAllProjectsForRestore(dgFile);
                }

                providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dgFile));

                var defaultSettings = Settings.LoadDefaultSettings(root: null, configFileName: null, machineWideSettings: null);
                var sourceProvider  = new CachingSourceProvider(new PackageSourceProvider(defaultSettings));

                var restoreContext = new RestoreArgs()
                {
                    CacheContext         = cacheContext,
                    LockFileVersion      = LockFileFormat.Version,
                    ConfigFile           = MSBuildStringUtility.TrimAndGetNullForEmpty(RestoreConfigFile),
                    DisableParallel      = RestoreDisableParallel,
                    GlobalPackagesFolder = RestorePackagesPath,
                    Log = log,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    PreLoadedRequestProviders = providers,
                    CachingSourceProvider     = sourceProvider,
                    AllowNoOp             = !RestoreForce,
                    HideWarningsAndErrors = HideWarningsAndErrors
                };

                if (!string.IsNullOrEmpty(RestoreSources))
                {
                    var sources = MSBuildStringUtility.Split(RestoreSources);
                    restoreContext.Sources.AddRange(sources);
                }

                if (restoreContext.DisableParallel)
                {
                    HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                }

                _cts.Token.ThrowIfCancellationRequested();

                var restoreSummaries = await RestoreRunner.RunAsync(restoreContext, _cts.Token);

                // Summary
                RestoreSummary.Log(log, restoreSummaries);

                return(restoreSummaries.All(x => x.Success));
            }
        }
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            // Log Inputs
            BuildTasksUtility.LogInputParam(log, nameof(ProjectUniqueName), ProjectUniqueName);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSources), RestoreSources);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPath), RestorePackagesPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFolders), RestoreFallbackFolders);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreConfigFile), RestoreConfigFile);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSolutionDirectory), RestoreSolutionDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreAdditionalProjectSources), RestoreAdditionalProjectSources);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreAdditionalProjectFallbackFolders), RestoreAdditionalProjectFallbackFolders);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPathOverride), RestorePackagesPathOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSourcesOverride), RestoreSourcesOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFoldersOverride), RestoreFallbackFoldersOverride);

            try
            {
                // Validate inputs
                if (RestoreSourcesOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreSources, ProjectUniqueName, log))
                {
                    // Fail due to invalid source combination
                    return(false);
                }

                if (RestoreFallbackFoldersOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreFallbackFolders, ProjectUniqueName, log))
                {
                    // Fail due to invalid fallback combination
                    return(false);
                }

                // Settings
                var settings = RestoreSettingsUtils.ReadSettings(RestoreSolutionDirectory, Path.GetDirectoryName(ProjectUniqueName), RestoreConfigFile, _machineWideSettings);
                OutputConfigFilePaths = SettingsUtility.GetConfigFilePaths(settings).ToArray();

                // PackagesPath
                OutputPackagesPath = RestoreSettingsUtils.GetValue(
                    () => string.IsNullOrEmpty(RestorePackagesPathOverride) ? null : UriUtility.GetAbsolutePath(MSBuildStartupDirectory, RestorePackagesPathOverride),
                    () => string.IsNullOrEmpty(RestorePackagesPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestorePackagesPath),
                    () => SettingsUtility.GetGlobalPackagesFolder(settings));

                // Sources
                var currentSources = RestoreSettingsUtils.GetValue(
                    () => RestoreSourcesOverride?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => UriUtility.GetAbsolutePath(MSBuildStartupDirectory, e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreSources) ? new string[0] : null,
                    () => RestoreSources?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => (new PackageSourceProvider(settings)).LoadPackageSources().Select(e => e.Source).ToArray());

                // Append additional sources
                // Escape strings to avoid xplat path issues with msbuild.
                OutputSources = AppendItems(currentSources, RestoreAdditionalProjectSources?.Select(MSBuildRestoreUtility.FixSourcePath).ToArray());

                // Fallback folders
                var currentFallbackFolders = RestoreSettingsUtils.GetValue(
                    () => RestoreFallbackFoldersOverride?.Select(e => UriUtility.GetAbsolutePath(MSBuildStartupDirectory, e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreFallbackFolders) ? new string[0] : null,
                    () => RestoreFallbackFolders?.Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => SettingsUtility.GetFallbackPackageFolders(settings).ToArray());

                // Append additional fallback folders
                OutputFallbackFolders = AppendItems(currentFallbackFolders, RestoreAdditionalProjectFallbackFolders);
            }
            catch (Exception ex)
            {
                // Log exceptions with error codes if they exist.
                ExceptionUtilities.LogException(ex, log);
                return(false);
            }

            // Log Outputs
            BuildTasksUtility.LogOutputParam(log, nameof(OutputPackagesPath), OutputPackagesPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputSources), OutputSources);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputFallbackFolders), OutputFallbackFolders);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputConfigFilePaths), OutputConfigFilePaths);

            return(true);
        }
        public override bool Execute()
        {
            var log = new MSBuildLogger(Log);

            // Log Inputs
            BuildTasksUtility.LogInputParam(log, nameof(ProjectUniqueName), ProjectUniqueName);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSources), RestoreSources);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPath), RestorePackagesPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFolders), RestoreFallbackFolders);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreConfigFile), RestoreConfigFile);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSolutionDirectory), RestoreSolutionDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPathOverride), RestorePackagesPathOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSourcesOverride), RestoreSourcesOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFoldersOverride), RestoreFallbackFoldersOverride);
            BuildTasksUtility.LogInputParam(log, nameof(MSBuildStartupDirectory), MSBuildStartupDirectory);

            try
            {
                // Validate inputs
                if (RestoreSourcesOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreSources, ProjectUniqueName, log))
                {
                    // Fail due to invalid source combination
                    return(false);
                }

                if (RestoreFallbackFoldersOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreFallbackFolders, ProjectUniqueName, log))
                {
                    // Fail due to invalid fallback combination
                    return(false);
                }

                // Settings
                // Find the absolute path of nuget.config, this should only be set on the command line. Setting the path in project files
                // is something that could happen, but it is not supported.
                var absoluteConfigFilePath = GetGlobalAbsolutePath(RestoreConfigFile);
                var settings = RestoreSettingsUtils.ReadSettings(RestoreSolutionDirectory, Path.GetDirectoryName(ProjectUniqueName), absoluteConfigFilePath, _machineWideSettings);
                OutputConfigFilePaths = SettingsUtility.GetConfigFilePaths(settings).ToArray();

                // PackagesPath
                OutputPackagesPath = RestoreSettingsUtils.GetValue(
                    () => GetGlobalAbsolutePath(RestorePackagesPathOverride),
                    () => string.IsNullOrEmpty(RestorePackagesPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestorePackagesPath),
                    () => SettingsUtility.GetGlobalPackagesFolder(settings));

                // Sources
                var currentSources = RestoreSettingsUtils.GetValue(
                    () => RestoreSourcesOverride?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => GetGlobalAbsolutePath(e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreSources) ? new string[0] : null,
                    () => RestoreSources?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => (new PackageSourceProvider(settings)).LoadPackageSources().Where(e => e.IsEnabled).Select(e => e.Source).ToArray());

                // Append additional sources
                // Escape strings to avoid xplat path issues with msbuild.
                var additionalProjectSources = MSBuildRestoreUtility.AggregateSources(
                    values: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectSources"),
                    excludeValues: Enumerable.Empty <string>())
                                               .Select(MSBuildRestoreUtility.FixSourcePath)
                                               .ToArray();

                OutputSources = AppendItems(currentSources, additionalProjectSources);

                // Fallback folders
                var currentFallbackFolders = RestoreSettingsUtils.GetValue(
                    () => RestoreFallbackFoldersOverride?.Select(e => GetGlobalAbsolutePath(e)).ToArray(),
                    () => MSBuildRestoreUtility.ContainsClearKeyword(RestoreFallbackFolders) ? new string[0] : null,
                    () => RestoreFallbackFolders?.Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray(),
                    () => SettingsUtility.GetFallbackPackageFolders(settings).ToArray());

                // Append additional fallback folders after removing excluded folders
                var additionalProjectFallbackFolders = MSBuildRestoreUtility.AggregateSources(
                    values: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFolders"),
                    excludeValues: GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFoldersExcludes"))
                                                       .ToArray();

                OutputFallbackFolders = AppendItems(currentFallbackFolders, additionalProjectFallbackFolders);
            }
            catch (Exception ex)
            {
                // Log exceptions with error codes if they exist.
                ExceptionUtilities.LogException(ex, log);
                return(false);
            }

            // Log Outputs
            BuildTasksUtility.LogOutputParam(log, nameof(OutputPackagesPath), OutputPackagesPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputSources), OutputSources);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputFallbackFolders), OutputFallbackFolders);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputConfigFilePaths), OutputConfigFilePaths);

            return(true);
        }
Ejemplo n.º 17
0
        public override bool Execute()
        {
#if DEBUG
            var debugRestoreTask = Environment.GetEnvironmentVariable("DEBUG_RESTORE_SETTINGS_TASK");
            if (!string.IsNullOrEmpty(debugRestoreTask) && debugRestoreTask.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase))
            {
                System.Diagnostics.Debugger.Launch();
            }
#endif
            var log = new MSBuildLogger(Log);

            // Log Inputs
            BuildTasksUtility.LogInputParam(log, nameof(ProjectUniqueName), ProjectUniqueName);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSources), RestoreSources);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPath), RestorePackagesPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreRepositoryPath), RestoreRepositoryPath);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFolders), RestoreFallbackFolders);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreConfigFile), RestoreConfigFile);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSolutionDirectory), RestoreSolutionDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreRootConfigDirectory), RestoreRootConfigDirectory);
            BuildTasksUtility.LogInputParam(log, nameof(RestorePackagesPathOverride), RestorePackagesPathOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreSourcesOverride), RestoreSourcesOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreFallbackFoldersOverride), RestoreFallbackFoldersOverride);
            BuildTasksUtility.LogInputParam(log, nameof(RestoreProjectStyle), RestoreProjectStyle);
            BuildTasksUtility.LogInputParam(log, nameof(MSBuildStartupDirectory), MSBuildStartupDirectory);


            try
            {
                // Validate inputs
                if (RestoreSourcesOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreSources, ProjectUniqueName, log))
                {
                    // Fail due to invalid source combination
                    return(false);
                }

                if (RestoreFallbackFoldersOverride == null &&
                    MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreFallbackFolders, ProjectUniqueName, log))
                {
                    // Fail due to invalid fallback combination
                    return(false);
                }

                // Settings
                // Find the absolute path of nuget.config, this should only be set on the command line. Setting the path in project files
                // is something that could happen, but it is not supported.
                var    absoluteConfigFilePath = GetGlobalAbsolutePath(RestoreConfigFile);
                string restoreDir;
                // To match non-msbuild behavior, we only default the restoreDir for non-PackagesConfig scenarios.
                if (string.IsNullOrEmpty(RestoreRootConfigDirectory))
                {
                    restoreDir = Path.GetDirectoryName(ProjectUniqueName);
                }
                else
                {
                    restoreDir = RestoreRootConfigDirectory;
                }
                var settings = RestoreSettingsUtils.ReadSettings(RestoreSolutionDirectory, restoreDir, absoluteConfigFilePath, _machineWideSettings);
                OutputConfigFilePaths = settings.GetConfigFilePaths().ToArray();

                // PackagesPath
                OutputPackagesPath = RestoreSettingsUtils.GetValue(
                    () => GetGlobalAbsolutePath(RestorePackagesPathOverride),
                    () => string.IsNullOrEmpty(RestorePackagesPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestorePackagesPath),
                    () => SettingsUtility.GetGlobalPackagesFolder(settings));

                OutputRepositoryPath = RestoreSettingsUtils.GetValue(
                    () => GetGlobalAbsolutePath(RestoreRepositoryPathOverride),
                    () => string.IsNullOrEmpty(RestoreRepositoryPath) ? null : UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, RestoreRepositoryPath),
                    () => SettingsUtility.GetRepositoryPath(settings));

                // Sources
                OutputSources = BuildTasksUtility.GetSources(
                    MSBuildStartupDirectory,
                    Path.GetDirectoryName(ProjectUniqueName),
                    RestoreSources,
                    RestoreSourcesOverride,
                    GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectSources"),
                    settings);

                // Fallback folders
                OutputFallbackFolders = BuildTasksUtility.GetFallbackFolders(
                    MSBuildStartupDirectory,
                    Path.GetDirectoryName(ProjectUniqueName),
                    RestoreFallbackFolders, RestoreFallbackFoldersOverride,
                    GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFolders"),
                    GetPropertyValues(RestoreSettingsPerFramework, "RestoreAdditionalProjectFallbackFoldersExcludes"),
                    settings);
            }
            catch (Exception ex)
            {
                // Log exceptions with error codes if they exist.
                ExceptionUtilities.LogException(ex, log);
                return(false);
            }

            // Log Outputs
            BuildTasksUtility.LogOutputParam(log, nameof(OutputPackagesPath), OutputPackagesPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputRepositoryPath), OutputRepositoryPath);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputSources), OutputSources);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputFallbackFolders), OutputFallbackFolders);
            BuildTasksUtility.LogOutputParam(log, nameof(OutputConfigFilePaths), OutputConfigFilePaths);

            return(true);
        }
Ejemplo n.º 18
0
        private async Task <bool> ExecuteAsync(Common.ILogger log)
        {
            if (RestoreGraphItems.Length < 1 && !HideWarningsAndErrors)
            {
                log.LogWarning(Strings.NoProjectsProvidedToTask);
                return(true);
            }

            // Set user agent and connection settings.
            ConfigureProtocol();

            // Convert to the internal wrapper
            var wrappedItems = RestoreGraphItems.Select(MSBuildUtility.WrapMSBuildItem);

            //var graphLines = RestoreGraphItems;
            var providerCache = new RestoreCommandProvidersCache();

            using (var cacheContext = new SourceCacheContext())
            {
                cacheContext.NoCache             = RestoreNoCache;
                cacheContext.IgnoreFailedSources = RestoreIgnoreFailedSources;

                // Pre-loaded request provider containing the graph file
                var providers = new List <IPreLoadedRestoreRequestProvider>();

                var dgFile = MSBuildRestoreUtility.GetDependencySpec(wrappedItems);

                if (dgFile.Restore.Count < 1)
                {
                    // Restore will fail if given no inputs, but here we should skip it and provide a friendly message.
                    log.LogMinimal(Strings.NoProjectsToRestore);
                    return(true);
                }

                // Add all child projects
                if (RestoreRecursive)
                {
                    BuildTasksUtility.AddAllProjectsForRestore(dgFile);
                }

                providers.Add(new DependencyGraphSpecRequestProvider(providerCache, dgFile));

                var restoreContext = new RestoreArgs()
                {
                    CacheContext              = cacheContext,
                    LockFileVersion           = LockFileFormat.Version,
                    DisableParallel           = RestoreDisableParallel,
                    Log                       = log,
                    MachineWideSettings       = new XPlatMachineWideSetting(),
                    PreLoadedRequestProviders = providers,
                    AllowNoOp                 = !RestoreForce,
                    HideWarningsAndErrors     = HideWarningsAndErrors,
                    RestoreForceEvaluate      = RestoreForceEvaluate
                };

                // 'dotnet restore' fails on slow machines (https://github.com/NuGet/Home/issues/6742)
                // The workaround is to pass the '--disable-parallel' option.
                // We apply the workaround by default when the system has 1 cpu.
                // This will fix restore failures on VMs with 1 CPU and containers with less or equal to 1 CPU assigned.
                if (Environment.ProcessorCount == 1)
                {
                    restoreContext.DisableParallel = true;
                }

                if (restoreContext.DisableParallel)
                {
                    HttpSourceResourceProvider.Throttle = SemaphoreSlimThrottle.CreateBinarySemaphore();
                }

                _cts.Token.ThrowIfCancellationRequested();

                var restoreSummaries = await RestoreRunner.RunAsync(restoreContext, _cts.Token);

                // Summary
                RestoreSummary.Log(log, restoreSummaries);

                return(restoreSummaries.All(x => x.Success));
            }
        }