-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
ToolCommand.cs
225 lines (184 loc) · 7.06 KB
/
ToolCommand.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
// 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.Threading.Tasks;
using Xunit.Abstractions;
#nullable enable
namespace Wasm.Build.Tests
{
public class ToolCommand : IDisposable
{
private bool isDisposed = false;
private string _label;
protected ITestOutputHelper _testOutput;
protected string _command;
public Process? CurrentProcess { get; private set; }
public Dictionary<string, string> Environment { get; } = new Dictionary<string, string>();
public event DataReceivedEventHandler? ErrorDataReceived;
public event DataReceivedEventHandler? OutputDataReceived;
public string? WorkingDirectory { get; set; }
public ToolCommand(string command, ITestOutputHelper testOutput, string label="")
{
_command = command;
_testOutput = testOutput;
_label = label;
}
public ToolCommand WithWorkingDirectory(string dir)
{
WorkingDirectory = dir;
return this;
}
public ToolCommand WithEnvironmentVariable(string key, string value)
{
Environment[key] = value;
return this;
}
public ToolCommand WithEnvironmentVariables(IDictionary<string, string>? extraEnvVars)
{
if (extraEnvVars != null)
{
foreach ((string key, string value) in extraEnvVars)
Environment[key] = value;
}
return this;
}
public ToolCommand WithOutputDataReceived(Action<string?> handler)
{
OutputDataReceived += (_, args) => handler(args.Data);
return this;
}
public ToolCommand WithErrorDataReceived(Action<string?> handler)
{
ErrorDataReceived += (_, args) => handler(args.Data);
return this;
}
public virtual CommandResult Execute(params string[] args)
{
return Task.Run(async () => await ExecuteAsync(args)).Result;
}
public async virtual Task<CommandResult> ExecuteAsync(params string[] args)
{
var resolvedCommand = _command;
string fullArgs = GetFullArgs(args);
_testOutput.WriteLine($"[{_label}] Executing - {resolvedCommand} {fullArgs} {WorkingDirectoryInfo()}");
return await ExecuteAsyncInternal(resolvedCommand, fullArgs);
}
public virtual CommandResult ExecuteWithCapturedOutput(params string[] args)
{
var resolvedCommand = _command;
string fullArgs = GetFullArgs(args);
_testOutput.WriteLine($"[{_label}] Executing (Captured Output) - {resolvedCommand} {fullArgs} - {WorkingDirectoryInfo()}");
return Task.Run(async () => await ExecuteAsyncInternal(resolvedCommand, fullArgs)).Result;
}
public virtual void Dispose()
{
if (isDisposed)
return;
if (CurrentProcess is not null && !CurrentProcess.HasExited)
{
CurrentProcess.Kill(entireProcessTree: true);
CurrentProcess.Dispose();
CurrentProcess = null;
}
isDisposed = true;
}
protected virtual string GetFullArgs(params string[] args) => string.Join(" ", args);
private async Task<CommandResult> ExecuteAsyncInternal(string executable, string args)
{
var output = new List<string>();
CurrentProcess = CreateProcess(executable, args);
DataReceivedEventHandler errorHandler = (s, e) =>
{
if (e.Data == null || isDisposed)
return;
string msg = $"[{_label}] {e.Data}";
output.Add(msg);
_testOutput.WriteLine(msg);
ErrorDataReceived?.Invoke(s, e);
};
DataReceivedEventHandler outputHandler = (s, e) =>
{
if (e.Data == null || isDisposed)
return;
string msg = $"[{_label}] {e.Data}";
output.Add(msg);
_testOutput.WriteLine(msg);
OutputDataReceived?.Invoke(s, e);
};
CurrentProcess.ErrorDataReceived += errorHandler;
CurrentProcess.OutputDataReceived += outputHandler;
var completionTask = CurrentProcess.StartAndWaitForExitAsync();
CurrentProcess.BeginOutputReadLine();
CurrentProcess.BeginErrorReadLine();
await completionTask;
CurrentProcess.ErrorDataReceived -= errorHandler;
CurrentProcess.OutputDataReceived -= outputHandler;
RemoveNullTerminator(output);
return new CommandResult(
CurrentProcess.StartInfo,
CurrentProcess.ExitCode,
string.Join(System.Environment.NewLine, output));
}
private Process CreateProcess(string executable, string args)
{
var psi = new ProcessStartInfo
{
FileName = executable,
Arguments = args,
RedirectStandardError = true,
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false
};
psi.Environment["DOTNET_MULTILEVEL_LOOKUP"] = "0";
psi.Environment["DOTNET_SKIP_FIRST_TIME_EXPERIENCE"] = "1";
// runtime repo sets this, which interferes with the tests
psi.RemoveEnvironmentVariables("MSBuildSDKsPath");
AddEnvironmentVariablesTo(psi);
AddWorkingDirectoryTo(psi);
var process = new Process
{
StartInfo = psi
};
process.EnableRaisingEvents = true;
return process;
}
private string WorkingDirectoryInfo()
{
if (WorkingDirectory == null)
{
return "";
}
return $" in pwd {WorkingDirectory}";
}
private void RemoveNullTerminator(List<string> strings)
{
var count = strings.Count;
if (count < 1)
{
return;
}
if (strings[count - 1] == null)
{
strings.RemoveAt(count - 1);
}
}
private void AddEnvironmentVariablesTo(ProcessStartInfo psi)
{
foreach (var item in Environment)
{
_testOutput.WriteLine($"\t[{item.Key}] = {item.Value}");
psi.Environment[item.Key] = item.Value;
}
}
private void AddWorkingDirectoryTo(ProcessStartInfo psi)
{
if (!string.IsNullOrWhiteSpace(WorkingDirectory))
{
psi.WorkingDirectory = WorkingDirectory;
}
}
}
}