Esempio n. 1
0
        private DirectoryPath GetToolPath(DirectoryPath root)
        {
            var toolPath = _configuration.GetValue(Constants.Paths.Tools);

            if (!string.IsNullOrWhiteSpace(toolPath))
            {
                return(new DirectoryPath(toolPath).MakeAbsolute(_environment));
            }

            return(root.Combine("tools"));
        }
Esempio n. 2
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ProcessRunner" /> class.
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="environment">The environment.</param>
        /// <param name="log">The log.</param>
        /// <param name="tools">The tool locator.</param>
        /// <param name="configuration">The tool configuration.</param>
        public ProcessRunner(IFileSystem fileSystem, ICakeEnvironment environment, ICakeLog log, IToolLocator tools, ICakeConfiguration configuration)
        {
            _fileSystem    = fileSystem ?? throw new ArgumentNullException(nameof(fileSystem));
            _environment   = environment ?? throw new ArgumentNullException(nameof(environment));
            _log           = log ?? throw new ArgumentNullException(nameof(log));
            _tools         = tools ?? throw new ArgumentNullException(nameof(tools));
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));

            var noMonoCoersion = configuration.GetValue(Constants.Settings.NoMonoCoersion);

            _noMonoCoersion = noMonoCoersion != null && noMonoCoersion.Equals("true", StringComparison.OrdinalIgnoreCase);
            var showCommandLine = configuration.GetValue(Constants.Settings.ShowProcessCommandLine);

            _showCommandLine = showCommandLine != null && showCommandLine.Equals("true", StringComparison.OrdinalIgnoreCase);
        }
        public NuGetSourceRepositoryProvider(ISettings settings, ICakeConfiguration config, PackageReference package)
        {
            // Create the package source provider (needed primarily to get default sources)
            PackageSourceProvider = new PackageSourceProvider(settings);

            // Create the default v3 resource provider
            _resourceProviders = new List <Lazy <INuGetResourceProvider> >();
            _resourceProviders.AddRange(Repository.Provider.GetCoreV3());

            // Add repositories
            _repositories = new List <SourceRepository>();

            foreach (var source in PackageSourceProvider.LoadPackageSources())
            {
                if (source.IsEnabled)
                {
                    CreateRepository(source);
                }
            }
            var nugetSource = config.GetValue(Constants.NuGet.Source);

            if (!string.IsNullOrWhiteSpace(nugetSource))
            {
                CreateRepository(nugetSource);
            }
            if (package.Address != null)
            {
                CreateRepository(package.Address.AbsoluteUri);
            }
        }
Esempio n. 4
0
        public AssemblyVerifier(ICakeConfiguration configuration, ICakeLog log)
        {
            _log = log;
            var skip = configuration.GetValue(Constants.Settings.SkipVerification);

            _skipVerification = skip != null && skip.Equals("true", StringComparison.OrdinalIgnoreCase);
        }
Esempio n. 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ScriptProcessor"/> class.
        /// </summary>
        /// <param name="fileSystem">The file system.</param>
        /// <param name="environment">The environment.</param>
        /// <param name="log">The log.</param>
        /// <param name="tools">The tool locator.</param>
        /// <param name="installers">The available package installers.</param>
        /// <param name="configuration">The configuration.</param>
        public ScriptProcessor(
            IFileSystem fileSystem,
            ICakeEnvironment environment,
            ICakeLog log,
            IToolLocator tools,
            IEnumerable <IPackageInstaller> installers,
            ICakeConfiguration configuration)
        {
            if (fileSystem == null)
            {
                throw new ArgumentNullException(nameof(fileSystem));
            }
            if (environment == null)
            {
                throw new ArgumentNullException(nameof(environment));
            }
            if (log == null)
            {
                throw new ArgumentNullException(nameof(log));
            }
            if (installers == null)
            {
                throw new ArgumentNullException(nameof(installers));
            }

            _environment = environment;
            _log         = log;
            _tools       = tools;
            _installers  = new List <IPackageInstaller>(installers);
            var skip = configuration.GetValue(Constants.Settings.SkipPackageVersionCheck);

            _skipPackageVersionCheck = skip != null && skip.Equals("true", StringComparison.OrdinalIgnoreCase);
        }
