forked from cake-build/cake
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tool.cs
387 lines (345 loc) · 14.3 KB
/
Tool.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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using Cake.Core.IO;
namespace Cake.Core.Tooling
{
/// <summary>
/// Base class for tools.
/// </summary>
/// <typeparam name="TSettings">The settings type.</typeparam>
public abstract class Tool<TSettings> where TSettings : ToolSettings
{
private readonly ICakeEnvironment _environment;
private readonly IFileSystem _fileSystem;
private readonly IGlobber _globber;
private readonly IToolLocator _tools;
private readonly IProcessRunner _processRunner;
/// <summary>
/// Initializes a new instance of the <see cref="Tool{TSettings}" /> class.
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="environment">The environment.</param>
/// <param name="processRunner">The process runner.</param>
/// <param name="globber">The globber.</param>
[Obsolete("Please use Tool(IFileSystem, ICakeEnvironment, IProcessRunner, IToolLocator) instead.")]
protected Tool(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IGlobber globber)
: this(fileSystem, environment, processRunner, (IToolLocator)null)
{
if (globber == null)
{
throw new ArgumentNullException(nameof(globber));
}
_globber = globber;
}
/// <summary>
/// Initializes a new instance of the <see cref="Tool{TSettings}"/> class.
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="environment">The environment.</param>
/// <param name="processRunner">The process runner.</param>
/// <param name="tools">The tool locator.</param>
protected Tool(IFileSystem fileSystem, ICakeEnvironment environment, IProcessRunner processRunner, IToolLocator tools)
{
if (fileSystem == null)
{
throw new ArgumentNullException(nameof(fileSystem));
}
if (environment == null)
{
throw new ArgumentNullException(nameof(environment));
}
if (processRunner == null)
{
throw new ArgumentNullException(nameof(processRunner));
}
_fileSystem = fileSystem;
_environment = environment;
_processRunner = processRunner;
_tools = tools;
}
/// <summary>
/// Runs the tool using the specified settings.
/// </summary>
/// <param name="settings">The settings.</param>
/// <param name="arguments">The arguments.</param>
protected void Run(TSettings settings, ProcessArgumentBuilder arguments)
{
Run(settings, arguments, null, null);
}
/// <summary>
/// Runs the tool using a custom tool path and the specified settings.
/// </summary>
/// <param name="settings">The settings.</param>
/// <param name="arguments">The arguments.</param>
/// <param name="processSettings">The process settings</param>
/// <param name="postAction">If specified called after process exit</param>
protected void Run(
TSettings settings,
ProcessArgumentBuilder arguments,
ProcessSettings processSettings,
Action<IProcess> postAction)
{
if (arguments == null && (processSettings?.Arguments == null))
{
throw new ArgumentNullException(nameof(arguments));
}
var process = RunProcess(settings, arguments, processSettings);
// Wait for the process to exit.
if (settings.ToolTimeout.HasValue)
{
if (!process.WaitForExit((int)settings.ToolTimeout.Value.TotalMilliseconds))
{
const string message = "Tool timeout ({0}): {1}";
throw new TimeoutException(string.Format(CultureInfo.InvariantCulture, message, settings.ToolTimeout.Value, GetToolName()));
}
}
else
{
process.WaitForExit();
}
try
{
ProcessExitCode(process.GetExitCode());
}
finally
{
// Post action specified?
postAction?.Invoke(process);
}
}
/// <summary>
/// Customized exit code handling.
/// Standard behavior is to fail when non zero.
/// </summary>
/// <param name="exitCode">The process exit code</param>
protected virtual void ProcessExitCode(int exitCode)
{
// Did an error occur?
if (exitCode != 0)
{
const string message = "{0}: Process returned an error (exit code {1}).";
throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, GetToolName(), exitCode));
}
}
/// <summary>
/// Runs the tool using a custom tool path and the specified settings.
/// </summary>
/// <param name="settings">The settings.</param>
/// <param name="arguments">The arguments.</param>
/// <returns>The process that the tool is running under.</returns>
protected IProcess RunProcess(TSettings settings, ProcessArgumentBuilder arguments)
{
return RunProcess(settings, arguments, null);
}
/// <summary>
/// Runs the tool using a custom tool path and the specified settings.
/// </summary>
/// <param name="settings">The settings.</param>
/// <param name="arguments">The arguments.</param>
/// <param name="processSettings">The process settings</param>
/// <returns>The process that the tool is running under.</returns>
protected IProcess RunProcess(
TSettings settings,
ProcessArgumentBuilder arguments,
ProcessSettings processSettings)
{
if (arguments == null && (processSettings?.Arguments == null))
{
throw new ArgumentNullException(nameof(arguments));
}
// Should we customize the arguments?
if (settings.ArgumentCustomization != null)
{
arguments = settings.ArgumentCustomization(arguments);
}
// Get the tool name.
var toolName = GetToolName();
// Get the tool path.
var toolPath = GetToolPath(settings);
if (toolPath == null || !_fileSystem.Exist(toolPath))
{
const string message = "{0}: Could not locate executable.";
throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
}
// Get the working directory.
var workingDirectory = GetWorkingDirectory(settings);
if (workingDirectory == null)
{
const string message = "{0}: Could not resolve working directory.";
throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
}
// Create the process start info.
var info = processSettings ?? new ProcessSettings();
if (info.Arguments == null)
{
info.Arguments = arguments;
}
if (info.WorkingDirectory == null)
{
info.WorkingDirectory = workingDirectory.MakeAbsolute(_environment).FullPath;
}
if (info.EnvironmentVariables == null)
{
info.EnvironmentVariables = GetEnvironmentVariables(settings);
}
// Want to opt out of using a working directory?
info.NoWorkingDirectory = settings.NoWorkingDirectory;
// Run the process.
var process = _processRunner.Start(toolPath, info);
if (process == null)
{
const string message = "{0}: Process was not started.";
throw new CakeException(string.Format(CultureInfo.InvariantCulture, message, toolName));
}
return process;
}
/// <summary>
/// Gets the name of the tool.
/// </summary>
/// <returns>The name of the tool.</returns>
protected abstract string GetToolName();
/// <summary>
/// Gets the possible names of the tool executable.
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns>The name of the tool.</returns>
protected virtual IEnumerable<string> GetToolExecutableNames(TSettings settings) => GetToolExecutableNames();
/// <summary>
/// Gets the possible names of the tool executable.
/// </summary>
/// <returns>The tool executable name.</returns>
protected abstract IEnumerable<string> GetToolExecutableNames();
/// <summary>
/// Gets the working directory.
/// Defaults to the currently set working directory.
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns>The working directory for the tool.</returns>
protected virtual DirectoryPath GetWorkingDirectory(TSettings settings)
{
if (settings.WorkingDirectory != null)
{
return settings.WorkingDirectory;
}
return _environment.WorkingDirectory;
}
/// <summary>
/// Gets alternative file paths which the tool may exist in
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns>The default tool path.</returns>
protected virtual IEnumerable<FilePath> GetAlternativeToolPaths(TSettings settings)
{
return Enumerable.Empty<FilePath>();
}
/// <summary>
/// Gets the environment variables.
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns>The environment variables for the tool.</returns>
protected virtual IDictionary<string, string> GetEnvironmentVariables(TSettings settings)
{
return settings.EnvironmentVariables;
}
/// <summary>
/// Gets the resolved tool path.
/// </summary>
/// <param name="settings">The settings.</param>
/// <returns>The resolved tool path.</returns>
protected FilePath GetToolPath(TSettings settings)
{
if (_tools != null)
{
return GetToolPathUsingToolService(settings);
}
return GetToolPathObsolete(settings);
}
private FilePath GetToolPathUsingToolService(TSettings settings)
{
var toolPath = settings.ToolPath;
if (toolPath != null)
{
return toolPath.MakeAbsolute(_environment);
}
// Look for each possible executable name in various places.
var toolExeNames = GetToolExecutableNames(settings);
foreach (var toolExeName in toolExeNames)
{
var result = _tools.Resolve(toolExeName);
if (result != null)
{
return result;
}
}
// Look through all the alternative directories for the tool.
var alternativePaths = GetAlternativeToolPaths(settings) ?? Enumerable.Empty<FilePath>();
foreach (var alternativePath in alternativePaths)
{
if (_fileSystem.Exist(alternativePath))
{
return alternativePath.MakeAbsolute(_environment);
}
}
return null;
}
[SuppressMessage("ReSharper", "ConvertIfStatementToConditionalTernaryExpression")]
private FilePath GetToolPathObsolete(TSettings settings)
{
var toolPath = settings.ToolPath;
if (toolPath != null)
{
return toolPath.MakeAbsolute(_environment);
}
var toolExeNames = GetToolExecutableNames(settings);
string[] pathDirs = null;
// Look for each possible executable name in various places.
foreach (var toolExeName in toolExeNames)
{
// First look in ./tools/
toolPath = _globber.GetFiles("./tools/**/" + toolExeName).FirstOrDefault();
if (toolPath != null)
{
return toolPath.MakeAbsolute(_environment);
}
// Cache the PATH directory list if we didn't already.
if (pathDirs == null)
{
var pathEnv = _environment.GetEnvironmentVariable("PATH");
if (!string.IsNullOrEmpty(pathEnv))
{
pathDirs = pathEnv.Split(new[] { _environment.Platform.IsUnix() ? ':' : ';' }, StringSplitOptions.RemoveEmptyEntries);
}
else
{
pathDirs = new string[] { };
}
}
// Look in every PATH directory for the file.
foreach (var pathDir in pathDirs)
{
var file = new DirectoryPath(pathDir).CombineWithFilePath(toolExeName);
if (_fileSystem.Exist(file))
{
return file.MakeAbsolute(_environment);
}
}
}
// Look through all the alternative directories for the tool.
var alternativePaths = GetAlternativeToolPaths(settings) ?? Enumerable.Empty<FilePath>();
foreach (var altPath in alternativePaths)
{
if (_fileSystem.Exist(altPath))
{
return altPath.MakeAbsolute(_environment);
}
}
return null;
}
}
}