This repository has been archived by the owner on Nov 6, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
ScriptRunner.cs
204 lines (174 loc) · 7.67 KB
/
ScriptRunner.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
// Copyright (c) .NET Foundation Contributors. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Original Source: https://github.com/aspnet/JavaScriptServices
using Microsoft.Extensions.Logging;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Text;
namespace VueCliMiddleware
{
/// <summary>
/// Executes the <c>script</c> entries defined in a <c>package.json</c> file,
/// capturing any output written to stdio.
/// </summary>
internal class ScriptRunner
{
public EventedStreamReader StdOut { get; }
public EventedStreamReader StdErr { get; }
public Process RunnerProcess { get; }
public ScriptRunnerType Runner { get; }
private string GetExeName()
{
switch (Runner)
{
case ScriptRunnerType.Npm:
return "npm";
case ScriptRunnerType.Yarn:
return "yarn";
case ScriptRunnerType.Npx:
return "npx";
case ScriptRunnerType.Pnpm:
return "pnpm";
default:
return "npm";
}
}
private static string BuildCommand(ScriptRunnerType runner, string scriptName, string arguments)
{
var command = new StringBuilder();
if (runner == ScriptRunnerType.Npm) { command.Append("run "); }
command.Append(scriptName);
command.Append(' ');
if (runner == ScriptRunnerType.Npm) { command.Append("-- "); }
if (!string.IsNullOrWhiteSpace(arguments)) { command.Append(arguments); }
return command.ToString();
}
private static Regex AnsiColorRegex = new Regex("\x001b\\[[0-9;]*m", RegexOptions.None, TimeSpan.FromSeconds(1));
public void Kill()
{
try { RunnerProcess?.Kill(); } catch { }
try { RunnerProcess?.WaitForExit(); } catch { }
}
public ScriptRunner(string workingDirectory, string scriptName, string arguments, IDictionary<string, string> envVars, ScriptRunnerType runner, bool wsl)
{
if (string.IsNullOrEmpty(workingDirectory))
{
throw new ArgumentException("Cannot be null or empty.", nameof(workingDirectory));
}
if (string.IsNullOrEmpty(scriptName))
{
throw new ArgumentException("Cannot be null or empty.", nameof(scriptName));
}
Runner = runner;
var exeName = GetExeName();
var completeArguments = BuildCommand(runner, scriptName, arguments);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
if (wsl)
{
completeArguments = $"{exeName} {completeArguments}";
exeName = "wsl";
}
else
{
// On Windows, the NPM executable is a .cmd file, so it can't be executed
// directly (except with UseShellExecute=true, but that's no good, because
// it prevents capturing stdio). So we need to invoke it via "cmd /c".
completeArguments = $"/c {exeName} {completeArguments}";
exeName = "cmd";
}
}
var processStartInfo = new ProcessStartInfo(exeName)
{
Arguments = completeArguments,
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
WorkingDirectory = workingDirectory
};
if (envVars != null)
{
foreach (var keyValuePair in envVars)
{
processStartInfo.Environment[keyValuePair.Key] = keyValuePair.Value;
}
}
RunnerProcess = LaunchNodeProcess(processStartInfo);
StdOut = new EventedStreamReader(RunnerProcess.StandardOutput);
StdErr = new EventedStreamReader(RunnerProcess.StandardError);
}
public void AttachToLogger(ILogger logger)
{
// When the NPM task emits complete lines, pass them through to the real logger
StdOut.OnReceivedLine += line =>
{
if (!string.IsNullOrWhiteSpace(line))
{
// NPM tasks commonly emit ANSI colors, but it wouldn't make sense to forward
// those to loggers (because a logger isn't necessarily any kind of terminal)
//logger.LogInformation(StripAnsiColors(line).TrimEnd('\n'));
// making this console for debug purpose
if (line.StartsWith("<s>"))
{
Console.Error.WriteLine(line.Substring(3));
}
else
{
Console.Error.WriteLine(line);
}
}
};
StdErr.OnReceivedLine += line =>
{
if (!string.IsNullOrWhiteSpace(line))
{
//logger.LogError(StripAnsiColors(line).TrimEnd('\n'));
// making this console for debug purpose
if (line.StartsWith("<s>"))
{
Console.Error.WriteLine(line.Substring(3));
}
else
{
Console.Error.WriteLine(line);
}
}
};
// But when it emits incomplete lines, assume this is progress information and
// hence just pass it through to StdOut regardless of logger config.
StdErr.OnReceivedChunk += chunk =>
{
var containsNewline = Array.IndexOf(chunk.Array, '\n', chunk.Offset, chunk.Count) >= 0;
if (!containsNewline)
{
Console.Write(chunk.Array, chunk.Offset, chunk.Count);
}
};
}
private static string StripAnsiColors(string line)
=> AnsiColorRegex.Replace(line, string.Empty);
private static Process LaunchNodeProcess(ProcessStartInfo startInfo)
{
try
{
var process = Process.Start(startInfo);
// See equivalent comment in OutOfProcessNodeInstance.cs for why
process.EnableRaisingEvents = true;
return process;
}
catch (Exception ex)
{
var message = $"Failed to start '{startInfo.FileName}'. To resolve this:.\n\n"
+ $"[1] Ensure that '{startInfo.FileName}' is installed and can be found in one of the PATH directories.\n"
+ $" Current PATH enviroment variable is: { Environment.GetEnvironmentVariable("PATH") }\n"
+ " Make sure the executable is in one of those directories, or update your PATH.\n\n"
+ "[2] See the InnerException for further details of the cause.";
throw new InvalidOperationException(message, ex);
}
}
}
}