Esempio n. 6
0
        private static Tuple <DirectoryPath, FilePath> GetNuGetConfigPath(ICakeEnvironment environment, ICakeConfiguration config, IFileSystem fileSystem)
        {
            DirectoryPath rootPath;
            FilePath      filePath;

            var nugetConfigFile = config.GetValue(Constants.NuGet.ConfigFile);

            if (!string.IsNullOrEmpty(nugetConfigFile))
            {
                var configFilePath = new FilePath(nugetConfigFile).MakeAbsolute(environment);

                if (!fileSystem.Exist(configFilePath))
                {
                    throw new System.IO.FileNotFoundException("NuGet Config file not found.", configFilePath.FullPath);
                }

                rootPath = configFilePath.GetDirectory();
                filePath = configFilePath.GetFilename();
            }
            else
            {
                rootPath = GetToolPath(environment, config);
                filePath = null;
            }

            return(Tuple.Create(rootPath, filePath));
        }
        private static string GetToolPath(ICakeEnvironment environment, ICakeConfiguration config)
        {
            var toolPath = config.GetValue(Constants.Paths.Tools);

            return(!string.IsNullOrWhiteSpace(toolPath) ?
                   new DirectoryPath(toolPath).MakeAbsolute(environment).FullPath :
                   environment.WorkingDirectory.Combine("tools").MakeAbsolute(environment).FullPath);
        }
Esempio n. 8
0
        private DirectoryPath GetToolPath(DirectoryPath root)
        {
            var toolPath = _configuration.GetValue("Paths_Tools");

            return(!string.IsNullOrWhiteSpace(toolPath)
                ? new DirectoryPath(toolPath).MakeAbsolute(_environment)
                : root.Combine("tools"));
        }
Esempio n. 9
0
        private string GetToolPath()
        {
            var toolPath = _config.GetValue(Constants.Paths.Tools);

            return(!string.IsNullOrWhiteSpace(toolPath) ?
                   new DirectoryPath(toolPath).MakeAbsolute(_environment).FullPath :
                   _environment.WorkingDirectory.Combine("tools").MakeAbsolute(_environment).FullPath);
        }
Esempio n. 10
0
        private DirectoryPath GetModulePath(CakeOptions options)
        {
            var root = _configuration.GetValue(Constants.Paths.Modules);

            if (string.IsNullOrWhiteSpace(root))
            {
                return(options.Script.GetDirectory().Combine("tools/modules"));
            }
            return(new DirectoryPath(root));
        }
Esempio n. 11
0
        /// <summary>
        /// Get a config-value as a flag from the <see cref="ICakeConfiguration"/>.
        /// </summary>
        /// <param name="config">The <see cref="ICakeConfiguration"/>.</param>
        /// <param name="key">The config key to get.</param>
        /// <returns><c>true</c>, if the config key exists and equals the text <c>"True"</c>. Otherwise, <c>false</c>.</returns>
        public static bool GetConfigFlag(this ICakeConfiguration config, string key)
        {
            string configValue = config.GetValue(key);

            return(string.IsNullOrWhiteSpace(configValue)
                ? false
                : bool.TryParse(configValue, out bool fail)
                    ? fail
                    : false);
        }
Esempio n. 12
0
        /// <summary>
        /// Gets the tool directory path.
        /// </summary>
        /// <param name="configuration">The Cake configuration.</param>
        /// <param name="defaultRoot">The default root path.</param>
        /// <param name="environment">The environment.</param>
        /// <returns>The tool directory path.</returns>
        public static DirectoryPath GetToolPath(this ICakeConfiguration configuration, DirectoryPath defaultRoot, ICakeEnvironment environment)
        {
            var toolPath = configuration.GetValue(Constants.Paths.Tools);

            if (!string.IsNullOrWhiteSpace(toolPath))
            {
                return(new DirectoryPath(toolPath).MakeAbsolute(environment));
            }
            return(defaultRoot.Combine("tools"));
        }
