-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathspawn.ts
More file actions
223 lines (195 loc) · 5.27 KB
/
spawn.ts
File metadata and controls
223 lines (195 loc) · 5.27 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
import * as childProcess from "node:child_process";
import os from "node:os";
import type { CancellationToken, LogOutputChannel } from "vscode";
/**
* Array of well-known log types.
*/
const knownLogTypes = [
"TRACE",
"DEBUG",
"INFO",
"WARN",
"WARNING",
"ERROR",
"FATAL",
"CRITICAL",
] as const;
/**
* Type representing a well-known log type.
*/
type LogType = (typeof knownLogTypes)[number];
/**
* Removes the timestamp and log type from a log line, and returns the cleaned log and the log type (if recognized).
*
* @param line The raw log line string.
* @returns An object containing the cleaned log message and the extracted log type (or undefined if not recognized).
*/
function parseLine(line: string): {
line: string;
logType: LogType | undefined;
} {
const regex =
/^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?)[ ]+([A-Z]+)[ ]+(.*)$/;
const match = line.match(regex);
if (match) {
const [, , logTypeRaw, rest] = match;
const logType = (knownLogTypes as readonly string[]).includes(logTypeRaw)
? (logTypeRaw as LogType)
: undefined;
return {
line: rest.trim(),
logType,
};
}
return {
line,
logType: undefined,
};
}
/**
* Represents {@link LogOutputChannel} methods.
*/
type LogOutputChannelMethods = "trace" | "debug" | "info" | "warn" | "error";
/**
* Maps log types to {@link LogOutputChannelMethods} methods.
*/
const logTypeToOutputChannelMethod: Record<LogType, LogOutputChannelMethods> = {
CRITICAL: "error",
DEBUG: "debug",
ERROR: "error",
FATAL: "error",
INFO: "info",
TRACE: "trace",
WARN: "warn",
WARNING: "warn",
};
export function pipeToLogOutputChannel(
child: childProcess.ChildProcess,
outputChannel: LogOutputChannel,
outputLabel: string,
) {
const writeToOutputChannel = (
data: Buffer,
defaultMethod: LogOutputChannelMethods,
) => {
const output = data
.toString()
.split("\n")
.map((line) => line.trim())
.filter((line) => line !== "")
.map((line) => parseLine(line));
for (const { line, logType } of output) {
const method = logType
? logTypeToOutputChannelMethod[logType]
: defaultMethod;
outputChannel[method](`${outputLabel}${line.trim()}`);
}
};
child.stdout?.on("data", (data: Buffer) =>
writeToOutputChannel(data, "info"),
);
child.stderr?.on("data", (data: Buffer) =>
writeToOutputChannel(data, "error"),
);
child.on("close", (code) => {
if (code === 0) {
outputChannel.info(`${outputLabel}Process ended (exit code = ${code})`);
} else {
outputChannel.error(`${outputLabel}Process ended (exit code = ${code})`);
}
});
}
/**
* Represents an error for a spawned child that exited with an error.
*/
export class SpawnError extends Error {
readonly command: string;
readonly code: number | null;
readonly signal: NodeJS.Signals | null;
constructor(options: {
command: string;
code: number | null;
signal: NodeJS.Signals | null;
}) {
super(`Command [${options.command}] failed with code [${options.code}]`);
this.command = options.command;
this.code = options.code;
this.signal = options.signal;
}
}
export interface SpawnOptions {
outputLabel?: string;
outputChannel: LogOutputChannel;
cancellationToken?: CancellationToken;
environment?: Record<string, string | undefined> | undefined;
onStderr?: (data: Buffer, context: { abort: () => void }) => void;
}
/**
* Spawns a new process using the given `command`, with command-line arguments in `args`.
* - All output is appended to the `options.outputChannel`, optionally prefixed by `options.outputLabel`.
* - The process can be cancelled using the `options.cancellationToken`.
*
* @throws if the process returns with `code !== 0` — See {@link SpawnError}.
*/
export const spawn = (
command: string,
args: string[],
options: SpawnOptions,
) => {
return new Promise<{ code: number | null; signal: NodeJS.Signals | null }>(
(resolve, reject) => {
const { outputChannel } = options;
const outputLabel = options.outputLabel
? `[${options.outputLabel}]: `
: "";
const commandLine = [command, ...args].join(" ");
outputChannel.info(`${outputLabel}$ ${commandLine}`);
const spawnOptions: childProcess.SpawnOptions = {
shell: true,
stdio: ["pipe", "pipe", "pipe"],
env: options.environment,
};
const child = childProcess.spawn(command, args, spawnOptions);
const killChild = () => {
// Use SIGINT on Unix, 'SIGTERM' on Windows
const isWindows = os.platform() === "win32";
if (isWindows) {
child.kill("SIGTERM");
} else {
child.kill("SIGINT");
}
};
const disposeCancel = options.cancellationToken?.onCancellationRequested(
() => {
outputChannel.appendLine(
`${outputLabel}Command cancelled: ${commandLine}`,
);
killChild();
reject(new Error("Command cancelled"));
},
);
pipeToLogOutputChannel(child, outputChannel, outputLabel);
if (options.onStderr) {
child.stderr?.on("data", (data: Buffer) =>
options.onStderr?.(data, {
abort() {
killChild();
},
}),
);
}
child.on("close", (code, signal) => {
disposeCancel?.dispose();
if (code === 0) {
resolve({ code, signal });
} else {
const error = new SpawnError({ command, code, signal });
reject(error);
}
});
child.on("error", (error) => {
reject(error);
});
},
);
};