/// <summary>
        /// Returns the PackageSource with its credentials if available
        /// </summary>
        /// <param name="requestedSources">Sources to match</param>
        /// <param name="configFilePaths">Config to use for credentials</param>
        /// <returns>Return a list of package sources</returns>
        public static List <PackageSource> EvaluateSources(IList <PackageSource> requestedSources, IList <string> configFilePaths)
        {
            using (var settingsLoadingContext = new SettingsLoadingContext())
            {
                ISettings settings       = Settings.LoadImmutableSettingsGivenConfigPaths(configFilePaths, settingsLoadingContext);
                var       packageSources = new List <PackageSource>();

                var packageSourceProvider = new PackageSourceProvider(settings);
                IEnumerable <PackageSource> packageProviderSources = packageSourceProvider.LoadPackageSources();

                for (int i = 0; i < requestedSources.Count; i++)
                {
                    PackageSource matchedSource = packageProviderSources.FirstOrDefault(e => e.Source == requestedSources[i].Source);
                    if (matchedSource == null)
                    {
                        packageSources.Add(requestedSources[i]);
                    }
                    else
                    {
                        packageSources.Add(matchedSource);
                    }
                }

                return(packageSources);
            }
        }
Exemplo n.º 2
0
        public void EvaluateSources_GivenConfigWithCredentials_ReturnsPackageSourceWithCredentials()
        {
            using (var mockBaseDirectory = TestDirectory.Create())
            {
                List <PackageSource> source = new List <PackageSource>()
                {
                    new PackageSource("https://contoso.org/v3/index.json"), new PackageSource("b")
                };

                var nugetConfigFileName = "NuGet.Config";
                var config = @"<?xml version=""1.0"" encoding=""utf-8""?>
                            <configuration>
                                <packageSources>
                                    <add key=""Contoso"" value=""https://contoso.org/v3/index.json"" />
                                    <add key=""b"" value =""b"" />
                                </packageSources>
                                <packageSourceCredentials>
                                    <Contoso>
                                        <add key=""Username"" value=""user @contoso.com"" />
                                        <add key=""Password"" value=""..."" />
                                    </Contoso>
                                </packageSourceCredentials>
                            </configuration>";

                var configPath = Path.Combine(mockBaseDirectory, nugetConfigFileName);
                SettingsTestUtils.CreateConfigurationFile(nugetConfigFileName, mockBaseDirectory, config);
                var settingsLoadContext = new SettingsLoadingContext();

                var settings = Settings.LoadImmutableSettingsGivenConfigPaths(new string[] { configPath }, settingsLoadContext);
                var result   = AddPackageCommandUtility.EvaluateSources(source, settings.GetConfigFilePaths());

                // Asert
                Assert.Equal(2, result.Count);
                Assert.NotEqual(null, result[0].Credentials);
            }
        }
Exemplo n.º 3
0
        private IReadOnlyList <RestoreSummaryRequest> GetRequestsFromItems(RestoreArgs restoreContext, DependencyGraphSpec dgFile)
        {
            if (restoreContext == null)
            {
                throw new ArgumentNullException(nameof(restoreContext));
            }

            if (dgFile == null)
            {
                throw new ArgumentNullException(nameof(dgFile));
            }

            // Validate the dg file input, this throws if errors are found.
            SpecValidationUtility.ValidateDependencySpec(dgFile);

            // Create requests
            var requests     = new ConcurrentBag <RestoreSummaryRequest>();
            var toolRequests = new ConcurrentBag <RestoreSummaryRequest>();

            var parallelOptions = new ParallelOptions
            {
                // By default, max degree of parallelism is -1 which means no upper bound.
                // Limiting to processor count reduces task context switching which is better
                MaxDegreeOfParallelism = Environment.ProcessorCount
            };

            using (var settingsLoadingContext = new SettingsLoadingContext())
            {
                // Parallel.Foreach has an optimization for Arrays, so calling .ToArray() is better and adds almost no overhead
                Parallel.ForEach(dgFile.Restore.ToArray(), parallelOptions, projectNameToRestore =>
                {
                    IReadOnlyList <PackageSpec> closure            = dgFile.GetClosure(projectNameToRestore);
                    DependencyGraphSpec projectDependencyGraphSpec = dgFile.CreateFromClosure(projectNameToRestore, closure);

                    var externalClosure = new HashSet <ExternalProjectReference>(closure.Select(GetExternalProject));

                    ExternalProjectReference rootProject = externalClosure.Single(p =>
                                                                                  StringComparer.Ordinal.Equals(projectNameToRestore, p.UniqueName));

                    RestoreSummaryRequest request = Create(
                        projectNameToRestore,
                        rootProject,
                        externalClosure,
                        restoreContext,
                        projectDependencyGraphSpec,
                        settingsLoadingContext);

                    if (request.Request.ProjectStyle == ProjectStyle.DotnetCliTool)
                    {
                        // Store tool requests to be filtered later
                        toolRequests.Add(request);
                    }
                    else
                    {
                        requests.Add(request);
                    }
                });
            }

            // Filter out duplicate tool restore requests
            foreach (RestoreSummaryRequest subSetRequest in ToolRestoreUtility.GetSubSetRequests(toolRequests))
            {
                requests.Add(subSetRequest);
            }

            return(requests.ToArray());
        }