Esempio n. 13
0
        private DirectoryPath GetToolsDirectory()
        {
            var toolPath = _configuration.GetValue(Constants.Paths.Tools);

            if (!string.IsNullOrWhiteSpace(toolPath))
            {
                return(new DirectoryPath(toolPath));
            }

            return(new DirectoryPath("./tools"));
        }
Esempio n. 14
0
        private bool UseInProcessClient(ICakeConfiguration configuration)
        {
            var useInProcessClientString = configuration.GetValue(Constants.NuGet.UseInProcessClient) ?? bool.TrueString;

            if (!bool.TryParse(useInProcessClientString, out bool useInProcessClient))
            {
                // If there is no explicit preference, use the in process client.
                return(true);
            }

            return(useInProcessClient);
        }
        private static ProcessArgumentBuilder GetArguments(
            PackageReference definition,
            DirectoryPath installationRoot, ICakeConfiguration config)
        {
            var arguments = new ProcessArgumentBuilder();

            arguments.Append("install");
            arguments.AppendQuoted(definition.Package);

            // Output directory
            arguments.Append("-OutputDirectory");
            arguments.AppendQuoted(installationRoot.FullPath);

            // if an absolute uri is specified for source, use this
            // otherwise check config for customise package source/s
            if (definition.Address != null)
            {
                arguments.Append("-Source");
                arguments.AppendQuoted(definition.Address.AbsoluteUri);
            }
            else
            {
                var nugetSource = config.GetValue(Constants.NuGet.Source);
                if (!string.IsNullOrWhiteSpace(nugetSource))
                {
                    arguments.Append("-Source");
                    arguments.AppendQuoted(nugetSource);
                }
            }

            // Version
            if (definition.Parameters.ContainsKey("version"))
            {
                arguments.Append("-Version");
                arguments.AppendQuoted(definition.Parameters["version"].First());
            }

            // Prerelease
            if (definition.Parameters.ContainsKey("prerelease"))
            {
                arguments.Append("-Prerelease");
            }

            // NoCache
            if (definition.Parameters.ContainsKey("nocache"))
            {
                arguments.Append("-NoCache");
            }

            arguments.Append("-ExcludeVersion");
            arguments.Append("-NonInteractive");
            return(arguments);
        }
        public NuGetSourceRepositoryProvider(ISettings settings, ICakeConfiguration config, PackageReference package)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

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

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

            // Create the package source provider (needed primarily to get default sources)
            PackageSourceProvider = new PackageSourceProvider(settings);

            // Create the default v3 resource provider
            _resourceProviders = new List <Lazy <INuGetResourceProvider> >();
            _resourceProviders.AddRange(Repository.Provider.GetCoreV3());

            // Add repositories
            _repositories = new HashSet <SourceRepository>(new SourceRepositoryComparer());

            if (package.Address != null)
            {
                CreateRepository(package.Address.AbsoluteUri);
            }

            var nugetSources = config.GetValue(Constants.NuGet.Source);

            if (!string.IsNullOrEmpty(nugetSources))
            {
                foreach (var nugetSource in nugetSources.Split(';'))
                {
                    if (!string.IsNullOrWhiteSpace(nugetSource))
                    {
                        CreateRepository(nugetSource);
                    }
                }
            }

            foreach (var source in PackageSourceProvider.LoadPackageSources())
            {
                if (source.IsEnabled)
                {
                    CreateRepository(source);
                }
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Gets the module directory path.
        /// </summary>
        /// <param name="configuration">The Cake configuration.</param>
        /// <param name="defaultRoot">The default root path.</param>
        /// <param name="environment">The environment.</param>
        /// <returns>The module directory path.</returns>
        public static DirectoryPath GetModulePath(this ICakeConfiguration configuration, DirectoryPath defaultRoot, ICakeEnvironment environment)
        {
            var modulePath = configuration.GetValue(Constants.Paths.Modules);

            if (!string.IsNullOrWhiteSpace(modulePath))
            {
                return(new DirectoryPath(modulePath).MakeAbsolute(environment));
            }
            var toolPath = configuration.GetToolPath(defaultRoot, environment);

            return(toolPath.Combine("Modules").Collapse());
        }
        private void Install(SemanticVersion version)
        {
            var root        = _environment.GetApplicationRoot().MakeAbsolute(_environment);
            var installRoot = root.Combine(Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture));

            var packages = new Dictionary <string, SemanticVersion>
            {
                { "Microsoft.CodeAnalysis.Scripting", version },
                { "Microsoft.CodeAnalysis.CSharp", version }
            };

            // Install package.
            var nugetSource    = _configuration.GetValue("Roslyn_NuGetSource") ?? "https://packages.nuget.org/api/v2";
            var repo           = PackageRepositoryFactory.Default.CreateRepository(nugetSource);
            var packageManager = new PackageManager(repo, installRoot.FullPath);

            _log.Verbose("Installing packages (using {0})...", nugetSource);
            foreach (var package in packages)
            {
                _log.Information("Downloading package {0} ({1})...", package.Key, package.Value);
                packageManager.InstallPackage(package.Key, package.Value, false, true);
            }

            // Copy files.
            _log.Verbose("Copying files...");
            foreach (var path in _paths)
            {
                // Find the file within the temporary directory.
                var exp       = string.Concat(installRoot.FullPath, "/**/", path);
                var foundFile = _globber.Match(exp).FirstOrDefault();
                if (foundFile == null)
                {
                    var format  = "Could not find file {0}.";
                    var message = string.Format(CultureInfo.InvariantCulture, format, path);
                    throw new CakeException(message);
                }

                var source      = _fileSystem.GetFile((FilePath)foundFile);
                var destination = _fileSystem.GetFile(root.CombineWithFilePath(path.GetFilename()));

                _log.Information("Copying {0}...", source.Path.GetFilename());

                if (!destination.Exists)
                {
                    source.Copy(destination.Path, true);
                }
            }

            // Delete the install directory.
            _log.Verbose("Deleting installation directory...");
            _fileSystem.GetDirectory(installRoot).Delete(true);
        }
