private static PackageSource ReadPackageSource(SourceItem setting, bool isEnabled, ISettings settings)
        {
            var name          = setting.Key;
            var packageSource = new PackageSource(setting.GetValueAsPath(), name, isEnabled)
            {
                IsMachineWide            = setting.Origin?.IsMachineWide ?? false,
                MaxHttpRequestsPerSource = SettingsUtility.GetMaxHttpRequest(settings)
            };

            var credentials = ReadCredential(name, settings);

            if (credentials != null)
            {
                packageSource.Credentials = credentials;
            }

            var clientCertificateProvider = new ClientCertificateProvider(settings);
            var clientCertificateItem     = clientCertificateProvider.GetClientCertificate(name);

            if (clientCertificateItem != null)
            {
                packageSource.ClientCertificates = clientCertificateItem.Search().ToList();
            }

            packageSource.ProtocolVersion = ReadProtocolVersion(setting);

            return(packageSource);
        }
Example #2
0
        private static int ReadProtocolVersion(SourceItem setting)
        {
            if (int.TryParse(setting.ProtocolVersion, out var protocolVersion))
            {
                return(protocolVersion);
            }

            return(PackageSource.DefaultProtocolVersion);
        }
Example #3
0
        public void AsSourceItem_WorksCorrectly()
        {
            var source = new PackageSource("Source", "SourceName", isEnabled: false)
            {
                ProtocolVersion = 43
            };

            var expectedItem = new SourceItem("SourceName", "Source", "43");

            source.AsSourceItem().DeepEquals(expectedItem).Should().BeTrue();
        }
Example #4
0
        internal NuGetConfiguration(SettingsFile origin)
            : base()
        {
            var defaultSource = new SourceItem(NuGetConstants.FeedName, NuGetConstants.V3FeedUrl, protocolVersion: PackageSourceProvider.MaxSupportedProtocolVersion.ToString());

            defaultSource.SetNode(defaultSource.AsXNode());

            var defaultSection = new ParsedSettingSection(ConfigurationConstants.PackageSources, defaultSource)
            {
                Parent = this
            };

            defaultSection.SetNode(defaultSection.AsXNode());

            ChildrenSet.Add(defaultSection, defaultSection);

            SetNode(AsXNode());
            SetOrigin(origin);
        }
Example #5
0
        private PackageSource ReadPackageSource(SourceItem setting, bool isEnabled)
        {
            var name          = setting.Key;
            var packageSource = new PackageSource(setting.GetValueAsPath(), name, isEnabled)
            {
                IsMachineWide            = setting.Origin?.IsMachineWide ?? false,
                MaxHttpRequestsPerSource = SettingsUtility.GetMaxHttpRequest(Settings)
            };

            var credentials = ReadCredential(name);

            if (credentials != null)
            {
                packageSource.Credentials = credentials;
            }

            packageSource.ProtocolVersion = ReadProtocolVersion(setting);

            return(packageSource);
        }
Example #6
0
        public void SetValue(string section, string key, string value)
        {
            if (string.IsNullOrEmpty(section))
            {
                throw new ArgumentException(Resources.Argument_Cannot_Be_Null_Or_Empty, nameof(section));
            }

            if (string.IsNullOrEmpty(key))
            {
                throw new ArgumentException(Resources.Argument_Cannot_Be_Null_Or_Empty, nameof(key));
            }

            var itemToAdd = new AddItem(key, value);

            if (string.Equals(section, ConfigurationConstants.PackageSources, StringComparison.OrdinalIgnoreCase))
            {
                itemToAdd = new SourceItem(key, value);
            }

            AddOrUpdate(section, itemToAdd);
            SaveToDisk();
        }
