示例#1
0
        /// <summary>
        /// For internal use only
        /// </summary>
        internal static ISettings LoadSettings(
            string root,
            string configFileName,
            IMachineWideSettings machineWideSettings,
            bool loadUserWideSettings,
            bool useTestingGlobalPath,
            SettingsLoadingContext settingsLoadingContext = null)
        {
            // Walk up the tree to find a config file; also look in .nuget subdirectories
            // If a configFile is passed, don't walk up the tree. Only use that single config file.
            var validSettingFiles = new List <SettingsFile>();

            if (root != null && string.IsNullOrEmpty(configFileName))
            {
                validSettingFiles.AddRange(
                    GetSettingsFilesFullPath(root)
                    .Select(f =>
                {
                    if (settingsLoadingContext == null)
                    {
                        return(ReadSettings(root, f));
                    }
                    return(settingsLoadingContext.GetOrCreateSettingsFile(f));
                })
                    .Where(f => f != null));
            }

            return(LoadSettingsForSpecificConfigs(
                       root,
                       configFileName,
                       validSettingFiles,
                       machineWideSettings,
                       loadUserWideSettings,
                       useTestingGlobalPath));
        }
示例#2
0
        /// <summary>
        /// For internal use only.
        /// Finds and loads all configuration files within <paramref name="root" />.
        /// Does not load configuration files outside of <paramref name="root" />.
        /// </summary>
        internal static ISettings LoadSettings(
            DirectoryInfo root,
            IMachineWideSettings machineWideSettings,
            bool loadUserWideSettings,
            bool useTestingGlobalPath,
            SettingsLoadingContext settingsLoadingContext = null)
        {
            var validSettingFiles = new List <SettingsFile>();
            var comparer          = PathUtility.GetStringComparisonBasedOnOS();
            var settingsFiles     = root.GetFileSystemInfos("*.*", SearchOption.AllDirectories)
                                    .OfType <FileInfo>()
                                    .OrderByDescending(file => file.FullName.Count(c => c == Path.DirectorySeparatorChar))
                                    .Where(file => OrderedSettingsFileNames.Any(fileName => fileName.Equals(file.Name, comparer)));

            validSettingFiles.AddRange(
                settingsFiles
                .Select(file => ReadSettings(file.DirectoryName, file.FullName, settingsLoadingContext: settingsLoadingContext))
                .Where(file => file != null));

            return(LoadSettingsForSpecificConfigs(
                       root.FullName,
                       configFileName: null,
                       validSettingFiles,
                       machineWideSettings,
                       loadUserWideSettings,
                       useTestingGlobalPath,
                       settingsLoadingContext));
        }
        /// <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;
                }

                var defaultSettingsFilePath = Path.Combine(userSettingsDir, DefaultSettingsFileName);

                // ReadSettings will try to create the default config file if it doesn't exist
                SettingsFile userSpecificSettings = ReadSettings(rootDirectory, defaultSettingsFilePath, settingsLoadingContext: settingsLoadingContext);

                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));
            }
        }
示例#4
0
 /// <summary>
 /// Loads user settings from the NuGet configuration files. The method walks the directory
 /// tree in <paramref name="root" /> up to its root, and reads each NuGet.config file
 /// it finds in the directories. It then reads the user specific settings,
 /// which is file <paramref name="configFileName" />
 /// in <paramref name="root" /> if <paramref name="configFileName" /> is not null,
 /// If <paramref name="configFileName" /> is null, the user specific settings file is
 /// %AppData%\NuGet\NuGet.config.
 /// After that, the machine wide settings files are added.
 /// </summary>
 /// <remarks>
 /// For example, if <paramref name="root" /> is c:\dir1\dir2, <paramref name="configFileName" />
 /// is "userConfig.file", the files loaded are (in the order that they are loaded):
 /// c:\dir1\dir2\nuget.config
 /// c:\dir1\nuget.config
 /// c:\nuget.config
 /// c:\dir1\dir2\userConfig.file
 /// machine wide settings (e.g. c:\programdata\NuGet\Config\*.config)
 /// </remarks>
 /// <param name="root">
 /// The file system to walk to find configuration files.
 /// Can be null.
 /// </param>
 /// <param name="configFileName">The user specified configuration file.</param>
 /// <param name="machineWideSettings">
 /// The machine wide settings. If it's not null, the
 /// settings files in the machine wide settings are added after the user specific
 /// config file.
 /// </param>
 /// <param name="settingsLoadingContext">A <see cref="SettingsLoadingContext" /> object to use when loading the settings.</param>
 /// <returns>The settings object loaded.</returns>
 public static ISettings LoadDefaultSettings(
     string root,
     string configFileName,
     IMachineWideSettings machineWideSettings,
     SettingsLoadingContext settingsLoadingContext)
 {
     return(LoadSettings(
                root,
                configFileName,
                machineWideSettings,
                loadUserWideSettings: true,
                useTestingGlobalPath: false,
                settingsLoadingContext));
 }