Esempio n. 19
0
        public IReadOnlyCollection <IFile> GetFiles(DirectoryPath directoryPath, PackageReference packageReference, PackageType type)
        {
            bool loadDependencies;

            if (packageReference.Parameters.ContainsKey("LoadDependencies"))
            {
                bool.TryParse(packageReference.Parameters["LoadDependencies"].FirstOrDefault() ?? bool.TrueString, out loadDependencies);
            }
            else
            {
                bool.TryParse(_config.GetValue(Constants.NuGet.LoadDependencies) ?? bool.FalseString, out loadDependencies);
            }

            var files       = new List <IFile>();
            var package     = _installedPackages.First(p => p.Id.Equals(packageReference.Package, StringComparison.OrdinalIgnoreCase));
            var installPath = new DirectoryPath(_pathResolver.GetInstallPath(package));

            if (!_fileSystem.Exist(installPath))
            {
                _log.Warning("Package {0} is not installed.", packageReference.Package);
                return(Array.Empty <IFile>());
            }

            files.AddRange(_contentResolver.GetFiles(installPath, packageReference, type));

            if (loadDependencies)
            {
                foreach (var dependency in _installedPackages
                         .Where(p => !p.Id.Equals(packageReference.Package, StringComparison.OrdinalIgnoreCase)))
                {
                    if (_blackListedPackages.Contains(dependency.Id))
                    {
                        _log.Warning("Package {0} depends on package {1}. Will not load this dependency...",
                                     packageReference.Package, dependency.ToString());
                        continue;
                    }

                    var dependencyInstallPath = new DirectoryPath(_pathResolver.GetInstallPath(dependency));

                    if (!_fileSystem.Exist(dependencyInstallPath))
                    {
                        _log.Warning("Package {0} is not installed.", dependency.Id);
                        continue;
                    }

                    files.AddRange(_contentResolver.GetFiles(dependencyInstallPath, packageReference, type));
                }
            }

            return(files);
        }
