-
Notifications
You must be signed in to change notification settings - Fork 368
/
CommandLine.cs
197 lines (169 loc) · 6.13 KB
/
CommandLine.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
// 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using Pocket;
namespace Microsoft.DotNet.Interactive.Utility
{
public static class CommandLine
{
public static Task<CommandLineResult> Execute(
FileInfo exePath,
string args,
DirectoryInfo workingDir = null,
TimeSpan? timeout = null) =>
Execute(exePath.FullName,
args,
workingDir,
timeout);
public static async Task<CommandLineResult> Execute(
string command,
string args,
DirectoryInfo workingDir = null,
TimeSpan? timeout = null)
{
args ??= "";
var stdOut = new StringBuilder();
var stdErr = new StringBuilder();
using (var operation = ConfirmOnExit(command, args))
using (var process = StartProcess(
command,
args,
workingDir,
output: data =>
{
stdOut.AppendLine(data);
},
error: data =>
{
stdErr.AppendLine(data);
}))
{
var exitCode = await process.Complete().Timeout(timeout ?? TimeSpan.FromMinutes(1));
var output = stdOut.Replace("\r\n", "\n").ToString().Split('\n');
var error = stdErr.Replace("\r\n", "\n").ToString().Split(new[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);
if (error.All(string.IsNullOrWhiteSpace))
{
error = null;
}
var result = new CommandLineResult(
exitCode: exitCode,
output: output,
error: error);
if (exitCode == 0)
{
operation.Succeed(
"> {command} {args} -> exited with {code}",
process.StartInfo.FileName,
process.StartInfo.Arguments,
process.ExitCode);
}
else
{
operation.Fail(new CommandLineInvocationException(result));
}
return result;
}
}
public static async Task<int> Complete(
this Process process) =>
await Task.Run(() =>
{
process.WaitForExit();
return process.ExitCode;
});
public static async Task<T> Timeout<T>(
this Task<T> source,
TimeSpan timeout)
{
if (await Task.WhenAny(
source,
Task.Delay(timeout)) != source)
{
throw new TimeoutException();
}
return await source;
}
public static Process StartProcess(
string command,
string args,
DirectoryInfo workingDir,
Action<string> output = null,
Action<string> error = null,
params (string key, string value)[] environmentVariables)
{
using (var operation = Log.OnEnterAndExit())
{
args ??= "";
var process = new Process
{
StartInfo =
{
Arguments = args,
FileName = command,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
WorkingDirectory = workingDir?.FullName ?? string.Empty,
StandardOutputEncoding = Encoding.UTF8
}
};
operation.Info("> {process} {args}", command, args);
if (environmentVariables?.Length > 0)
{
foreach (var tuple in environmentVariables)
{
operation.Trace("Adding environment variable {tuple}", tuple);
process.StartInfo.Environment.Add(tuple.key, tuple.value);
}
}
if (output is not null)
{
process.OutputDataReceived += (sender, eventArgs) =>
{
if (eventArgs.Data is not null)
{
output(eventArgs.Data);
}
};
}
if (error is not null)
{
process.ErrorDataReceived += (sender, eventArgs) =>
{
if (eventArgs.Data is not null)
{
error(eventArgs.Data);
}
};
}
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
return process;
}
}
public static string AppendArgs(this string initial, string append = null) =>
string.IsNullOrWhiteSpace(append)
? initial
: $"{initial} {append}";
private static ConfirmationLogger ConfirmOnExit(
object command,
string args,
[CallerMemberName] string operationName = null)
{
return new ConfirmationLogger(
operationName: operationName,
category: Log.Category,
message: "> {command} {args}",
args: new[] { command, args },
logOnStart: true);
}
private static Logger Log { get; } = new Logger(nameof(CommandLine));
}
}