dotnet-installer/src/Microsoft.DotNet.Cli.Utils/Command.cs

215 lines
6.5 KiB
C#
Raw Normal View History

// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using NuGet.Frameworks;
namespace Microsoft.DotNet.Cli.Utils
{
2016-01-05 23:48:50 -08:00
public class Command
{
2015-12-07 14:18:09 -08:00
private readonly Process _process;
private readonly StreamForwarder _stdOut;
private readonly StreamForwarder _stdErr;
private bool _running = false;
2016-01-06 02:27:16 -08:00
private Command(CommandSpec commandSpec)
{
2016-01-06 02:27:16 -08:00
var psi = new ProcessStartInfo
{
2016-01-06 02:27:16 -08:00
FileName = commandSpec.Path,
Arguments = commandSpec.Args,
RedirectStandardError = true,
RedirectStandardOutput = true
};
2016-01-06 02:27:16 -08:00
_stdOut = new StreamForwarder();
_stdErr = new StreamForwarder();
_process = new Process
{
StartInfo = psi
};
2015-12-07 14:18:09 -08:00
2016-01-06 02:27:16 -08:00
ResolutionStrategy = commandSpec.ResolutionStrategy;
}
public static Command CreateDotNet(string commandName, IEnumerable<string> args, NuGetFramework framework = null, bool useComSpec = false)
{
return Create("dotnet", new[] { commandName }.Concat(args), framework, useComSpec);
}
/// <summary>
/// Create a command with the specified arg array. Args will be
/// escaped properly to ensure that exactly the strings in this
/// array will be present in the corresponding argument array
/// in the command's process.
/// </summary>
/// <param name="commandName"></param>
/// <param name="args"></param>
/// <param name="framework"></param>
/// <returns></returns>
public static Command Create(string commandName, IEnumerable<string> args, NuGetFramework framework = null, bool useComSpec = false)
{
var commandSpec = CommandResolver.TryResolveCommandSpec(commandName, args, framework, useComSpec);
2015-10-15 12:18:45 -07:00
2016-01-06 02:27:16 -08:00
if (commandSpec == null)
{
2016-01-06 02:27:16 -08:00
throw new CommandUnknownException(commandName);
}
2016-01-06 02:27:16 -08:00
var command = new Command(commandSpec);
2016-01-06 02:27:16 -08:00
return command;
}
2016-01-06 02:27:16 -08:00
public CommandResult Execute()
{
Reporter.Verbose.WriteLine($"Running {_process.StartInfo.FileName} {_process.StartInfo.Arguments}");
ThrowIfRunning();
_running = true;
_process.EnableRaisingEvents = true;
#if DEBUG
2015-10-18 21:24:26 -07:00
var sw = Stopwatch.StartNew();
2015-11-01 16:21:10 -08:00
Reporter.Verbose.WriteLine($"> {FormatProcessInfo(_process.StartInfo)}".White());
#endif
_process.Start();
2015-11-29 10:58:13 -08:00
Reporter.Verbose.WriteLine($"Process ID: {_process.Id}");
2015-12-07 14:18:09 -08:00
var threadOut = _stdOut.BeginRead(_process.StandardOutput);
var threadErr = _stdErr.BeginRead(_process.StandardError);
_process.WaitForExit();
2015-12-07 14:18:09 -08:00
threadOut.Join();
threadErr.Join();
var exitCode = _process.ExitCode;
#if DEBUG
2015-10-22 05:31:24 -07:00
var message = $"< {FormatProcessInfo(_process.StartInfo)} exited with {exitCode} in {sw.ElapsedMilliseconds} ms.";
2015-10-20 02:42:29 -07:00
if (exitCode == 0)
{
2015-11-01 16:21:10 -08:00
Reporter.Verbose.WriteLine(message.Green());
2015-10-20 02:42:29 -07:00
}
else
{
2015-11-01 16:21:10 -08:00
Reporter.Verbose.WriteLine(message.Red().Bold());
2015-10-20 02:42:29 -07:00
}
#endif
return new CommandResult(
this._process.StartInfo,
exitCode,
2015-12-07 14:18:09 -08:00
_stdOut.GetCapturedOutput(),
_stdErr.GetCapturedOutput());
}
public Command WorkingDirectory(string projectDirectory)
{
_process.StartInfo.WorkingDirectory = projectDirectory;
return this;
}
2015-10-30 15:40:13 -07:00
public Command EnvironmentVariable(string name, string value)
{
2015-11-01 06:24:31 -08:00
_process.StartInfo.Environment[name] = value;
2015-10-30 15:40:13 -07:00
return this;
}
public Command CaptureStdOut()
{
ThrowIfRunning();
2015-12-07 14:18:09 -08:00
_stdOut.Capture();
return this;
}
public Command CaptureStdErr()
{
ThrowIfRunning();
2015-12-07 14:18:09 -08:00
_stdErr.Capture();
return this;
}
2015-11-01 16:21:10 -08:00
public Command ForwardStdOut(TextWriter to = null, bool onlyIfVerbose = false)
{
ThrowIfRunning();
2015-11-01 16:21:10 -08:00
if (!onlyIfVerbose || CommandContext.IsVerbose())
{
if (to == null)
{
2015-12-07 14:18:09 -08:00
_stdOut.ForwardTo(write: Reporter.Output.Write, writeLine: Reporter.Output.WriteLine);
2015-11-01 16:21:10 -08:00
}
else
{
2015-12-07 14:18:09 -08:00
_stdOut.ForwardTo(write: to.Write, writeLine: to.WriteLine);
2015-11-01 16:21:10 -08:00
}
}
return this;
}
2015-11-01 16:21:10 -08:00
public Command ForwardStdErr(TextWriter to = null, bool onlyIfVerbose = false)
{
ThrowIfRunning();
2015-11-01 16:21:10 -08:00
if (!onlyIfVerbose || CommandContext.IsVerbose())
{
if (to == null)
{
2015-12-07 14:18:09 -08:00
_stdErr.ForwardTo(write: Reporter.Error.Write, writeLine: Reporter.Error.WriteLine);
2015-11-01 16:21:10 -08:00
}
else
{
2015-12-07 14:18:09 -08:00
_stdErr.ForwardTo(write: to.Write, writeLine: to.WriteLine);
2015-11-01 16:21:10 -08:00
}
}
return this;
}
public Command OnOutputLine(Action<string> handler)
{
ThrowIfRunning();
2015-12-07 14:18:09 -08:00
_stdOut.ForwardTo(write: null, writeLine: handler);
return this;
}
public Command OnErrorLine(Action<string> handler)
{
ThrowIfRunning();
2015-12-07 14:18:09 -08:00
_stdErr.ForwardTo(write: null, writeLine: handler);
return this;
}
public CommandResolutionStrategy ResolutionStrategy { get; }
public string CommandName => _process.StartInfo.FileName;
private string FormatProcessInfo(ProcessStartInfo info)
{
if (string.IsNullOrWhiteSpace(info.Arguments))
{
return info.FileName;
}
return info.FileName + " " + info.Arguments;
}
private void ThrowIfRunning([CallerMemberName] string memberName = null)
{
if (_running)
{
throw new InvalidOperationException($"Unable to invoke {memberName} after the command has been run");
}
}
2015-12-07 14:18:09 -08:00
}
}