Esempio n. 20
0
        private ProcessArgumentBuilder GetArguments(
            PackageReference definition,
            ICakeConfiguration config)
        {
            var arguments = new ProcessArgumentBuilder();

            arguments.Append("install");
            arguments.Append("-y");
            var packageString = new StringBuilder(definition.Package);

            // if an absolute uri is specified for source, use this
            // otherwise check config for customise package source/s
            if (definition.Address != null)
            {
                arguments.Append($"--repofrompath=\"{definition.Package},{definition.Address.AbsoluteUri}\"");
                arguments.Append($"--repo={definition.Package}");
            }
            else
            {
                var dnfSource = config.GetValue("DNF_Source");
                if (!string.IsNullOrWhiteSpace(dnfSource))
                {
                    arguments.Append($"--repofrompath=\"{definition.Package},{dnfSource}\"");
                    arguments.Append($"--repo={definition.Package}");
                }
            }

            if (_log.Verbosity == Verbosity.Verbose || _log.Verbosity == Verbosity.Diagnostic)
            {
                arguments.Append("--verbose");
            }

            if (definition.GetSwitch("best"))
            {
                arguments.Append("--best");
            }

            // Version
            if (definition.Parameters.ContainsKey("version"))
            {
                packageString.Append($"-{definition.Parameters["version"].First()}");
            }

            if (definition.Parameters.ContainsKey("arch"))
            {
                packageString.Append($".{definition.Parameters["arch"].First()}");
            }
            arguments.Append(packageString.ToString());
            return(arguments);
        }
Esempio n. 21
0
        public static bool ShouldLoadDependencies(this PackageReference packageReference, ICakeConfiguration config)
        {
            bool loadDependencies;

            if (packageReference.Parameters.ContainsKey(LoadDependenciesKey))
            {
                bool.TryParse(packageReference.Parameters[LoadDependenciesKey].FirstOrDefault() ?? bool.TrueString, out loadDependencies);
            }
            else
            {
                bool.TryParse(config.GetValue(Constants.NuGet.LoadDependencies) ?? bool.FalseString, out loadDependencies);
            }
            return(loadDependencies);
        }
Esempio n. 22
0
        private static ProcessArgumentBuilder GetArguments(
            PackageReference definition,
            DirectoryPath installationRoot,
            ICakeConfiguration config)
        {
            var arguments = new ProcessArgumentBuilder();

            arguments.Append("install");
            arguments.AppendQuoted(definition.Package);
            arguments.Append("-y");

            // if an absolute uri is specified for source, use this
            // otherwise check config for customise package source/s
            if (definition.Address != null)
            {
                arguments.Append("--source");
                arguments.AppendQuoted(definition.Address.AbsoluteUri);
            }
            else
            {
                var chocolateySource = config.GetValue(Constants.Chocolatey.Source) ?? "https://chocolatey.org/api/v2/";
                if (!string.IsNullOrWhiteSpace(chocolateySource))
                {
                    arguments.Append("--source");
                    arguments.AppendQuoted(chocolateySource);
                }
            }

            // Version
            if (definition.Parameters.ContainsKey("version"))
            {
                arguments.Append("--version");
                arguments.AppendQuoted(definition.Parameters["version"].First());
            }

            // Prerelease
            if (definition.Parameters.ContainsKey("prerelease"))
            {
                arguments.Append("--prerelease");
            }

            return(arguments);
        }
Esempio n. 23
0
        /// <summary>
        /// Performs custom registrations in the provided registrar.
        /// </summary>
        /// <param name="registrar">The container registrar.</param>
        public void Register(ICakeContainerRegistrar registrar)
        {
            if (registrar == null)
            {
                throw new ArgumentNullException(nameof(registrar));
            }

            // NuGet content resolver.
            registrar.RegisterType <NuGetContentResolver>()
            .As <INuGetContentResolver>()
            .Singleton();

#if !NETCORE
            // Load directive provider.
            registrar.RegisterType <NuGetLoadDirectiveProvider>()
            .As <ILoadDirectiveProvider>()
            .Singleton();
#endif

            // URI resource support.
            bool.TryParse(_config.GetValue(Constants.NuGet.UseInProcessClient) ?? bool.FalseString, out bool useInProcessClient);
            if (useInProcessClient)
            {
#if NETCORE
                // Load directive provider.
                registrar.RegisterType <NuGetLoadDirectiveProvider>()
                .As <ILoadDirectiveProvider>()
                .Singleton();
#endif
                registrar.RegisterType <Install.NuGetPackageInstaller>()
                .As <INuGetPackageInstaller>()
                .As <IPackageInstaller>()
                .Singleton();
            }
            else
            {
                registrar.RegisterType <NuGetPackageInstaller>()
                .As <INuGetPackageInstaller>()
                .As <IPackageInstaller>()
                .Singleton();
            }
        }
