summaryrefslogtreecommitdiffhomepage
path: root/packages/tool-shell/src/spawn.ts
blob: 9025c26e2cfa49766e31c883c437395e7b32efc0 (plain)
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
import { spawn as nodeSpawn } from "node:child_process";
import type { SpawnResult, SpawnShell } from "./shell.js";

export const realSpawn: SpawnShell = (params): Promise<SpawnResult> => {
	return new Promise<SpawnResult>((resolve) => {
		const child = nodeSpawn("sh", ["-c", params.command], {
			cwd: params.cwd,
			stdio: ["ignore", "pipe", "pipe"],
		});

		let timedOut = false;
		let killed = false;
		const timer = setTimeout(() => {
			timedOut = true;
			child.kill("SIGKILL");
		}, params.timeout);

		const onAbort = () => {
			killed = true;
			child.kill("SIGKILL");
		};
		params.signal.addEventListener("abort", onAbort, { once: true });

		child.stdout.on("data", (chunk: Buffer) => {
			params.onOutput(chunk.toString(), "stdout");
		});

		child.stderr.on("data", (chunk: Buffer) => {
			params.onOutput(chunk.toString(), "stderr");
		});

		child.on("close", (code) => {
			clearTimeout(timer);
			params.signal.removeEventListener("abort", onAbort);
			resolve({ exitCode: code, timedOut });
		});

		child.on("error", () => {
			clearTimeout(timer);
			params.signal.removeEventListener("abort", onAbort);
			if (!killed && !timedOut) {
				resolve({ exitCode: 1, timedOut: false });
			}
		});
	});
};