예제 #1
0
 static void HandleClear(List <string> values)
 {
     if (MSBuildRestoreUtility.ContainsClearKeyword(values))
     {
         values.Clear();
     }
 }
예제 #2
0
        static Tuple <List <NuGetFramework>, ProjectRestoreReference> GetProjectRestoreReference(
            ProjectReference item,
            IDotNetProject project,
            ILogger logger)
        {
            var frameworks = GetFrameworks(project).ToList();

            var referencedProject = project.ParentSolution.ResolveProject(item);

            if (referencedProject == null)
            {
                logger.LogWarning(GettextCatalog.GetString("WARNING: Unable to resolve project '{0}' referenced by '{1}'.", item.Include, project.Name));
                return(null);
            }

            var reference = new ProjectRestoreReference()
            {
                ProjectPath       = referencedProject.FileName,
                ProjectUniqueName = referencedProject.FileName,
            };

            MSBuildRestoreUtility.ApplyIncludeFlags(
                reference,
                item.Metadata.GetValue("IncludeAssets"),
                item.Metadata.GetValue("ExcludeAssets"),
                item.Metadata.GetValue("PrivateAssets"));

            return(new Tuple <List <NuGetFramework>, ProjectRestoreReference> (frameworks, reference));
        }
        private static LibraryDependency ToPackageLibraryDependency(PackageReference reference, bool isCpvmEnabled)
        {
            var dependency = new LibraryDependency
            {
                AutoReferenced       = MSBuildStringUtility.IsTrue(GetReferenceMetadataValue(reference, ProjectItemProperties.IsImplicitlyDefined)),
                GeneratePathProperty = MSBuildStringUtility.IsTrue(GetReferenceMetadataValue(reference, ProjectItemProperties.GeneratePathProperty)),
                Aliases      = GetReferenceMetadataValue(reference, ProjectItemProperties.Aliases, defaultValue: null),
                LibraryRange = new LibraryRange(
                    name: reference.Name,
                    versionRange: ToVersionRange(reference.Version, isCpvmEnabled),
                    typeConstraint: LibraryDependencyTarget.Package)
            };

            MSBuildRestoreUtility.ApplyIncludeFlags(
                dependency,
                GetReferenceMetadataValue(reference, ProjectItemProperties.IncludeAssets),
                GetReferenceMetadataValue(reference, ProjectItemProperties.ExcludeAssets),
                GetReferenceMetadataValue(reference, ProjectItemProperties.PrivateAssets));


            // Add warning suppressions
            foreach (var code in MSBuildStringUtility.GetNuGetLogCodes(GetReferenceMetadataValue(reference, ProjectItemProperties.NoWarn)))
            {
                dependency.NoWarn.Add(code);
            }

            return(dependency);
        }
예제 #4
0
        private static LibraryDependency ToPackageLibraryDependency(IVsReferenceItem item)
        {
            var dependency = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    name: item.Name,
                    versionRange: GetVersionRange(item),
                    typeConstraint: LibraryDependencyTarget.Package),

                // Mark packages coming from the SDK as AutoReferenced
                AutoReferenced = GetPropertyBoolOrFalse(item, "IsImplicitlyDefined"),
            };

            // Add warning suppressions
            foreach (var code in MSBuildStringUtility.GetNuGetLogCodes(GetPropertyValueOrNull(item, NoWarn)))
            {
                dependency.NoWarn.Add(code);
            }

            MSBuildRestoreUtility.ApplyIncludeFlags(
                dependency,
                includeAssets: GetPropertyValueOrNull(item, IncludeAssets),
                excludeAssets: GetPropertyValueOrNull(item, ExcludeAssets),
                privateAssets: GetPropertyValueOrNull(item, PrivateAssets));

            return(dependency);
        }
예제 #5
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));
        }