Esempio n. 24
0
 public string GetValue(string key)
 {
     lock (_lock)
     {
         if (_configuration == null)
         {
             var arguments = new Dictionary <string, string>(_options.Arguments, StringComparer.OrdinalIgnoreCase);
             if (_values != null)
             {
                 // Add additional configuration values.
                 foreach (var value in _values)
                 {
                     arguments[value.Key] = value.Value;
                 }
             }
             _configuration = _provider.CreateConfiguration(_environment.WorkingDirectory, arguments);
         }
         return(_configuration.GetValue(key));
     }
 }
        private static Tuple <DirectoryPath, FilePath> GetNuGetConfigPath(ICakeEnvironment environment, ICakeConfiguration config)
        {
            DirectoryPath rootPath;
            FilePath      filePath;

            var nugetConfigFile = config.GetValue(Constants.NuGet.ConfigFile);

            if (!string.IsNullOrEmpty(nugetConfigFile))
            {
                var configFilePath = new FilePath(nugetConfigFile);

                rootPath = configFilePath.GetDirectory();
                filePath = configFilePath.GetFilename();
            }
            else
            {
                rootPath = GetToolPath(environment, config);
                filePath = null;
            }

            return(Tuple.Create(rootPath, filePath));
        }
Esempio n. 26
0
        public RoslynScriptSession(
            IScriptHost host,
            IAssemblyLoader loader,
            ICakeConfiguration configuration,
            ICakeLog log,
            IScriptHostSettings settings)
        {
            _host          = host;
            _fileSystem    = host.Context.FileSystem;
            _loader        = loader;
            _log           = log;
            _configuration = configuration;
            _settings      = settings;

            ReferencePaths = new HashSet <FilePath>(PathComparer.Default);
            References     = new HashSet <Assembly>();
            Namespaces     = new HashSet <string>(StringComparer.Ordinal);

            var cacheEnabled = configuration.GetValue(Constants.Settings.EnableScriptCache) ?? bool.FalseString;

            _scriptCacheEnabled = cacheEnabled.Equals(bool.TrueString, StringComparison.OrdinalIgnoreCase);
            _regenerateCache    = host.Context.Arguments.HasArgument(Constants.Cache.InvalidateScriptCache);
            _scriptCachePath    = configuration.GetScriptCachePath(settings.Script.GetDirectory(), host.Context.Environment);
        }