Exemplo n.º 4
0
        private RestoreSummaryRequest Create(
            string projectNameToRestore,
            ExternalProjectReference project,
            HashSet <ExternalProjectReference> projectReferenceClosure,
            RestoreArgs restoreArgs,
            DependencyGraphSpec projectDgSpec,
            SettingsLoadingContext settingsLoadingContext)
        {
            var projectPackageSpec = projectDgSpec.GetProjectSpec(projectNameToRestore);
            //fallback paths, global packages path and sources need to all be passed in the dg spec
            var fallbackPaths       = projectPackageSpec.RestoreMetadata.FallbackFolders;
            var globalPath          = GetPackagesPath(restoreArgs, projectPackageSpec);
            var settings            = Settings.LoadImmutableSettingsGivenConfigPaths(projectPackageSpec.RestoreMetadata.ConfigFilePaths, settingsLoadingContext);
            var sources             = restoreArgs.GetEffectiveSources(settings, projectPackageSpec.RestoreMetadata.Sources);
            var clientPolicyContext = ClientPolicyContext.GetClientPolicy(settings, restoreArgs.Log);

            var sharedCache = _providerCache.GetOrCreate(
                globalPath,
                fallbackPaths.AsList(),
                sources,
                restoreArgs.CacheContext,
                restoreArgs.Log);

            var rootPath = Path.GetDirectoryName(project.PackageSpec.FilePath);

            // Create request
            var request = new RestoreRequest(
                project.PackageSpec,
                sharedCache,
                restoreArgs.CacheContext,
                clientPolicyContext,
                restoreArgs.Log)
            {
                // Set properties from the restore metadata
                ProjectStyle = project.PackageSpec.RestoreMetadata.ProjectStyle,
                //  Project.json is special cased to put assets file and generated .props and targets in the project folder
                RestoreOutputPath            = project.PackageSpec.RestoreMetadata.ProjectStyle == ProjectStyle.ProjectJson ? rootPath : project.PackageSpec.RestoreMetadata.OutputPath,
                DependencyGraphSpec          = projectDgSpec,
                MSBuildProjectExtensionsPath = projectPackageSpec.RestoreMetadata.OutputPath
            };

            var restoreLegacyPackagesDirectory = project.PackageSpec?.RestoreMetadata?.LegacyPackagesDirectory
                                                 ?? DefaultRestoreLegacyPackagesDirectory;

            request.IsLowercasePackagesDirectory = !restoreLegacyPackagesDirectory;

            // Standard properties
            restoreArgs.ApplyStandardProperties(request);

            // Add project references
            request.ExternalProjects = projectReferenceClosure.ToList();

            // The lock file is loaded later since this is an expensive operation
            var summaryRequest = new RestoreSummaryRequest(
                request,
                project.MSBuildProjectPath,
                settings.GetConfigFilePaths(),
                sources);

            return(summaryRequest);
        }