예제 #6
0
        private static LibraryDependency ToPackageLibraryDependency(IVsReferenceItem item, bool cpvmEnabled)
        {
            if (!TryGetVersionRange(item, out VersionRange versionRange))
            {
                versionRange = cpvmEnabled ? null : VersionRange.All;
            }

            var dependency = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    name: item.Name,
                    versionRange: versionRange,
                    typeConstraint: LibraryDependencyTarget.Package),

                // Mark packages coming from the SDK as AutoReferenced
                AutoReferenced       = GetPropertyBoolOrFalse(item, "IsImplicitlyDefined"),
                GeneratePathProperty = GetPropertyBoolOrFalse(item, "GeneratePathProperty"),
                Aliases = GetPropertyValueOrNull(item, "Aliases"),
            };

            // Add warning suppressions
            foreach (var code in MSBuildStringUtility.GetNuGetLogCodes(GetPropertyValueOrNull(item, ProjectBuildProperties.NoWarn)))
            {
                dependency.NoWarn.Add(code);
            }

            MSBuildRestoreUtility.ApplyIncludeFlags(
                dependency,
                includeAssets: GetPropertyValueOrNull(item, ProjectBuildProperties.IncludeAssets),
                excludeAssets: GetPropertyValueOrNull(item, ProjectBuildProperties.ExcludeAssets),
                privateAssets: GetPropertyValueOrNull(item, ProjectBuildProperties.PrivateAssets));

            return(dependency);
        }
예제 #7
0
 static void HandleClear(List <PackageSource> sources)
 {
     if (MSBuildRestoreUtility.ContainsClearKeyword(sources.Select(source => source.Source)))
     {
         sources.Clear();
     }
 }
        private static LibraryDependency ToPackageLibraryDependency(PackageReference reference)
        {
            var dependency = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    name: reference.Name,
                    versionRange: VersionRange.Parse(reference.Version),
                    typeConstraint: LibraryDependencyTarget.Package)
            };

            MSBuildRestoreUtility.ApplyIncludeFlags(
                dependency,
                GetReferenceMetadataValue(reference, ProjectItemProperties.IncludeAssets),
                GetReferenceMetadataValue(reference, ProjectItemProperties.ExcludeAssets),
                GetReferenceMetadataValue(reference, ProjectItemProperties.PrivateAssets));

            dependency.AutoReferenced = MSBuildStringUtility.IsTrue(GetReferenceMetadataValue(reference, ProjectItemProperties.IsImplicitlyDefined));

            // Add warning suppressions
            foreach (var code in MSBuildRestoreUtility.GetNuGetLogCodes(GetReferenceMetadataValue(reference, ProjectItemProperties.NoWarn)))
            {
                dependency.NoWarn.Add(code);
            }

            return(dependency);
        }
예제 #9
0
 static void ApplyIncludeFlags(LibraryDependency dependency, ProjectPackageReference packageReference)
 {
     MSBuildRestoreUtility.ApplyIncludeFlags(
         dependency,
         packageReference.Metadata.GetValue("IncludeAssets"),
         packageReference.Metadata.GetValue("ExcludeAssets"),
         packageReference.Metadata.GetValue("PrivateAssets"));
 }
예제 #10
0
 static WarningProperties GetWarningProperties(IDotNetProject project)
 {
     return(MSBuildRestoreUtility.GetWarningProperties(
                project.EvaluatedProperties.GetValue("TreatWarningsAsErrors"),
                project.EvaluatedProperties.GetValue("WarningsAsErrors"),
                project.EvaluatedProperties.GetValue("NoWarn")
                ));
 }
        public void DependencyNodeEqualityFails_NodesHaveDifferentProjectWideWarningProperties(
            string firstNoWarn,
            string secondNoWarn)
        {
            // Arrange
            var packageId1 = "test_id1";
            var packageId2 = "test_id2";

            // Arrange
            var firstProjectWideNoWarn     = new HashSet <NuGetLogCode>(MSBuildRestoreUtility.GetNuGetLogCodes(firstNoWarn));
            var firstPackageSpecificNoWarn = new Dictionary <string, HashSet <NuGetLogCode> >
            {
                { packageId1, new HashSet <NuGetLogCode> {
                      NuGetLogCode.NU1601, NuGetLogCode.NU1108
                  } },
                { packageId2, new HashSet <NuGetLogCode> {
                      NuGetLogCode.NU1601, NuGetLogCode.NU1701
                  } }
            };

            var secondProjectWideNoWarn     = new HashSet <NuGetLogCode>(MSBuildRestoreUtility.GetNuGetLogCodes(secondNoWarn));
            var secondPackageSpecificNoWarn = new Dictionary <string, HashSet <NuGetLogCode> >
            {
                { packageId1, new HashSet <NuGetLogCode> {
                      NuGetLogCode.NU1601, NuGetLogCode.NU1108
                  } },
                { packageId2, new HashSet <NuGetLogCode> {
                      NuGetLogCode.NU1601, NuGetLogCode.NU1701
                  } }
            };

            var first = new TransitiveNoWarnUtils.DependencyNode(
                id: "test",
                isProject: true,
                nodeWarningProperties: new TransitiveNoWarnUtils.NodeWarningProperties(
                    firstProjectWideNoWarn,
                    firstPackageSpecificNoWarn
                    ));

            var second = new TransitiveNoWarnUtils.DependencyNode(
                id: "test",
                isProject: true,
                nodeWarningProperties: new TransitiveNoWarnUtils.NodeWarningProperties(
                    secondProjectWideNoWarn,
                    secondPackageSpecificNoWarn
                    ));

            // Act
            var seen = new HashSet <TransitiveNoWarnUtils.DependencyNode>
            {
                first,
                second
            };

            // Assert
            seen.Count.Should().Be(2);
        }
