/
child_process.ts
485 lines (431 loc) · 12.1 KB
/
child_process.ts
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.
// This module implements 'child_process' module of Node.JS API.
// ref: https://nodejs.org/api/child_process.html
import { assert } from "../_util/assert.ts";
import { EventEmitter } from "./events.ts";
import { notImplemented } from "./_utils.ts";
import { Readable, Stream, Writable } from "./stream.ts";
import { deferred } from "../async/deferred.ts";
import { iterateReader, writeAll } from "../streams/conversion.ts";
import { isWindows } from "../_util/os.ts";
import { Buffer } from "./buffer.ts";
export class ChildProcess extends EventEmitter {
/**
* The exit code of the child process. This property will be `null` until the child process exits.
*/
exitCode: number | null = null;
/**
* This property is set to `true` after `kill()` is called.
*/
killed = false;
/**
* The PID of this child process.
*/
pid!: number;
/**
* Command line arguments given to this child process.
*/
spawnargs: string[];
/**
* The executable file name of this child process.
*/
spawnfile: string;
/**
* This property represents the child process's stdin.
*/
stdin: Writable | null = null;
/**
* This property represents the child process's stdout.
*/
stdout: Readable | null = null;
/**
* This property represents the child process's stderr.
*/
stderr: Readable | null = null;
/**
* Pipes to this child process.
*/
stdio: [Writable | null, Readable | null, Readable | null] = [
null,
null,
null,
];
#process!: Deno.Process;
#spawned = deferred<void>();
constructor(
command: string,
args?: string[],
options?: ChildProcessOptions,
) {
super();
const {
env = {},
stdio = ["pipe", "pipe", "pipe"],
shell = false,
} = options || {};
const [
stdin = "pipe",
stdout = "pipe",
stderr = "pipe",
] = normalizeStdioOption(stdio);
const cmd = buildCommand(
command,
args || [],
shell,
);
this.spawnfile = cmd[0];
this.spawnargs = cmd;
try {
this.#process = Deno.run({
cmd,
env,
stdin: toDenoStdio(stdin as NodeStdio | number),
stdout: toDenoStdio(stdout as NodeStdio | number),
stderr: toDenoStdio(stderr as NodeStdio | number),
});
this.pid = this.#process.pid;
if (stdin === "pipe") {
assert(this.#process.stdin);
this.stdin = createWritableFromStdin(this.#process.stdin);
}
if (stdout === "pipe") {
assert(this.#process.stdout);
this.stdout = createReadableFromReader(this.#process.stdout);
}
if (stderr === "pipe") {
assert(this.#process.stderr);
this.stderr = createReadableFromReader(this.#process.stderr);
}
this.stdio[0] = this.stdin;
this.stdio[1] = this.stdout;
this.stdio[2] = this.stderr;
queueMicrotask(() => {
this.emit("spawn");
this.#spawned.resolve();
});
(async () => {
const status = await this.#process.status();
this.exitCode = status.code;
this.#spawned.then(async () => {
// The 'exit' and 'close' events must be emitted after the 'spawn' event.
this.emit("exit", this.exitCode, status.signal ?? null);
await this._waitForChildStreamsToClose();
this.kill();
this.emit("close", this.exitCode, status.signal ?? null);
});
})();
} catch (err) {
this._handleError(err);
}
}
/**
* @param signal NOTE: this parameter is not yet implemented.
*/
kill(signal?: number): boolean {
if (signal != null) {
notImplemented("`ChildProcess.kill()` with the `signal` parameter");
}
if (this.killed) {
return this.killed;
}
if (this.#process.stdin) {
assert(this.stdin);
ensureClosed(this.#process.stdin);
}
if (this.#process.stdout) {
ensureClosed(this.#process.stdout);
}
if (this.#process.stderr) {
ensureClosed(this.#process.stderr);
}
ensureClosed(this.#process); // TODO Use `Deno.Process.kill` instead when it becomes stable.
this.killed = true;
return this.killed;
}
ref(): void {
notImplemented("ChildProcess.ref()");
}
unref(): void {
notImplemented("ChildProcess.unref()");
}
private async _waitForChildStreamsToClose(): Promise<void> {
const promises = [] as Array<Promise<void>>;
if (this.stdin && !this.stdin.destroyed) {
assert(this.stdin);
this.stdin.destroy();
promises.push(waitForStreamToClose(this.stdin));
}
if (this.stdout && !this.stdout.destroyed) {
promises.push(waitForReadableToClose(this.stdout));
}
if (this.stderr && !this.stderr.destroyed) {
promises.push(waitForReadableToClose(this.stderr));
}
await Promise.all(promises);
}
private _handleError(err: unknown): void {
queueMicrotask(() => {
this.emit("error", err); // TODO(uki00a) Convert `err` into nodejs's `SystemError` class.
});
}
}
const supportedNodeStdioTypes: NodeStdio[] = ["pipe", "ignore", "inherit"];
function toDenoStdio(
pipe: NodeStdio | number | Stream | null | undefined,
): DenoStdio {
if (
!supportedNodeStdioTypes.includes(pipe as NodeStdio) ||
typeof pipe === "number" || pipe instanceof Stream
) {
notImplemented();
}
switch (pipe) {
case "pipe":
case undefined:
case null:
return "piped";
case "ignore":
return "null";
case "inherit":
return "inherit";
default:
notImplemented();
}
}
type NodeStdio = "pipe" | "overlapped" | "ignore" | "inherit";
type DenoStdio = "inherit" | "piped" | "null";
interface ChildProcessOptions {
/**
* Current working directory of the child process.
*/
cwd?: string;
/**
* Environment variables passed to the child process.
*/
env?: Record<string, string>;
/**
* This option defines child process's stdio configuration.
* @see https://nodejs.org/api/child_process.html#child_process_options_stdio
*/
stdio?: Array<NodeStdio | number | Stream | null | undefined> | NodeStdio;
/**
* NOTE: This option is not yet implemented.
*/
detached?: boolean;
/**
* NOTE: This option is not yet implemented.
*/
uid?: number;
/**
* NOTE: This option is not yet implemented.
*/
gid?: number;
/**
* NOTE: This option is not yet implemented.
*/
argv0?: string;
/**
* * If this option is `true`, run the command in the shell.
* * If this option is a string, run the command in the specified shell.
*/
shell?: string | boolean;
/**
* NOTE: This option is not yet implemented.
*/
signal?: AbortSignal;
/**
* NOTE: This option is not yet implemented.
*/
serialization?: "json" | "advanced";
/**
* NOTE: This option is not yet implemented.
*
* @see https://github.com/rust-lang/rust/issues/29494
* @see https://github.com/denoland/deno/issues/8852
*/
windowsVerbatimArguments?: boolean;
/**
* NOTE: This option is not yet implemented.
*/
windowsHide?: boolean;
}
// deno-lint-ignore no-empty-interface
interface SpawnOptions extends ChildProcessOptions {}
export function spawn(command: string): ChildProcess;
export function spawn(command: string, options: SpawnOptions): ChildProcess;
export function spawn(command: string, args: string[]): ChildProcess;
export function spawn(
command: string,
args: string[],
options: SpawnOptions,
): ChildProcess;
/**
* Spawns a child process using `command`.
*/
export function spawn(
command: string,
argsOrOptions?: string[] | SpawnOptions,
maybeOptions?: SpawnOptions,
): ChildProcess {
const args = Array.isArray(argsOrOptions) ? argsOrOptions : [];
const options = !Array.isArray(argsOrOptions) && argsOrOptions != null
? argsOrOptions
: maybeOptions;
return new ChildProcess(command, args, options);
}
export default { spawn };
function ensureClosed(closer: Deno.Closer): void {
try {
closer.close();
} catch (err) {
if (isAlreadyClosed(err)) {
return;
}
throw err;
}
}
function isAlreadyClosed(err: unknown): boolean {
return err instanceof Deno.errors.BadResource ||
err instanceof Deno.errors.Interrupted;
}
function createReadableFromReader(
reader: Deno.Reader,
): Readable {
// TODO(uki00a): This could probably be more efficient.
return Readable.from(cloneIterator(iterateReader(reader)), {
objectMode: false,
});
}
async function* cloneIterator(iterator: AsyncIterableIterator<Uint8Array>) {
try {
for await (const chunk of iterator) {
yield new Buffer(chunk);
}
} catch (e) {
if (isAlreadyClosed(e)) {
return;
}
throw e;
}
}
function createWritableFromStdin(stdin: Deno.Closer & Deno.Writer): Writable {
const encoder = new TextEncoder();
return new Writable({
async write(chunk, encoding, callback) {
try {
if (encoding !== "buffer") {
chunk = encoder.encode(chunk);
}
if (!(chunk instanceof Uint8Array)) {
throw new TypeError(
`Expected chunk to be of type Uint8Array, got ${typeof chunk}`,
);
}
await writeAll(stdin, chunk);
callback();
} catch (err) {
callback(err instanceof Error ? err : new Error("[non-error thrown]"));
}
},
final(callback) {
try {
ensureClosed(stdin);
} catch (err) {
callback(err instanceof Error ? err : new Error("[non-error thrown]"));
}
},
});
}
function normalizeStdioOption(
stdio: Array<NodeStdio | number | null | undefined | Stream> | NodeStdio = [
"pipe",
"pipe",
"pipe",
],
) {
if (Array.isArray(stdio)) {
if (stdio.length > 3) {
notImplemented();
} else {
return stdio;
}
} else {
switch (stdio) {
case "overlapped":
if (isWindows) {
notImplemented();
}
// 'overlapped' is same as 'piped' on non Windows system.
return ["pipe", "pipe", "pipe"];
case "pipe":
return ["pipe", "pipe", "pipe"];
case "inherit":
return ["inherit", "inherit", "inherit"];
case "ignore":
return ["ignore", "ignore", "ignore"];
default:
notImplemented();
}
}
}
function waitForReadableToClose(readable: Readable): Promise<void> {
readable.resume(); // Ensure buffered data will be consumed.
return waitForStreamToClose(readable);
}
function waitForStreamToClose(stream: Stream): Promise<void> {
const promise = deferred<void>();
const cleanup = () => {
stream.removeListener("close", onClose);
stream.removeListener("error", onError);
};
const onClose = () => {
cleanup();
promise.resolve();
};
const onError = (err: Error) => {
cleanup();
promise.reject(err);
};
stream.once("close", onClose);
stream.once("error", onError);
return promise;
}
/**
* This function is based on https://github.com/nodejs/node/blob/fc6426ccc4b4cb73076356fb6dbf46a28953af01/lib/child_process.js#L504-L528.
* Copyright Joyent, Inc. and other Node contributors. All rights reserved. MIT license.
*/
function buildCommand(
file: string,
args: string[],
shell: string | boolean,
): string[] {
const command = [file, ...args].join(" ");
if (shell) {
// Set the shell, switches, and commands.
if (isWindows) {
// TODO(uki00a): Currently, due to escaping issues, it is difficult to reproduce the same behavior as Node.js's `child_process` module.
// For more details, see the following issues:
// * https://github.com/rust-lang/rust/issues/29494
// * https://github.com/denoland/deno/issues/8852
if (typeof shell === "string") {
file = shell;
} else {
file = Deno.env.get("comspec") || "cmd.exe";
}
// '/d /s /c' is used only for cmd.exe.
if (/^(?:.*\\)?cmd(?:\.exe)?$/i.test(file)) {
args = ["/d", "/s", "/c", `"${command}"`];
} else {
args = ["-c", command];
}
} else {
if (typeof shell === "string") {
file = shell;
} else {
file = "/bin/sh";
}
args = ["-c", command];
}
}
return [file, ...args];
}