-
Notifications
You must be signed in to change notification settings - Fork 125
Expand file tree
/
Copy pathCommandLineInvocationService.cs
More file actions
194 lines (170 loc) · 7.25 KB
/
CommandLineInvocationService.cs
File metadata and controls
194 lines (170 loc) · 7.25 KB
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
#nullable disable
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/>
internal 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);
try
{
var result = await RunProcessAsync(pathToRun, joinedParameters, workingDirectory, cancellationToken);
record.Track(result, pathToRun, joinedParameters);
return result;
}
catch (Exception ex)
{
record.Track(ex, pathToRun, joinedParameters);
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 async Task<CommandLineExecutionResult> RunProcessAsync(
string fileName,
string parameters,
DirectoryInfo workingDirectory = null,
CancellationToken cancellationToken = default)
{
if (fileName.EndsWith(".cmd", StringComparison.OrdinalIgnoreCase) || fileName.EndsWith(".bat", StringComparison.OrdinalIgnoreCase))
{
// 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";
}
using var process = new Process
{
StartInfo =
{
FileName = fileName,
Arguments = parameters,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardError = true,
RedirectStandardOutput = true,
},
};
if (workingDirectory != null)
{
process.StartInfo.WorkingDirectory = workingDirectory.FullName;
}
process.Start();
// Read both streams concurrently to avoid deadlocks if either fills its buffer.
var stdOutTask = process.StandardOutput.ReadToEndAsync(cancellationToken);
var stdErrTask = process.StandardError.ReadToEndAsync(cancellationToken);
try
{
await process.WaitForExitAsync(cancellationToken);
}
catch (OperationCanceledException)
{
try
{
process.Kill(entireProcessTree: true);
}
catch (InvalidOperationException)
{
// Process already exited.
}
throw;
}
var stdOut = await stdOutTask;
var stdErr = await stdErrTask;
return new CommandLineExecutionResult
{
ExitCode = process.ExitCode,
StdOut = stdOut,
StdErr = stdErr,
};
}
}