예제 #12
0
        public static IEnumerable <string> HandleClear(IEnumerable <string> values)
        {
            if ((MSBuildRestoreUtility.ContainsClearKeyword(values)))
            {
                return(Enumerable.Empty <string>());
            }

            return(values);
        }
예제 #13
0
        /// <summary>
        /// The result will contain CLEAR and no sources specified in RestoreSources if the clear keyword is in it.
        /// If there are additional sources specified, the value AdditionalValue will be set in the result and then all the additional sources will follow
        /// </summary>
        internal static IEnumerable <string> GetRestoreSources(IEnumerable values)
        {
            var sources = HandleClear(MSBuildStringUtility.Split(GetSingleNonEvaluatedPropertyOrNull(values, ProjectBuildProperties.RestoreSources, e => e)));

            // Read RestoreAdditionalProjectSources from the inner build, these may be different between frameworks.
            // Exclude is not allowed for sources
            var additional = MSBuildRestoreUtility.AggregateSources(
                values: GetAggregatePropertyValues(values, ProjectBuildProperties.RestoreAdditionalProjectSources),
                excludeValues: Enumerable.Empty <string>());

            return(VSRestoreSettingsUtilities.GetEntriesWithAdditional(sources, additional.ToArray()));
        }
예제 #14
0
        /// <summary>
        /// The result will contain CLEAR and no sources specified in RestoreFallbackFolders if the clear keyword is in it.
        /// If there are additional fallback folders specified, the value AdditionalValue will be set in the result and then all the additional fallback folders will follow
        /// </summary>
        internal static IEnumerable <string> GetRestoreFallbackFolders(IEnumerable tfms)
        {
            var folders = HandleClear(MSBuildStringUtility.Split(GetSingleNonEvaluatedPropertyOrNull(tfms, ProjectBuildProperties.RestoreFallbackFolders, e => e)));

            // Read RestoreAdditionalProjectFallbackFolders from the inner build.
            // Remove all excluded fallback folders listed in RestoreAdditionalProjectFallbackFoldersExcludes.
            var additional = MSBuildRestoreUtility.AggregateSources(
                values: GetAggregatePropertyValues(tfms, ProjectBuildProperties.RestoreAdditionalProjectFallbackFolders),
                excludeValues: GetAggregatePropertyValues(tfms, ProjectBuildProperties.RestoreAdditionalProjectFallbackFoldersExcludes));

            return(VSRestoreSettingsUtilities.GetEntriesWithAdditional(folders, additional.ToArray()));
        }
예제 #15
0
        private static ProjectRestoreReference ToProjectRestoreReference(LegacyCSProjProjectReference item)
        {
            var reference = new ProjectRestoreReference()
            {
                ProjectUniqueName = item.UniqueName,
                ProjectPath       = item.UniqueName
            };

            MSBuildRestoreUtility.ApplyIncludeFlags(
                reference,
                GetProjectMetadataValue(item, _includeAssets),
                GetProjectMetadataValue(item, _excludeAssets),
                GetProjectMetadataValue(item, _privateAssets));

            return(reference);
        }