Esempio n. 27
0
        private void Install(DirectoryPath root)
        {
            if (root == null)
            {
                throw new ArgumentNullException("root");
            }

            var installRoot = root.Combine(Guid.NewGuid().ToString().Replace("-", string.Empty));

            // Install package.
            var nugetSource    = _configuration.GetValue(Constants.Roslyn.NuGetSource) ?? "https://packages.nuget.org/api/v2";
            var repository     = PackageRepositoryFactory.Default.CreateRepository(nugetSource);
            var packageManager = new PackageManager(repository, installRoot.FullPath);

            _log.Verbose("Installing packages (using {0})...", nugetSource);
            packageManager.InstallPackage("Roslyn.Compilers.CSharp", new SemanticVersion(new Version(1, 2, 20906, 2)), false, true);

            // Copy files
            _log.Verbose("Copying files...");
            foreach (var path in _paths)
            {
                var source      = _fileSystem.GetFile(installRoot.CombineWithFilePath(path));
                var destination = _fileSystem.GetFile(root.CombineWithFilePath(path.GetFilename()));

                _log.Information("Copying {0}...", source.Path.GetFilename());

                if (!destination.Exists)
                {
                    source.Copy(destination.Path, true);
                }
            }

            // Delete the install directory.
            _log.Verbose("Deleting installation directory...");
            _fileSystem.GetDirectory(installRoot).Delete(true);
        }
        public NuGetSourceRepositoryProvider(ISettings settings, ICakeConfiguration config, PackageReference package)
        {
            if (settings == null)
            {
                throw new ArgumentNullException(nameof(settings));
            }

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

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

            // Create the package source provider (needed primarily to get default sources)
            PackageSourceProvider = new PackageSourceProvider(settings);

            // Create the default v3 resource provider
            _resourceProviders = new List <Lazy <INuGetResourceProvider> >();
            _resourceProviders.AddRange(Repository.Provider.GetCoreV3());

            // Add repositories
            _repositories        = new HashSet <SourceRepository>(new SourceRepositoryComparer());
            _primaryRepositories = new HashSet <SourceRepository>(new SourceRepositoryComparer());

            var packageSources = PackageSourceProvider.LoadPackageSources().ToList();

            if (package.Address != null)
            {
                var repository = GetOrCreateRepository(package.Address.AbsoluteUri);

                // Sources specified in directive is always primary.
                _primaryRepositories.Add(repository);
            }

            var nugetSources = config.GetValue(Constants.NuGet.Source);

            if (!string.IsNullOrEmpty(nugetSources))
            {
                foreach (var nugetSource in nugetSources.Split(';'))
                {
                    if (!string.IsNullOrWhiteSpace(nugetSource))
                    {
                        var repository = GetOrCreateRepository(nugetSource);

                        // If source is not specified in directive, add it as primary source.
                        if (package.Address == null)
                        {
                            _primaryRepositories.Add(repository);
                        }
                    }
                }
            }
            else
            {
                // Only add sources added via NuGet.Config's if nuget_source configuration value is not specified.
                foreach (var source in packageSources)
                {
                    if (source.IsEnabled)
                    {
                        var repository = CreateRepository(source);

                        // If source is not specified in directive, add it as primary source.
                        if (package.Address == null)
                        {
                            _primaryRepositories.Add(repository);
                        }
                    }
                }
            }

            SourceRepository GetOrCreateRepository(string source)
            {
                var packageSource = packageSources
                                    .Where(p => p.IsEnabled)
                                    .FirstOrDefault(p => p.Source.Equals(source, StringComparison.OrdinalIgnoreCase));

                return(packageSource == null?
                       CreateRepository(source) :
                           CreateRepository(packageSource));
            }
        }
        private static string GetToolPath(string rootPath, ICakeConfiguration configuration)
        {
            var toolPath = configuration.GetValue(Constants.Paths.Tools);

            return(Path.Combine(rootPath, !string.IsNullOrWhiteSpace(toolPath) ? toolPath : "tools"));
        }
        private ProcessArgumentBuilder GetArguments(
            PackageReference definition,
            ICakeConfiguration config)
        {
            var arguments = new ProcessArgumentBuilder();

            arguments.Append("install");

            if (_log.Verbosity == Verbosity.Verbose || _log.Verbosity == Verbosity.Diagnostic)
            {
                arguments.Append("--verbose");
            }

            if (definition.Address != null)
            {
                arguments.Append($"--registry \"{definition.Address}\"");
            }
            else
            {
                var npmSource = config.GetValue(Constants.ConfigKey);
                if (!string.IsNullOrWhiteSpace(npmSource))
                {
                    arguments.Append($"--registry \"{npmSource}\"");
                }
            }

            if (definition.GetSwitch("force"))
            {
                arguments.Append("--force");
            }

            if (definition.GetSwitch("global"))
            {
                arguments.Append("--global");
            }

            if (definition.GetSwitch("ignore-scripts"))
            {
                arguments.Append("--ignore-scripts");
            }

            if (definition.GetSwitch("no-optional"))
            {
                arguments.Append("--no-optional");
            }

            if (definition.GetSwitch("save"))
            {
                GetSaveArguments(arguments, definition);
            }

            var packageString = new StringBuilder();

            if (definition.HasValue("source", out string source))
            {
                packageString.Append(source.Trim(':') + ":");
            }

            if (definition.HasValue("scope", out string scope))
            {
                packageString.Append("@" + scope.Trim('@') + "/");
            }

            packageString.Append(definition.Package);

            if (definition.HasValue("version", out string version))
            {
                packageString.Append(("@" + version.Trim(':', '=', '@')).Quote());
            }

            arguments.Append(packageString.ToString());
            return(arguments);
        }