Exemplo n.º 5
0
        public void TestConfigFileProbingDirectoryWithSettingsLoadingContext()
        {
            // Arrange
            var parentConfig = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <configuration>
                <fallbackPackageFolders>
                    <add key=""a"" value=""C:\Temp\a"" />
                </fallbackPackageFolders>
            </configuration>";

            var unreachableConfig = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <configuration>
                <fallbackPackageFolders>
                    <add key=""b"" value=""C:\Temp\b"" />
                </fallbackPackageFolders>
            </configuration>";

            var baseConfig = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <configuration>
                <packageSources>
                    <add key=""c"" value=""C:\Temp\c"" />
                </packageSources>
            </configuration>";

            var configName = "NuGet.Config";

            using (var machineWide = TestDirectory.CreateInTemp())
                using (var mockParentDirectory = TestDirectory.CreateInTemp())
                {
                    // Parent
                    //       Base
                    //            Probe Path
                    //       Unreachable
                    var basePath        = Path.Combine(mockParentDirectory, "base");
                    var unreachablePath = Path.Combine(mockParentDirectory, "unreachable");
                    var probePath       = Path.Combine(basePath, "probe");
                    Directory.CreateDirectory(basePath);
                    Directory.CreateDirectory(unreachablePath);
                    Directory.CreateDirectory(probePath);

                    SettingsTestUtils.CreateConfigurationFile(configName, mockParentDirectory, parentConfig);
                    SettingsTestUtils.CreateConfigurationFile(configName, basePath, baseConfig);
                    SettingsTestUtils.CreateConfigurationFile(configName, unreachablePath, unreachableConfig);

                    SettingsTestUtils.CreateConfigurationFile(configName, machineWide, MachineWideSettingsConfig);

                    var machineWideSettings = new Lazy <IMachineWideSettings>(() => new TestMachineWideSettings(new Settings(machineWide, configName, isMachineWide: true)));

                    // Test
                    using (var settingsLoadingContext = new SettingsLoadingContext())
                    {
                        var settings  = RestoreSettingsUtils.ReadSettings(null, probePath, null, machineWideSettings, settingsLoadingContext);
                        var filePaths = settings.GetConfigFilePaths();

                        Assert.Equal(4, filePaths.Count()); // base, parent, app data + machine wide
                        Assert.Contains(Path.Combine(basePath, configName), filePaths);
                        Assert.Contains(Path.Combine(mockParentDirectory, configName), filePaths);
                        Assert.DoesNotContain(Path.Combine(unreachablePath, configName), filePaths);
                    }
                }
        }
Exemplo n.º 6
0
        public static ISettings ReadSettings(string solutionDirectory, string restoreDirectory, string restoreConfigFile, Lazy <IMachineWideSettings> machineWideSettings, SettingsLoadingContext settingsLoadContext)
        {
            if (!string.IsNullOrEmpty(solutionDirectory))
            {
                // Read the solution-level settings
                var solutionSettingsFile = Path.Combine(
                    solutionDirectory,
                    NuGetConstants.NuGetSolutionSettingsFolder);

                if (restoreConfigFile != null)
                {
                    restoreConfigFile = Path.GetFullPath(restoreConfigFile);
                }

                return(Configuration.Settings.LoadDefaultSettings(
                           solutionSettingsFile,
                           configFileName: restoreConfigFile,
                           machineWideSettings: machineWideSettings.Value,
                           settingsLoadingContext: settingsLoadContext));
            }

            if (string.IsNullOrEmpty(restoreConfigFile))
            {
                return(Configuration.Settings.LoadDefaultSettings(
                           restoreDirectory,
                           configFileName: null,
                           machineWideSettings: machineWideSettings.Value,
                           settingsLoadingContext: settingsLoadContext));
            }
            else
            {
                var configFileFullPath = Path.GetFullPath(restoreConfigFile);
                var directory          = Path.GetDirectoryName(configFileFullPath);
                var configFileName     = Path.GetFileName(configFileFullPath);
                return(Configuration.Settings.LoadDefaultSettings(
                           directory,
                           configFileName,
                           machineWideSettings: null,
                           settingsLoadContext));
            }
        }