예제 #16
0
        /// <summary>
        /// Gets the package fallback folders for a project.
        /// </summary>
        /// <param name="startupDirectory">The start-up directory of the tool.</param>
        /// <param name="projectDirectory">The full path to the directory of the project.</param>
        /// <param name="fallbackFolders">A <see cref="T:string[]" /> containing the fallback folders for the project.</param>
        /// <param name="fallbackFoldersOverride">A <see cref="T:string[]" /> containing overrides for the fallback folders for the project.</param>
        /// <param name="additionalProjectFallbackFolders">An <see cref="IEnumerable{String}" /> containing additional fallback folders for the project.</param>
        /// <param name="additionalProjectFallbackFoldersExcludes">An <see cref="IEnumerable{String}" /> containing fallback folders to exclude.</param>
        /// <param name="settings">An <see cref="ISettings" /> object containing settings for the project.</param>
        /// <returns>A <see cref="T:string[]" /> containing the package fallback folders for the project.</returns>
        public static string[] GetFallbackFolders(string startupDirectory, string projectDirectory, string[] fallbackFolders, string[] fallbackFoldersOverride, IEnumerable <string> additionalProjectFallbackFolders, IEnumerable <string> additionalProjectFallbackFoldersExcludes, ISettings settings)
        {
            // Fallback folders
            var currentFallbackFolders = RestoreSettingsUtils.GetValue(
                () => fallbackFoldersOverride?.Select(e => UriUtility.GetAbsolutePath(startupDirectory, e)).ToArray(),
                () => MSBuildRestoreUtility.ContainsClearKeyword(fallbackFolders) ? Array.Empty <string>() : null,
                () => fallbackFolders?.Select(e => UriUtility.GetAbsolutePath(projectDirectory, e)).ToArray(),
                () => SettingsUtility.GetFallbackPackageFolders(settings).ToArray());

            // Append additional fallback folders after removing excluded folders
            var filteredAdditionalProjectFallbackFolders = MSBuildRestoreUtility.AggregateSources(
                values: additionalProjectFallbackFolders,
                excludeValues: additionalProjectFallbackFoldersExcludes);

            return(AppendItems(projectDirectory, currentFallbackFolders, filteredAdditionalProjectFallbackFolders));
        }
        private static ProjectRestoreReference ToProjectRestoreReference(ProjectReference item)
        {
            var reference = new ProjectRestoreReference
            {
                ProjectUniqueName = item.UniqueName,
                ProjectPath       = item.UniqueName
            };

            MSBuildRestoreUtility.ApplyIncludeFlags(
                reference,
                GetReferenceMetadataValue(item, ProjectItemProperties.IncludeAssets),
                GetReferenceMetadataValue(item, ProjectItemProperties.ExcludeAssets),
                GetReferenceMetadataValue(item, ProjectItemProperties.PrivateAssets));

            return(reference);
        }
예제 #18
0
        private static LibraryDependency ToPackageLibraryDependency(LegacyCSProjPackageReference item)
        {
            var dependency = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    name: item.Name,
                    versionRange: new VersionRange(new NuGetVersion(item.Version), originalString: item.Version),
                    typeConstraint: LibraryDependencyTarget.Package)
            };

            MSBuildRestoreUtility.ApplyIncludeFlags(
                dependency,
                GetPackageMetadataValue(item, _includeAssets),
                GetPackageMetadataValue(item, _excludeAssets),
                GetPackageMetadataValue(item, _privateAssets));

            return(dependency);
        }
        private static LibraryDependency ToPackageLibraryDependency(MSBuildProjectItemData item)
        {
            var dependency = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    name: item.EvaluatedInclude,
                    versionRange: GetVersionRange(item),
                    typeConstraint: LibraryDependencyTarget.Package)
            };

            MSBuildRestoreUtility.ApplyIncludeFlags(
                dependency,
                GetItemMetadataValueOrDefault(item, ProjectItemProperties.IncludeAssets),
                GetItemMetadataValueOrDefault(item, ProjectItemProperties.ExcludeAssets),
                GetItemMetadataValueOrDefault(item, ProjectItemProperties.PrivateAssets));

            return(dependency);
        }