Example #7
0
        /// <summary>
        /// Load the user specific settings
        /// </summary>
        /// <param name="root"></param>
        /// <param name="configFileName"></param>
        /// <param name="useTestingGlobalPath"></param>
        /// <param name="settingsLoadingContext"></param>
        /// <returns></returns>
        internal static IEnumerable <SettingsFile> LoadUserSpecificSettings(
            string root,
            string configFileName,
            bool useTestingGlobalPath,
            SettingsLoadingContext settingsLoadingContext = null)
        {
            // Path.Combine is performed with root so it should not be null
            // However, it is legal for it be empty in this method
            var rootDirectory = root ?? string.Empty;

            if (configFileName == null)
            {
                string userSettingsDir = GetUserSettingsDirectory(rootDirectory, useTestingGlobalPath);
                if (userSettingsDir == null)
                {
                    yield break;
                }

                // If the default user config NuGet.Config does not exist, we need to create it.
                var defaultSettingsFilePath = Path.Combine(userSettingsDir, DefaultSettingsFileName);

                SettingsFile userSpecificSettings = ReadSettings(rootDirectory, defaultSettingsFilePath, settingsLoadingContext: settingsLoadingContext);
                if (File.Exists(defaultSettingsFilePath) && userSpecificSettings.IsEmpty())
                {
                    var trackFilePath = Path.Combine(Path.GetDirectoryName(defaultSettingsFilePath), NuGetConstants.AddV3TrackFile);

                    if (!File.Exists(trackFilePath))
                    {
                        File.Create(trackFilePath).Dispose();

                        var defaultSource = new SourceItem(NuGetConstants.FeedName, NuGetConstants.V3FeedUrl, protocolVersion: "3");
                        userSpecificSettings.AddOrUpdate(ConfigurationConstants.PackageSources, defaultSource);
                        userSpecificSettings.SaveToDisk();
                    }
                }

                yield return(userSpecificSettings);

                // For backwards compatibility, we first return default user specific the non-default configs and then the additional files from the nested `config` directory
                var additionalConfigurationPath = GetAdditionalUserWideConfigurationDirectory(userSettingsDir);
                foreach (var file in FileSystemUtility
                         .GetFilesRelativeToRoot(root: additionalConfigurationPath, filters: SupportedMachineWideConfigExtension, searchOption: SearchOption.TopDirectoryOnly)
                         .OrderBy(e => e, PathUtility.GetStringComparerBasedOnOS()))
                {
                    if (!PathUtility.GetStringComparerBasedOnOS().Equals(DefaultSettingsFileName, file))
                    {
                        var settings = ReadSettings(additionalConfigurationPath, file, isMachineWideSettings: false, isAdditionalUserWideConfig: true);
                        if (settings != null)
                        {
                            yield return(settings);
                        }
                    }
                }
            }
            else
            {
                if (!FileSystemUtility.DoesFileExistIn(rootDirectory, configFileName))
                {
                    var message = string.Format(CultureInfo.CurrentCulture,
                                                Resources.FileDoesNotExist,
                                                Path.Combine(rootDirectory, configFileName));
                    throw new InvalidOperationException(message);
                }

                yield return(ReadSettings(rootDirectory, configFileName, settingsLoadingContext: settingsLoadingContext));
            }
        }
