-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathRunScriptCommand.cs
More file actions
227 lines (177 loc) · 6.68 KB
/
RunScriptCommand.cs
File metadata and controls
227 lines (177 loc) · 6.68 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
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
namespace RunScript;
using System.CommandLine.Invocation;
using DotNet.Globbing;
using RunScript.Logging;
internal class RunScriptCommand : RootCommand, ICommandHandler
{
private readonly IEnvironment _environment;
private readonly IFormatProvider _consoleFormatProvider;
private string _workingDirectory;
internal RunScriptCommand(
IEnvironment environment,
IFormatProvider consoleFormatProvider,
string workingDirectory)
: base("Run arbitrary project scripts")
{
_environment = environment ?? throw new ArgumentNullException(nameof(environment));
_consoleFormatProvider = consoleFormatProvider ?? throw new ArgumentNullException(nameof(consoleFormatProvider));
if (string.IsNullOrEmpty(workingDirectory)) throw new ArgumentException($"'{nameof(workingDirectory)}' cannot be null or empty.", nameof(workingDirectory));
_workingDirectory = workingDirectory;
AddArgument(GlobalArguments.Scripts);
AddOption(GlobalOptions.IfPresent);
AddOption(GlobalOptions.ScriptShell);
AddOption(GlobalOptions.Verbose);
Handler = this;
}
public int Invoke(InvocationContext context)
=> throw new NotImplementedException();
public async Task<int> InvokeAsync(InvocationContext context)
{
if (context is null) throw new ArgumentNullException(nameof(context));
var ifPresent = context.ParseResult.GetValueForOption(GlobalOptions.IfPresent);
var scriptShell = context.ParseResult.GetValueForOption(GlobalOptions.ScriptShell);
var verbose = context.ParseResult.GetValueForOption(GlobalOptions.Verbose);
var scripts = context.ParseResult.GetValueForArgument(GlobalArguments.Scripts);
IConsoleWriter writer = new ConsoleWriter(context.Console, _consoleFormatProvider, verbose);
writer.VerboseBanner();
Project? project;
try
{
_environment.SetEnvironmentVariable("INIT_CWD", _workingDirectory);
(project, _workingDirectory) = await new ProjectLoader().LoadAsync(_workingDirectory);
}
catch (Exception ex)
{
writer.Error(ex.Message);
return 1;
}
var builder = new CommandBuilder(
writer,
_environment,
project,
_workingDirectory,
// For now we just write to the executing shell, later we can opt to write to the log instead
captureOutput: false);
builder.SetUpEnvironment(scriptShell);
if (scripts.Length == 0)
{
GlobalCommands.PrintAvailableScripts(writer, project.Scripts!);
return 0;
}
var scriptsToRun = FindScripts(project.Scripts!, scripts);
// When `--if-present` isn't specified and a script wasn't found in the config then we show an error and stop
if (scriptsToRun.Any(s => !s.Exists) && !ifPresent)
{
writer.Error(
"Script not found: {0}",
string.Join(
", ",
scriptsToRun
.Where(script => !script.Exists)
.Select(script => script.Name)));
return 1;
}
var runResults = new List<RunResult>();
foreach (var script in scriptsToRun)
{
using (var logGroup = writer.Group(_environment, script.Name))
{
if (!script.Exists)
{
writer.Banner($"Skipping script {script.Name}");
continue;
}
// UnparsedTokens is backed by string[] so if we cast
// back to that we get a lot better perf down the line.
// Hopefully this doesn't break in the future 🤞
var scriptArgs = (string[])context.ParseResult.UnparsedTokens;
var scriptRunner = builder.CreateGroupRunner(context.GetCancellationToken());
var result = await scriptRunner.RunAsync(
script.Name,
scriptArgs);
runResults.Add(new(script.Name, result));
if (result != 0)
{
break;
}
}
}
return RunResults(writer, runResults);
}
internal static List<ScriptResult> FindScripts(
ScriptCollection projectScripts,
string[] scripts)
{
var results = new List<ScriptResult>();
foreach (var script in scripts)
{
// The `env` script is special so if it's not explicitly declared we act like it was
if (projectScripts.Contains(script) || script == "env")
{
results.Add(new(script, true));
continue;
}
var hadMatch = false;
var matcher = Glob.Parse(
SwapColonAndSlash(script),
new GlobOptions
{
Evaluation =
{
CaseInsensitive = true,
}
});
foreach (var (projectScript, _) in projectScripts)
{
if (matcher.IsMatch(SwapColonAndSlash(projectScript).AsSpan()))
{
hadMatch = true;
results.Add(new(projectScript, true));
}
}
if (!hadMatch)
{
results.Add(new(script, false));
}
}
return results;
}
internal static int RunResults(IConsoleWriter writer, List<RunResult> results)
{
// If only 1 script ran we don't need a report of the results
if (results.Count == 1)
{
return results[0].ExitCode;
}
var hadError = false;
foreach (var result in results.Where(r => r.ExitCode != 0))
{
hadError = true;
writer.Line(
"ERROR: \"{0}\" exited with {1}",
writer.ColorText(ConsoleColor.Blue, result.Name),
writer.ColorText(ConsoleColor.Green, result.ExitCode));
}
return hadError ? 1 : 0;
}
internal static string SwapColonAndSlash(string scriptName)
{
var result = new char[scriptName.Length];
for (var i = 0; i < scriptName.Length; i++)
{
if (scriptName[i] == ':')
{
result[i] = '/';
}
else if (scriptName[i] == '/')
{
result[i] = ':';
}
else
{
result[i] = scriptName[i];
}
}
return new string(result);
}
}