예제 #20
0
        public static string[] GetSources(string startupDirectory, string projectDirectory, string[] sources, string[] sourcesOverride, IEnumerable <string> additionalProjectSources, ISettings settings)
        {
            // Sources
            var currentSources = RestoreSettingsUtils.GetValue(
                () => sourcesOverride?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => UriUtility.GetAbsolutePath(startupDirectory, e)).ToArray(),
                () => MSBuildRestoreUtility.ContainsClearKeyword(sources) ? Array.Empty <string>() : null,
                () => sources?.Select(MSBuildRestoreUtility.FixSourcePath).Select(e => UriUtility.GetAbsolutePath(projectDirectory, e)).ToArray(),
                () => (PackageSourceProvider.LoadPackageSources(settings)).Where(e => e.IsEnabled).Select(e => e.Source).ToArray());

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

            return(AppendItems(projectDirectory, currentSources, filteredAdditionalProjectSources));
        }
예제 #21
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);
        }
        public void MergeProjectWideWarningProperties_MergesNonEmptyCollections(
            string firstNoWarn,
            string secondNoWarn,
            string expectedNoWarn)
        {
            // Arrange
            var first = new HashSet <NuGetLogCode>(MSBuildRestoreUtility.GetNuGetLogCodes(firstNoWarn));

            var second = new HashSet <NuGetLogCode>(MSBuildRestoreUtility.GetNuGetLogCodes(secondNoWarn));

            var expected = new HashSet <NuGetLogCode>(MSBuildRestoreUtility.GetNuGetLogCodes(expectedNoWarn));

            // Act
            var merged = TransitiveNoWarnUtils.MergeCodes(first, second);

            // Assert
            merged.Should().NotBeNull();
            merged.ShouldBeEquivalentTo(expected);
        }
예제 #23
0
        private static ProjectRestoreReference ToProjectRestoreReference(MSBuildProjectItemData item, string projectDirectory)
        {
            var referencePath = Path.GetFullPath(
                Path.Combine(
                    projectDirectory, item.EvaluatedInclude));

            var reference = new ProjectRestoreReference()
            {
                ProjectUniqueName = referencePath,
                ProjectPath       = referencePath
            };

            MSBuildRestoreUtility.ApplyIncludeFlags(
                reference,
                includeAssets: GetPropertyValueOrDefault(item, IncludeAssets),
                excludeAssets: GetPropertyValueOrDefault(item, ExcludeAssets),
                privateAssets: GetPropertyValueOrDefault(item, PrivateAssets));

            return(reference);
        }
        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);
        }
예제 #25
0
        private static ProjectRestoreReference ToProjectRestoreReference(IVsReferenceItem item, string projectDirectory)
        {
            // The path may be a relative path, to match the project unique name as a
            // string this should be the full path to the project
            // Remove ../../ and any other relative parts of the path that were used in the project file
            var referencePath = Path.GetFullPath(Path.Combine(projectDirectory, item.Name));

            var dependency = new ProjectRestoreReference
            {
                ProjectPath       = referencePath,
                ProjectUniqueName = referencePath,
            };

            MSBuildRestoreUtility.ApplyIncludeFlags(
                dependency,
                includeAssets: GetPropertyValueOrNull(item, ProjectBuildProperties.IncludeAssets),
                excludeAssets: GetPropertyValueOrNull(item, ProjectBuildProperties.ExcludeAssets),
                privateAssets: GetPropertyValueOrNull(item, ProjectBuildProperties.PrivateAssets));

            return(dependency);
        }
        private static LibraryDependency ToPackageLibraryDependency(IVsReferenceItem item)
        {
            var dependency = new LibraryDependency
            {
                LibraryRange = new LibraryRange(
                    name: item.Name,
                    versionRange: GetVersionRange(item),
                    typeConstraint: LibraryDependencyTarget.Package),

                // Mark packages coming from the SDK as AutoReferenced
                AutoReferenced = GetPropertyBoolOrFalse(item, "IsImplicitlyDefined")
            };

            MSBuildRestoreUtility.ApplyIncludeFlags(
                dependency,
                includeAssets: GetPropertyValueOrNull(item, IncludeAssets),
                excludeAssets: GetPropertyValueOrNull(item, ExcludeAssets),
                privateAssets: GetPropertyValueOrNull(item, PrivateAssets));

            return(dependency);
        }
예제 #27
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);
        }
