Example #1
0
        private void StartAppVeyor(ProcessArgumentBuilder arguments, [System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
        {
            var process = _processRunner.Start("appveyor", new ProcessSettings {
                Arguments = arguments
            });

            process.WaitForExit();
            var exitCode = process.GetExitCode();

            if (exitCode != 0)
            {
                throw new CakeException($"{memberName} failed ({exitCode}).");
            }
        }
Example #2
0
        private void RunFirewallCommand(string command)
        {
            var startInfo = new ProcessStartInfo("netsh.exe", command)
            {
                CreateNoWindow = true, UseShellExecute = false
            };
            var firewall = new Process {
                StartInfo = startInfo
            };

            ProcessRunner.Start(firewall);

            ProcessRunner.WaitForExit(firewall, 60000);
        }
Example #3
0
        /// <summary>
        /// Runs the tool using a custom tool path and the specified settings.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="arguments">The arguments.</param>
        /// <param name="toolPath">The tool path to use.</param>
        /// <param name="processSettings">The process settings</param>
        /// <returns>The process that the tool is running under.</returns>
        protected IProcess RunProcess(TSettings settings, ProcessArgumentBuilder arguments, FilePath toolPath,
                                      ProcessSettings processSettings)
        {
            if (arguments == null && (processSettings == null || processSettings.Arguments == null))
            {
                throw new ArgumentNullException("arguments");
            }

            // Get the tool name.
            var toolName = GetToolName();

            // Get the tool path.
            toolPath = GetToolPath(settings, toolPath);
            if (toolPath == null || !_fileSystem.Exist(toolPath))
            {
                const string message = "{0}: Could not locate executable.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Get the working directory.
            var workingDirectory = GetWorkingDirectory(settings);

            if (workingDirectory == null)
            {
                const string message = "{0}: Could not resolve working directory.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Create the process start info.
            var info = processSettings ?? new ProcessSettings();

            if (info.Arguments == null)
            {
                info.Arguments = arguments;
            }
            if (info.WorkingDirectory == null)
            {
                info.WorkingDirectory = workingDirectory.MakeAbsolute(_environment).FullPath;
            }

            // Run the process.
            var process = _processRunner.Start(toolPath, info);

            if (process == null)
            {
                const string message = "{0}: Process was not started.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }
            return(process);
        }
Example #4
0
        /// <summary>
        /// Installs the specified resource at the given location.
        /// </summary>
        /// <param name="package">The package reference.</param>
        /// <param name="type">The package type.</param>
        /// <param name="path">The location where to install the package.</param>
        /// <returns>The installed files.</returns>
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }
            if (path == null)
            {
                throw new ArgumentNullException("path");
            }

            path = path.MakeAbsolute(_environment);

            var root        = _fileSystem.GetDirectory(path);
            var packagePath = path.Combine(package.Package);

            // Create the addin directory if it doesn't exist.
            if (!root.Exists)
            {
                _log.Debug("Creating directory {0}", path);
                root.Create();
            }

            // Fetch available content from disc.
            var content = _contentResolver.GetFiles(packagePath, type);

            if (content.Any())
            {
                _log.Debug("Package {0} has already been installed.", package.Package);
                return(content);
            }

            // Install the package.
            _log.Debug("Installing NuGet package {0}...", package.Package);
            var nugetPath = GetNuGetPath();
            var process   = _processRunner.Start(nugetPath, new ProcessSettings
            {
                Arguments = GetArguments(package, path),
                RedirectStandardOutput = true,
                Silent = true
            });

            process.WaitForExit();

            // Return the files.
            return(_contentResolver.GetFiles(packagePath, type));
        }
Example #5
0
        private IEnumerable <DotnetListPackageResult> CheckForUpdates(Project project)
        {
            foreach (var severity in new[] { "", " --highest-minor", " --highest-patch" })
            {
                var transitive = project.Config.IncludeTransitive ? " --include-transitive" : "";
                var arguments  = $"list {project.FullPath} package --outdated{transitive}{severity}";

                var errors = new List <string>();
                var output = new List <string>();

                var info = new ProcessStartInfo
                {
                    Arguments             = arguments,
                    FileName              = "dotnet",
                    StandardErrorHandler  = s => errors.Add(s),
                    StandardOutputHandler = s => output.Add(s)
                };

                _processRunner.Start(info).Task.Wait();

                errors.RemoveAll(string.IsNullOrWhiteSpace);
                output.RemoveAll(string.IsNullOrWhiteSpace);

                if (errors.Any())
                {
                    project.Errors.Add(new Error
                    {
                        Message = string.Join(Environment.NewLine, errors),
                        Stage   = "analyze"
                    });

                    yield break;
                }

                var parser = new DotnetListPackageResultParser();

                var result = parser.Parse(output);

                if (!result.Frameworks.Any())
                {
                    continue;
                }

                yield return(result);
            }
        }
        public void Generate_WithValidSettings_RunJavaProcess()
        {
            var generator = new OpenApiGenerator(fileSystem, environment, runner, tools, mavenClient);

            generator.Generate(new OpenApiGeneratorGenerateSettings()
            {
                Specification   = "specification.yaml",
                Generator       = "csharp",
                OutputDirectory = "./src"
            });

            A.CallTo(() => runner.Start(javaExecutable, A <ProcessSettings> ._)).MustHaveHappenedOnceExactly();
        }
Example #7
0
        public void Run()
        {
            if (_filesystem.Path.IsPathRooted(ExecutablePath))
            {
                throw new NoRelativePathException(ExecutablePath);
            }
            _runner.Start(new ProcessStartInfo
            {
                FileName         = ExecutablePath,
                Arguments        = Arguments,
                WorkingDirectory = WorkingDirectory
            });

            _runner.WaitForExit();
            if (!AllowedToFail && _runner.ExitCode != 0)
            {
                throw new ProcessFailedException();
            }
        }
Example #8
0
        /// <summary>
        /// Installs the specified resource at the given location.
        /// </summary>
        /// <param name="package">The package reference.</param>
        /// <param name="type">The package type.</param>
        /// <param name="path">The location where to install the package.</param>
        /// <returns>The installed files.</returns>
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

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

            path = path.MakeAbsolute(_environment);

            // Install the package.
            _log.Debug("Installing Chocolatey package {0}...", package.Package);
            var process = _processRunner.Start(
                "choco",
                new ProcessSettings {
                Arguments = GetArguments(package, path, _config), RedirectStandardOutput = true, Silent = _log.Verbosity < Verbosity.Diagnostic
            });

            process.WaitForExit();

            var exitCode = process.GetExitCode();

            if (exitCode != 0)
            {
                _log.Warning("Chocolatey exited with {0}", exitCode);
                var output = string.Join(Environment.NewLine, process.GetStandardOutput());
                _log.Verbose(Verbosity.Diagnostic, "Output:\r\n{0}", output);
            }

            var result = _contentResolver.GetFiles(package, type);

            if (result.Count != 0)
            {
                return(result);
            }

            // TODO: maybe some warnings here
            return(result);
        }
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            if (_environment.Platform.Family != PlatformFamily.Linux)
            {
                _log.Warning("Non-Linux platform detected! Not attempting installation...");
                return(_contentResolver.GetFiles(package, type));
            }

            // Install the package.
            _log.Debug("Installing package {0} with APT...", package.Package);
            var process = _processRunner.Start(
                "apt-get",
                new ProcessSettings {
                Arguments = GetArguments(package, _config), RedirectStandardOutput = true, Silent = _log.Verbosity < Verbosity.Diagnostic
            });

            process.WaitForExit();

            var exitCode = process.GetExitCode();

            if (exitCode != 0)
            {
                _log.Warning("APT exited with {0}", exitCode);
                var output = string.Join(Environment.NewLine, process.GetStandardOutput());
                _log.Verbose(Verbosity.Diagnostic, "Output:\r\n{0}", output);
            }

            var result = _contentResolver.GetFiles(package, type);

            if (result.Count != 0)
            {
                return(result);
            }

            // TODO: maybe some warnings here
            return(result);
        }
Example #10
0
        public void RunWurmAssistant([NotNull] string buildNumber)
        {
            if (buildNumber == null)
            {
                throw new ArgumentNullException("buildNumber");
            }

            var exepath = Path.Combine(installDirPath, buildNumber, "AldursLab.WurmAssistant3.exe");
            var args    = string.Empty;

            if (config.WurmUnlimitedMode)
            {
                args += " -WurmUnlimited";
            }
            if (config.UseRelativeDataDirPath)
            {
                args += " -RelativeDataDir";
            }
            processRunner.Start(exepath, args);
        }
        private void ExecuteProcess(FilePath filePath, ProcessArgumentBuilder arguments, int timeout = 60000)
        {
            try
            {
                filePath = filePath.MakeAbsolute(_Environment.WorkingDirectory);

                _Runner.Start(filePath, new ProcessSettings()
                {
                    Arguments = arguments
                })
                .WaitForExit(timeout);
            }
            catch (Exception ex)
            {
                if (!(ex is TimeoutException))
                {
                    throw;
                }

                _Log.Warning("Process timed out!");
            }
        }
Example #12
0
        /// <summary>
        /// Sets and environment variable that can be used in next steps on Bitrise.
        /// </summary>
        /// <param name="variable">The variable.</param>
        /// <param name="value">The value.</param>
        public void SetEnvironmentString(string variable, string value)
        {
            var arguments = new ProcessArgumentBuilder()
                            .Append("add")
                            .Append("--key")
                            .Append(variable)
                            .Append("--value")
                            .AppendQuoted(value);

            var process = _processRunner.Start("envman", new ProcessSettings
            {
                Arguments = arguments
            });

            process.WaitForExit();
            var exitCode = process.GetExitCode();

            if (exitCode != 0)
            {
                throw new CakeException($"BitriseProvider SetEnvironmentString failed ({exitCode}).");
            }
        }
        private void InstallPackage(PackageReference package, DirectoryPath path)
        {
            _log.Debug("Installing NuGet package {0}...", package.Package);

            var nugetPath = GetNuGetPath();
            var process   = _processRunner.Start(nugetPath, new ProcessSettings
            {
                Arguments = GetArguments(package, path, _config),
                RedirectStandardOutput = true,
                Silent = _log.Verbosity < Verbosity.Diagnostic
            });

            process.WaitForExit();

            var exitCode = process.GetExitCode();

            if (exitCode != 0)
            {
                _log.Warning("NuGet exited with {0}", exitCode);
                var output = string.Join(Environment.NewLine, process.GetStandardOutput());
                _log.Verbose(Verbosity.Diagnostic, "Output:\r\n{0}", output);
            }
        }
Example #14
0
        public MSBuildRunnerFixture(bool is64BitOperativeSystem = false,
                                    bool msBuildFileExist       = true)
        {
            Process = Substitute.For <IProcess>();

            ProcessRunner = Substitute.For <IProcessRunner>();
            ProcessRunner.Start(Arg.Any <ProcessStartInfo>()).Returns(Process);

            Environment = Substitute.For <ICakeEnvironment>();
            Environment.Is64BitOperativeSystem().Returns(is64BitOperativeSystem);
            Environment.GetSpecialPath(SpecialPath.ProgramFilesX86).Returns("/Program86");
            Environment.GetSpecialPath(SpecialPath.Windows).Returns("/Windows");
            Environment.WorkingDirectory.Returns("/Working");

            FileSystem = Substitute.For <IFileSystem>();
            FileSystem.GetFile(Arg.Is <FilePath>(p => p.FullPath.EndsWith("MSBuild.exe", System.StringComparison.Ordinal)))
            .Returns(c => {
                // All requested files exist.
                var file = Substitute.For <IFile>();
                file.Exists.Returns(msBuildFileExist);
                file.Path.Returns(c.Arg <FilePath>());
                return(file);
            });
        }
Example #15
0
File: Tool.cs Project: gitfool/cake
        /// <summary>
        /// Runs the tool using a custom tool path and the specified settings.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="arguments">The arguments.</param>
        /// <param name="processSettings">The process settings.</param>
        /// <returns>The process that the tool is running under.</returns>
        protected IProcess RunProcess(
            TSettings settings,
            ProcessArgumentBuilder arguments,
            ProcessSettings processSettings)
        {
            if (arguments == null && (processSettings?.Arguments == null))
            {
                throw new ArgumentNullException(nameof(arguments));
            }

            // Should we customize the arguments?
            if (settings.ArgumentCustomization != null)
            {
                arguments = settings.ArgumentCustomization(arguments);
            }

            // Get the tool name.
            var toolName = GetToolName();

            // Get the tool path.
            var toolPath = GetToolPath(settings);

            if (toolPath == null || !_fileSystem.Exist(toolPath))
            {
                const string message = "{0}: Could not locate executable.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Get the working directory.
            var workingDirectory = GetWorkingDirectory(settings);

            if (workingDirectory == null)
            {
                const string message = "{0}: Could not resolve working directory.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Create the process start info.
            var info = processSettings ?? new ProcessSettings();

            if (info.Arguments == null)
            {
                info.Arguments = arguments;
            }
            if (info.WorkingDirectory == null)
            {
                info.WorkingDirectory = workingDirectory.MakeAbsolute(_environment).FullPath;
            }
            if (info.EnvironmentVariables == null)
            {
                info.EnvironmentVariables = GetEnvironmentVariables(settings);
            }

            // Want to opt out of using a working directory?
            info.NoWorkingDirectory = settings.NoWorkingDirectory;

            // Configure process settings
            settings.SetupProcessSettings?.Invoke(info);

            // Run the process.
            var process = _processRunner.Start(toolPath, info);

            if (process == null)
            {
                const string message = "{0}: Process was not started.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            return(process);
        }
Example #16
0
 public IProcess Start(FilePath filePath, ProcessSettings settings)
 {
     // Prepends "dotnet" to the tool path
     settings.Arguments.Prepend(filePath.FullPath);
     return(_processRunner.Start("dotnet", settings));
 }
        /// <summary>
        /// Installs the specified resource.
        /// </summary>
        /// <param name="package">The package resource.</param>
        /// <param name="type">The package type.</param>
        /// <param name="path">The location where to install the resource.</param>
        /// <returns>The installed files.</returns>
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }

            // find npm
            _log.Debug("looking for npm.cmd");
            var npmTool = _toolLocator.Resolve("npm.cmd");

            if (npmTool == null)
            {
                _log.Debug("looking for npm");
                npmTool = _toolLocator.Resolve("npm");
            }

            if (npmTool == null)
            {
                throw new FileNotFoundException("npm could not be found.");
            }

            _log.Debug("Found npm at {0}", npmTool);

            // Install the package.
            _log.Debug("Installing package {0} with npm...", package.Package);
            var workingDir = _environment.WorkingDirectory;

            if (GetModuleInstallationLocation(package) == ModulesInstallationLocation.Tools)
            {
                var toolsFolder = _fileSystem.GetDirectory(
                    _config.GetToolPath(_environment.WorkingDirectory, _environment));

                if (!toolsFolder.Exists)
                {
                    toolsFolder.Create();
                }

                _log.Debug("Installing into cake-tools location: {0}", package.Package);
                workingDir = toolsFolder.Path;
            }

            var process = _processRunner.Start(
                npmTool.FullPath,
                new ProcessSettings
            {
                Arguments              = GetArguments(package, _config),
                WorkingDirectory       = workingDir,
                RedirectStandardOutput = true,
                Silent = _log.Verbosity < Verbosity.Diagnostic,
            });

            process.WaitForExit();

            var exitCode = process.GetExitCode();

            if (exitCode != 0)
            {
                _log.Warning("npm exited with {0}", exitCode);
                var output = string.Join(Environment.NewLine, process.GetStandardOutput());
                _log.Verbose(Verbosity.Diagnostic, "Output:\r\n{0}", output);
            }

            var result = _contentResolver.GetFiles(package, type, GetModuleInstallationLocation(package));

            if (result.Count != 0)
            {
                return(result);
            }

            _log.Warning("Could not determine installed package files! Installation may not be complete.");

            // TODO: maybe some warnings here
            return(result);
        }
Example #18
0
        /// <summary>
        /// Runs the tool using a custom tool path and the specified settings.
        /// </summary>
        /// <param name="settings">The settings.</param>
        /// <param name="arguments">The arguments.</param>
        /// <param name="toolPath">The tool path to use.</param>
        /// <param name="processSettings">The process settings</param>
        /// <param name="postAction">If specified called after process exit</param>
        protected void Run(TSettings settings, ProcessArgumentBuilder arguments, FilePath toolPath, ProcessSettings processSettings, Action <IProcess> postAction)
        {
            if (arguments == null && (processSettings == null || processSettings.Arguments == null))
            {
                throw new ArgumentNullException("arguments");
            }

            // Get the tool name.
            var toolName = GetToolName();

            // Get the tool path.
            toolPath = GetToolPath(settings, toolPath);
            if (toolPath == null || !_fileSystem.Exist(toolPath))
            {
                const string message = "{0}: Could not locate executable.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Get the working directory.
            var workingDirectory = GetWorkingDirectory(settings);

            if (workingDirectory == null)
            {
                const string message = "{0}: Could not resolve working directory.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Create the process start info.
            var info = processSettings ?? new ProcessSettings();

            if (info.Arguments == null)
            {
                info.Arguments = arguments;
            }
            if (info.WorkingDirectory == null)
            {
                info.WorkingDirectory = workingDirectory.MakeAbsolute(_environment).FullPath;
            }

            // Run the process.
            var process = _processRunner.Start(toolPath, info);

            if (process == null)
            {
                const string message = "{0}: Process was not started.";
                throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
            }

            // Wait for the process to exit.
            process.WaitForExit();

            try
            {
                // Did an error occur?
                if (process.GetExitCode() != 0)
                {
                    const string message = "{0}: Process returned an error.";
                    throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
                }
            }
            finally
            {
                // Post action specified?
                if (postAction != null)
                {
                    postAction(process);
                }
            }
        }
Example #19
0
        public void Run()
        {
            if (_args.Length == 0 || (_args[0] == "-h"))
            {
                string usageInfo = GetUsageInfo();
                ConsoleContext.Current.WriteLine(usageInfo);
                EnvironmentContext.Current.Exit(0);
                return;
            }

            string serviceName = _args.ExtractServiceName();

            if (string.IsNullOrEmpty(serviceName))
            {
                ConsoleContext.Current.WriteLine("ERROR: Invalid argument, please enter a valid aws cli command");
                EnvironmentContext.Current.Exit(1);
                return;
            }

            AwsServiceEndpoint?awsServiceEndpoint = _config.GetServiceEndpoint(serviceName);

            if (awsServiceEndpoint == null)
            {
                ConsoleContext.Current.WriteLine($"ERROR: Unable to find LocalStack endpoint for service {serviceName}");
                EnvironmentContext.Current.Exit(1);
                return;
            }

            var processSettings = new ProcessSettings
            {
                NoWorkingDirectory = true, Silent = true, EnvironmentVariables = new Dictionary <string, string>()
            };

            string?defaultRegion = Environment.GetEnvironmentVariable("DEFAULT_REGION");

            if (!string.IsNullOrEmpty(defaultRegion))
            {
                ConsoleContext.Current.WriteLine("Environment variable \"AWS_DEFAULT_REGION\" will be overwritten by \"DEFAULT_REGION\"");

                Environment.SetEnvironmentVariable("AWS_DEFAULT_REGION", defaultRegion);
            }

            processSettings.EnvironmentVariables.Add("AWS_DEFAULT_REGION", Environment.GetEnvironmentVariable("AWS_DEFAULT_REGION") ?? "us-east-1");
            processSettings.EnvironmentVariables.Add("AWS_ACCESS_KEY_ID", Environment.GetEnvironmentVariable("AWS_ACCESS_KEY_ID") ?? "_not_needed_locally_");
            processSettings.EnvironmentVariables.Add("AWS_SECRET_ACCESS_KEY", Environment.GetEnvironmentVariable("AWS_SECRET_ACCESS_KEY") ?? "_not_needed_locally_");


            var builder = new ProcessArgumentBuilder();

            builder.Append(_args[0]);
            builder.AppendSwitch("--endpoint-url", "=", awsServiceEndpoint.ServiceUrl);

            if (awsServiceEndpoint.ServiceUrl.StartsWith("https"))
            {
                builder.Append("--no-verify-ssl");
            }

            var passToNextArgument = false;

            for (var i = 0; i < _args.Length; i++)
            {
                string argument = _args[i];

                if (argument == _args[0])
                {
                    continue;
                }

                if (passToNextArgument)
                {
                    passToNextArgument = false;
                    continue;
                }


                if (argument.StartsWith("--") && !argument.Contains("=") && i + 1 < _args.Length) // switch argument
                {
                    string nextArgument = _args[i + 1];
                    builder.AppendSwitchQuoted(argument, " ", nextArgument);

                    passToNextArgument = true;
                    continue;
                }

                builder.Append(argument);
            }


            processSettings.Arguments = builder;

            string[] awsExec = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
                ? new[] { "aws.exe", "aws.cmd" }
                : new[] { "aws" };

            FilePath?awsPath = GetAwsPath(awsExec);

            if (awsPath == null)
            {
                ConsoleContext.Current.WriteLine(
                    $"ERROR: Unable to find aws cli. Executable name: {string.Join(',', awsExec)}");
                EnvironmentContext.Current.Exit(1);
                return;
            }

            IProcess?process = _processRunner.Start(awsPath, processSettings);

            process?.WaitForExit();
        }
        /// <summary>
        /// Installs the specified resource at the given location.
        /// </summary>
        /// <param name="package">The package reference.</param>
        /// <param name="type">The package type.</param>
        /// <param name="path">The location where to install the package.</param>
        /// <returns>The installed files.</returns>
        public IReadOnlyCollection <IFile> Install(PackageReference package, PackageType type, DirectoryPath path)
        {
            if (package == null)
            {
                throw new ArgumentNullException(nameof(package));
            }
            if (path == null)
            {
                throw new ArgumentNullException(nameof(path));
            }

            path = path.MakeAbsolute(_environment);

            var root        = _fileSystem.GetDirectory(path);
            var packagePath = path.Combine(package.Package);

            // Create the addin directory if it doesn't exist.
            if (!root.Exists)
            {
                _log.Debug("Creating directory {0}", path);
                root.Create();
            }

            // Fetch available content from disc.
            var content = _contentResolver.GetFiles(packagePath, package, type);

            if (content.Any())
            {
                _log.Debug("Package {0} has already been installed.", package.Package);
                return(content);
            }

            // Install the package.
            _log.Debug("Installing NuGet package {0}...", package.Package);
            var nugetPath = GetNuGetPath();
            var process   = _processRunner.Start(nugetPath, new ProcessSettings
            {
                Arguments = GetArguments(package, path, _config),
                RedirectStandardOutput = true,
                Silent = _log.Verbosity < Verbosity.Diagnostic
            });

            process.WaitForExit();

            var exitCode = process.GetExitCode();

            if (exitCode != 0)
            {
                _log.Warning("NuGet exited with {0}", exitCode);
                var output = string.Join(Environment.NewLine, process.GetStandardOutput());
                _log.Verbose(Verbosity.Diagnostic, "Output:\r\n{0}", output);
            }

            // Get the files.
            var result = _contentResolver.GetFiles(packagePath, package, type);

            if (result.Count == 0)
            {
                if (type == PackageType.Addin)
                {
                    var framework = _environment.Runtime.TargetFramework;
                    _log.Warning("Could not find any assemblies compatible with {0}.", framework.FullName);
                }
                else if (type == PackageType.Tool)
                {
                    const string format = "Could not find any relevant files for tool '{0}'. Perhaps you need an include parameter?";
                    _log.Warning(format, package.Package);
                }
            }

            return(result);
        }
        protected override IEnumerable <FilePath> GetAlternativeToolPaths(KnifeSettings settings)
        {
            var toolPaths       = new List <FilePath>(base.GetAlternativeToolPaths(settings));
            var chefdkInstalled = false;

            const string defaultPathWin = @"C:\opscode\chefdk\bin";
            const string defaultPathNix = "/usr/bin";

            //Look for chefdk installed on the system
            var defaultPath = _environment.Platform.IsUnix() ? _fileSystem.GetDirectory(defaultPathNix) : _fileSystem.GetDirectory(defaultPathWin);
            var knifeExec   = _environment.Platform.IsUnix() ? _fileSystem.GetFile(_executableNames.Single(x => !x.EndsWith(".bat"))) : _fileSystem.GetFile(_executableNames.Single(x => x.EndsWith(".bat")));

            var knifePath = defaultPath.Path.CombineWithFilePath(knifeExec.Path);

            if (_fileSystem.Exist(knifePath))
            {
                chefdkInstalled = true;
            }

            if (!String.IsNullOrWhiteSpace(_environment.GetEnvironmentVariable("CHEF_DK_INSTALL_PATH")))
            {
                knifePath = _environment.GetEnvironmentVariable("CHEF_DK_INSTALL_PATH");
                if (_fileSystem.Exist(knifePath))
                {
                    chefdkInstalled = true;
                }
            }

            if (chefdkInstalled)
            {
                toolPaths.Add(knifePath);
                return(toolPaths);
            }

            if (_environment.Platform.Family != PlatformFamily.Windows)
            {
                throw new NotImplementedException("Knife executable not found--automatic install of chef dk is currently only supported on windows.");
            }

            //Install chefdk on the system if it isn't found
            var installerFileName = $"chefdk-{settings.ChefDKVersion}-1-x86.msi";
            var packageUri        = $"https://packages.chef.io/stable/windows/2012r2/{installerFileName}";

            byte[] installerBytes = null;
            using (var httpClient = new HttpClient())
            {
                installerBytes = httpClient.GetByteArrayAsync(packageUri).Result;
            }

            var installerPath = _fileSystem
                                .GetFile(_environment.GetSpecialPath(SpecialPath.LocalTemp)
                                         .GetFilePath(installerFileName));

            installerPath
            .OpenWrite()
            .Write(installerBytes, 0, installerBytes.Length);

            _processRunner
            .Start(installerPath.Path, new ProcessSettings {
                Arguments = new ProcessArgumentBuilder().Append("/qn /quiet /norestart")
            })
            .WaitForExit();

            toolPaths.Add(knifePath);
            return(toolPaths);
        }