Example #8
0
        public void SavePackageSources(IEnumerable <PackageSource> sources)
        {
            if (sources == null)
            {
                throw new ArgumentNullException(nameof(sources));
            }

            var isDirty = false;
            var existingSettingsLookup = GetExistingSettingsLookup();

            var disabledSourcesSection        = Settings.GetSection(ConfigurationConstants.DisabledPackageSources);
            var existingDisabledSources       = disabledSourcesSection?.Items.OfType <AddItem>();
            var existingDisabledSourcesLookup = existingDisabledSources?.ToDictionary(setting => setting.Key, StringComparer.OrdinalIgnoreCase);

            var credentialsSection        = Settings.GetSection(ConfigurationConstants.CredentialsSectionName);
            var existingCredentials       = credentialsSection?.Items.OfType <CredentialsItem>();
            var existingCredentialsLookup = existingCredentials?.ToDictionary(setting => setting.ElementName, StringComparer.OrdinalIgnoreCase);

            foreach (var source in sources)
            {
                AddItem         existingDisabledSourceItem = null;
                SourceItem      existingSourceItem         = null;
                CredentialsItem existingCredentialsItem    = null;

                var existingSourceIsEnabled = existingDisabledSourcesLookup == null || existingDisabledSourcesLookup.TryGetValue(source.Name, out existingDisabledSourceItem);

                if (existingSettingsLookup != null &&
                    existingSettingsLookup.TryGetValue(source.Name, out existingSourceItem) &&
                    ReadProtocolVersion(existingSourceItem) == source.ProtocolVersion)
                {
                    var oldPackageSource = ReadPackageSource(existingSourceItem, existingSourceIsEnabled);

                    existingCredentialsLookup?.TryGetValue(source.Name, out existingCredentialsItem);

                    UpdatePackageSource(
                        source,
                        oldPackageSource,
                        existingDisabledSourceItem,
                        existingCredentialsItem,
                        updateEnabled: true,
                        updateCredentials: true,
                        shouldSkipSave: true,
                        isDirty: ref isDirty);
                }
                else
                {
                    AddPackageSource(source, shouldSkipSave: true, isDirty: ref isDirty);
                }

                if (existingSourceItem != null)
                {
                    existingSettingsLookup.Remove(source.Name);
                }
            }

            if (existingSettingsLookup != null)
            {
                // get list of credentials for sources
                var sourceCredentialsSection        = Settings.GetSection(ConfigurationConstants.CredentialsSectionName);
                var sourceCredentialsSettings       = sourceCredentialsSection?.Items.OfType <CredentialsItem>();
                var existingsourceCredentialsLookup = sourceCredentialsSettings?.ToDictionary(setting => setting.ElementName, StringComparer.OrdinalIgnoreCase);

                foreach (var sourceItem in existingSettingsLookup)
                {
                    if (existingDisabledSourcesLookup != null && existingDisabledSourcesLookup.TryGetValue(sourceItem.Value.Key, out var existingDisabledSourceItem))
                    {
                        Settings.Remove(ConfigurationConstants.DisabledPackageSources, existingDisabledSourceItem);
                        isDirty = true;
                    }

                    if (existingsourceCredentialsLookup != null && existingsourceCredentialsLookup.TryGetValue(sourceItem.Value.Key, out var existingSourceCredentialItem))
                    {
                        Settings.Remove(ConfigurationConstants.CredentialsSectionName, existingSourceCredentialItem);
                        isDirty = true;
                    }

                    Settings.Remove(ConfigurationConstants.PackageSources, sourceItem.Value);
                    isDirty = true;
                }
            }


            if (isDirty)
            {
                Settings.SaveToDisk();
                OnPackageSourcesChanged();
                isDirty = false;
            }
        }
Example #9
0
        private static SettingsFile LoadUserSpecificSettings(
            string root,
            string configFileName,
            bool useTestingGlobalPath)
        {
            // Path.Combine is performed with root so it should not be null
            // However, it is legal for it be empty in this method
            var rootDirectory = root ?? string.Empty;

            // for the default location, allow case where file does not exist, in which case it'll end
            // up being created if needed
            SettingsFile userSpecificSettings = null;

            if (configFileName == null)
            {
                var defaultSettingsFilePath = string.Empty;
                if (useTestingGlobalPath)
                {
                    defaultSettingsFilePath = Path.Combine(rootDirectory, "TestingGlobalPath", DefaultSettingsFileName);
                }
                else
                {
                    var userSettingsDir = NuGetEnvironment.GetFolderPath(NuGetFolderPath.UserSettingsDirectory);

                    // If there is no user settings directory, return no settings
                    if (userSettingsDir == null)
                    {
                        return(null);
                    }
                    defaultSettingsFilePath = Path.Combine(userSettingsDir, DefaultSettingsFileName);
                }

                userSpecificSettings = ReadSettings(rootDirectory, defaultSettingsFilePath);

                if (File.Exists(defaultSettingsFilePath) && userSpecificSettings.IsEmpty())
                {
                    var trackFilePath = Path.Combine(Path.GetDirectoryName(defaultSettingsFilePath), NuGetConstants.AddV3TrackFile);

                    if (!File.Exists(trackFilePath))
                    {
                        File.Create(trackFilePath).Dispose();

                        var defaultSource = new SourceItem(NuGetConstants.FeedName, NuGetConstants.V3FeedUrl, protocolVersion: "3");
                        userSpecificSettings.AddOrUpdate(ConfigurationConstants.PackageSources, defaultSource);
                        userSpecificSettings.SaveToDisk();
                    }
                }
            }
            else
            {
                if (!FileSystemUtility.DoesFileExistIn(rootDirectory, configFileName))
                {
                    var message = string.Format(CultureInfo.CurrentCulture,
                                                Resources.FileDoesNotExist,
                                                Path.Combine(rootDirectory, configFileName));
                    throw new InvalidOperationException(message);
                }

                userSpecificSettings = ReadSettings(rootDirectory, configFileName);
            }

            return(userSpecificSettings);
        }