예제 #28
0
        public override bool Execute()
        {
            // Log Inputs
            var log = new MSBuildLogger(Log);

            log.LogDebug($"(in) ProjectUniqueName '{ProjectUniqueName}'");
            if (RestoreSources != null)
            {
                log.LogDebug($"(in) RestoreSources '{string.Join(";", RestoreSources.Select(p => p))}'");
            }
            if (RestorePackagesPath != null)
            {
                log.LogDebug($"(in) RestorePackagesPath '{RestorePackagesPath}'");
            }
            if (RestoreFallbackFolders != null)
            {
                log.LogDebug($"(in) RestoreFallbackFolders '{string.Join(";", RestoreFallbackFolders.Select(p => p))}'");
            }
            if (RestoreConfigFile != null)
            {
                log.LogDebug($"(in) RestoreConfigFile '{RestoreConfigFile}'");
            }

            if (RestoreSolutionDirectory != null)
            {
                log.LogDebug($"(in) RestoreSolutionDirectory '{RestoreSolutionDirectory}'");
            }

            if (RestoreAdditionalProjectSources != null)
            {
                log.LogDebug($"(in) RestoreAdditionalProjectSources '{RestoreAdditionalProjectSources}'");
            }

            if (RestoreAdditionalProjectFallbackFolders != null)
            {
                log.LogDebug($"(in) RestoreAdditionalProjectFallbackFolders '{RestoreAdditionalProjectFallbackFolders}'");
            }

            try
            {
                var settings = RestoreSettingsUtils.ReadSettings(RestoreSolutionDirectory, Path.GetDirectoryName(ProjectUniqueName), RestoreConfigFile, _machineWideSettings);

                OutputPackagesPath = RestoreSettingsUtils.GetPackagesPath(ProjectUniqueName, settings, RestorePackagesPath);

                if (RestoreSources == null)
                {
                    var packageSourceProvider      = new PackageSourceProvider(settings);
                    var packageSourcesFromProvider = packageSourceProvider.LoadPackageSources();
                    OutputSources = packageSourcesFromProvider.Select(e => e.Source).ToArray();
                }
                else if (MSBuildRestoreUtility.ContainsClearKeyword(RestoreSources))
                {
                    if (MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreSources, ProjectUniqueName, log))
                    {
                        // Fail due to invalid combination
                        return(false);
                    }

                    OutputSources = new string[] { };
                }
                else
                {
                    // Relative -> Absolute paths
                    OutputSources = RestoreSources.Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray();
                }

                // Append additional sources
                OutputSources = AppendItems(OutputSources, RestoreAdditionalProjectSources);

                if (RestoreFallbackFolders == null)
                {
                    OutputFallbackFolders = SettingsUtility.GetFallbackPackageFolders(settings).ToArray();
                }
                else if (MSBuildRestoreUtility.ContainsClearKeyword(RestoreFallbackFolders))
                {
                    if (MSBuildRestoreUtility.LogErrorForClearIfInvalid(RestoreFallbackFolders, ProjectUniqueName, log))
                    {
                        // Fail due to invalid combination
                        return(false);
                    }

                    OutputFallbackFolders = new string[] { };
                }
                else
                {
                    // Relative -> Absolute paths
                    OutputFallbackFolders = RestoreFallbackFolders.Select(e => UriUtility.GetAbsolutePathFromFile(ProjectUniqueName, e)).ToArray();
                }

                // Append additional fallback folders
                OutputFallbackFolders = AppendItems(OutputFallbackFolders, RestoreAdditionalProjectFallbackFolders);

                OutputConfigFilePaths = SettingsUtility.GetConfigFilePaths(settings).ToArray();
            }
            catch (Exception ex)
            {
                // Log exceptions with error codes if they exist.
                ExceptionUtilities.LogException(ex, log);
                return(false);
            }

            // Log Outputs
            log.LogDebug($"(out) OutputPackagesPath '{OutputPackagesPath}'");
            log.LogDebug($"(out) OutputSources '{string.Join(";", OutputSources.Select(p => p))}'");
            log.LogDebug($"(out) OutputFallbackFolders '{string.Join(";", OutputFallbackFolders.Select(p => p))}'");
            log.LogDebug($"(out) OutputConfigFilePaths '{string.Join(";", OutputConfigFilePaths.Select(p => p))}'");

            return(true);
        }
        /// <summary>
        /// Gets a <see cref="DependencyGraphSpec" /> for the specified project.
        /// </summary>
        /// <param name="entryProjectPath">The full path to a project or Visual Studio Solution File.</param>
        /// <param name="globalProperties">An <see cref="IDictionary{String,String}" /> containing the global properties to use when evaluation MSBuild projects.</param>
        /// <returns>A <see cref="DependencyGraphSpec" /> for the specified project if they could be loaded, otherwise <code>null</code>.</returns>
        private DependencyGraphSpec GetDependencyGraphSpec(string entryProjectPath, IDictionary <string, string> globalProperties)
        {
            try
            {
                // TODO: Use a localized resource from https://github.com/NuGet/NuGet.Client/pull/3111
                MSBuildLogger.LogMinimal("Determining projects to restore...");

                var entryProjects = GetProjectGraphEntryPoints(entryProjectPath, globalProperties);

                // Load the projects via MSBuild and create an array of them since Parallel.ForEach is optimized for arrays
                var projects = LoadProjects(entryProjects)?.ToArray();

                // If no projects were loaded, return null indicating that the projects could not be loaded.
                if (projects == null || projects.Length == 0)
                {
                    return(null);
                }

                var sw = Stopwatch.StartNew();

                var dependencyGraphSpec = new DependencyGraphSpec(isReadOnly: true);

                // Unique names created by the MSBuild restore target are project paths, these
                // can be different on case-insensitive file systems for the same project file.
                // To workaround this unique names should be compared based on the OS.
                var uniqueNameComparer = PathUtility.GetStringComparerBasedOnOS();
                var projectPathLookup  = new ConcurrentDictionary <string, string>(uniqueNameComparer);

                try
                {
                    // Get the PackageSpecs in parallel because creating each one is relatively expensive so parallelism speeds things up
                    Parallel.ForEach(projects, new ParallelOptions {
                        MaxDegreeOfParallelism = Environment.ProcessorCount
                    }, project =>
                    {
                        var packageSpec = GetPackageSpec(project.OuterProject, project);

                        if (packageSpec != null)
                        {
                            // Keep track of all project path casings
                            var uniqueName = packageSpec.RestoreMetadata.ProjectUniqueName;
                            if (uniqueName != null && !projectPathLookup.ContainsKey(uniqueName))
                            {
                                projectPathLookup.TryAdd(uniqueName, uniqueName);
                            }

                            var projectPath = packageSpec.RestoreMetadata.ProjectPath;
                            if (projectPath != null && !projectPathLookup.ContainsKey(projectPath))
                            {
                                projectPathLookup.TryAdd(projectPath, projectPath);
                            }

                            // TODO: Remove this lock once https://github.com/NuGet/Home/issues/9002 is fixed
                            lock (dependencyGraphSpec)
                            {
                                dependencyGraphSpec.AddProject(packageSpec);
                            }
                        }
                    });
                }
                catch (AggregateException e)
                {
                    // Log exceptions thrown while creating PackageSpec objects
                    foreach (var exception in e.Flatten().InnerExceptions)
                    {
                        LoggingQueue.TaskLoggingHelper.LogErrorFromException(exception);
                    }

                    return(null);
                }

                // Fix project reference casings to match the original project on case insensitive file systems.
                MSBuildRestoreUtility.NormalizePathCasings(projectPathLookup, dependencyGraphSpec);

                // Add all entry projects if they support restore.  In most cases this is just a single project but if the entry
                // project is a solution, then all projects in the solution are added (if they support restore)
                foreach (var entryPoint in entryProjects)
                {
                    PackageSpec project = dependencyGraphSpec.GetProjectSpec(entryPoint.ProjectFile);

                    if (project != null && BuildTasksUtility.DoesProjectSupportRestore(project))
                    {
                        dependencyGraphSpec.AddRestore(entryPoint.ProjectFile);
                    }
                }

                sw.Stop();

                MSBuildLogger.LogDebug(string.Format(CultureInfo.CurrentCulture, Strings.CreatedDependencyGraphSpec, sw.ElapsedMilliseconds));

                return(dependencyGraphSpec);
            }
            catch (Exception e)
            {
                LoggingQueue.TaskLoggingHelper.LogErrorFromException(e, showStackTrace: true);
            }

            return(null);
        }
예제 #30
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));
            }
        }