示例#5
0
        private static ISettings LoadSettingsForSpecificConfigs(
            string root,
            string configFileName,
            List <SettingsFile> validSettingFiles,
            IMachineWideSettings machineWideSettings,
            bool loadUserWideSettings,
            bool useTestingGlobalPath,
            SettingsLoadingContext settingsLoadingContext = null)
        {
            if (loadUserWideSettings)
            {
                var userSpecific = LoadUserSpecificSettings(root, configFileName, useTestingGlobalPath, settingsLoadingContext);
                if (userSpecific != null)
                {
                    validSettingFiles.Add(userSpecific);
                }
            }

            if (machineWideSettings != null && machineWideSettings.Settings is Settings mwSettings && string.IsNullOrEmpty(configFileName))
            {
                // Priority gives you the settings file in the order you want to start reading them
                var files = mwSettings.Priority.Select(
                    s => ReadSettings(s.DirectoryPath, s.FileName, s.IsMachineWide, settingsLoadingContext));

                validSettingFiles.AddRange(files);
            }

            if (validSettingFiles?.Any() != true)
            {
                // This means we've failed to load all config files and also failed to load or create the one in %AppData%
                // Work Item 1531: If the config file is malformed and the constructor throws, NuGet fails to load in VS.
                // Returning a null instance prevents us from silently failing and also from picking up the wrong config
                return(NullSettings.Instance);
            }

            // Create a settings object with the linked list head. Typically, it's either the config file in %ProgramData%\NuGet\Config,
            // or the user wide config (%APPDATA%\NuGet\nuget.config) if there are no machine
            // wide config files. The head file is the one we want to read first, while the user wide config
            // is the one that we want to write to.
            // TODO: add UI to allow specifying which one to write to
            return(new Settings(settingsFiles: validSettingFiles));
        }
示例#6
0
        private static SettingsFile ReadSettings(string settingsRoot, string settingsPath, bool isMachineWideSettings = false, bool isAdditionalUserWideConfig = false, SettingsLoadingContext settingsLoadingContext = null)
        {
            try
            {
                if (settingsLoadingContext != null)
                {
                    return(settingsLoadingContext.GetOrCreateSettingsFile(settingsPath, isMachineWideSettings, isAdditionalUserWideConfig));
                }

                var tuple    = GetFileNameAndItsRoot(settingsRoot, settingsPath);
                var filename = tuple.Item1;
                var root     = tuple.Item2;
                return(new SettingsFile(root, filename, isMachineWideSettings, isAdditionalUserWideConfig));
            }
            catch (XmlException)
            {
                return(null);
            }
        }
示例#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));
            }
        }
示例#8
0
        public static ISettings LoadImmutableSettingsGivenConfigPaths(IList <string> configFilePaths, SettingsLoadingContext settingsLoadingContext)
        {
            if (configFilePaths == null || configFilePaths.Count == 0)
            {
                return(NullSettings.Instance);
            }
            var settings = new List <SettingsFile>();

            foreach (var configFilePath in configFilePaths)
            {
                settings.Add(settingsLoadingContext.GetOrCreateSettingsFile(configFilePath, isReadOnly: true));
            }

            return(new ImmutableSettings(LoadSettingsGivenSettingsFiles(settings)));
        }
示例#9
0
        private static 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;

            // 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, 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();
                    }
                }
            }
            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, settingsLoadingContext: settingsLoadingContext);
            }

            return(userSpecificSettings);
        }