-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathCommandLineInvocationService.cs
204 lines (178 loc) · 7.84 KB
/
CommandLineInvocationService.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
namespace Microsoft.ComponentDetection.Common;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ComponentDetection.Common.Telemetry.Records;
using Microsoft.ComponentDetection.Contracts;
/// <inheritdoc/>
public class CommandLineInvocationService : ICommandLineInvocationService
{
private readonly IDictionary<string, string> commandLocatableCache = new ConcurrentDictionary<string, string>();
/// <inheritdoc/>
public async Task<bool> CanCommandBeLocatedAsync(string command, IEnumerable<string> additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters)
{
additionalCandidateCommands ??= [];
parameters ??= [];
var allCommands = new[] { command }.Concat(additionalCandidateCommands);
if (!this.commandLocatableCache.TryGetValue(command, out var validCommand))
{
foreach (var commandToTry in allCommands)
{
using var record = new CommandLineInvocationTelemetryRecord();
var joinedParameters = string.Join(" ", parameters);
try
{
var result = await RunProcessAsync(commandToTry, joinedParameters, workingDirectory);
record.Track(result, commandToTry, joinedParameters);
if (result.ExitCode == 0)
{
this.commandLocatableCache[command] = validCommand = commandToTry;
break;
}
}
catch (Exception ex) when (ex is Win32Exception || ex is FileNotFoundException || ex is PlatformNotSupportedException)
{
// When we get an exception indicating the command cannot be found.
record.Track(ex, commandToTry, joinedParameters);
}
}
}
return !string.IsNullOrWhiteSpace(validCommand);
}
/// <inheritdoc/>
public async Task<CommandLineExecutionResult> ExecuteCommandAsync(
string command,
IEnumerable<string> additionalCandidateCommands = null,
DirectoryInfo workingDirectory = null,
CancellationToken cancellationToken = default,
params string[] parameters)
{
var isCommandLocatable = await this.CanCommandBeLocatedAsync(command, additionalCandidateCommands, workingDirectory, parameters);
if (!isCommandLocatable)
{
throw new InvalidOperationException(
$"{nameof(this.ExecuteCommandAsync)} was called with a command that could not be located: `{command}`!");
}
if (workingDirectory != null && !Directory.Exists(workingDirectory.FullName))
{
throw new InvalidOperationException(
$"{nameof(this.ExecuteCommandAsync)} was called with a working directory that could not be located: `{workingDirectory.FullName}`");
}
using var record = new CommandLineInvocationTelemetryRecord();
var pathToRun = this.commandLocatableCache[command];
var joinedParameters = string.Join(" ", parameters);
var commandForLogging = joinedParameters.RemoveSensitiveInformation();
try
{
var result = await RunProcessAsync(pathToRun, joinedParameters, workingDirectory, cancellationToken);
record.Track(result, pathToRun, commandForLogging);
return result;
}
catch (Exception ex)
{
record.Track(ex, pathToRun, commandForLogging);
throw;
}
}
/// <inheritdoc/>
public bool IsCommandLineExecution()
{
return true;
}
/// <inheritdoc/>
public async Task<bool> CanCommandBeLocatedAsync(string command, IEnumerable<string> additionalCandidateCommands = null, params string[] parameters)
{
return await this.CanCommandBeLocatedAsync(command, additionalCandidateCommands, workingDirectory: null, parameters);
}
/// <inheritdoc/>
public async Task<CommandLineExecutionResult> ExecuteCommandAsync(string command, IEnumerable<string> additionalCandidateCommands = null, CancellationToken cancellationToken = default, params string[] parameters)
{
return await this.ExecuteCommandAsync(command, additionalCandidateCommands, workingDirectory: null, cancellationToken, parameters);
}
/// <inheritdoc/>
public async Task<CommandLineExecutionResult> ExecuteCommandAsync(
string command,
IEnumerable<string> additionalCandidateCommands = null,
DirectoryInfo workingDirectory = null,
params string[] parameters)
{
return await this.ExecuteCommandAsync(command, additionalCandidateCommands, workingDirectory, CancellationToken.None, parameters);
}
/// <inheritdoc/>
public async Task<CommandLineExecutionResult> ExecuteCommandAsync(string command, IEnumerable<string> additionalCandidateCommands = null, params string[] parameters)
{
return await this.ExecuteCommandAsync(command, additionalCandidateCommands, workingDirectory: null, CancellationToken.None, parameters);
}
private static Task<CommandLineExecutionResult> RunProcessAsync(string fileName, string parameters, DirectoryInfo workingDirectory = null)
{
return RunProcessAsync(fileName, parameters, workingDirectory, CancellationToken.None);
}
private static Task<CommandLineExecutionResult> RunProcessAsync(string fileName, string parameters, DirectoryInfo workingDirectory = null, CancellationToken cancellationToken = default)
{
var tcs = new TaskCompletionSource<CommandLineExecutionResult>();
if (fileName.EndsWith(".cmd") || fileName.EndsWith(".bat"))
{
// If a script attempts to find its location using "%dp0", that can return the wrong path (current
// working directory) unless the script is run via "cmd /C". An example is "ant.bat".
parameters = $"/C {fileName} {parameters}";
fileName = "cmd.exe";
}
var process = new Process
{
StartInfo =
{
FileName = fileName,
Arguments = parameters,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
},
EnableRaisingEvents = true,
};
if (workingDirectory != null)
{
process.StartInfo.WorkingDirectory = workingDirectory.FullName;
}
var errorText = string.Empty;
var stdOutText = string.Empty;
var t1 = new Task(() =>
{
errorText = process.StandardError.ReadToEnd();
});
var t2 = new Task(() =>
{
stdOutText = process.StandardOutput.ReadToEnd();
});
process.Exited += (sender, args) =>
{
Task.WaitAll(t1, t2);
tcs.TrySetResult(new CommandLineExecutionResult { ExitCode = process.ExitCode, StdErr = errorText, StdOut = stdOutText });
process.Dispose();
};
process.Start();
t1.Start();
t2.Start();
cancellationToken.Register(() =>
{
try
{
process.Kill();
}
catch (InvalidOperationException)
{
// swallow invalid operations, which indicate that there is no process associated with
// the process object, and therefore nothing to kill
// https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.kill?view=net-8.0#system-diagnostics-process-kill
return;
}
});
return tcs.Task;
}
}