mirror of
https://github.com/smogon/sprites.git
synced 2026-12-05 07:00:37 -06:00
Parsers use charAt or check-and-throw; the executor gets a paired()
helper for its parallel arrays; matchSubsets returns {entry, matched}
pairs so the deploy loop stops indexing two arrays; spawn stdin and
pid get real guards.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
85 lines
2.6 KiB
TypeScript
85 lines
2.6 KiB
TypeScript
|
|
import {spawn} from 'node:child_process';
|
|
|
|
export type ExecResult = {
|
|
code: number | null,
|
|
signal: NodeJS.Signals | null,
|
|
output: string,
|
|
durationMs: number,
|
|
};
|
|
|
|
let livePids = new Set<number>();
|
|
|
|
// Emergency stop (e.g. second Ctrl-C): SIGKILL every live process group.
|
|
export function killAllProcessGroups(): void {
|
|
for (let pid of livePids) {
|
|
try {
|
|
process.kill(-pid, 'SIGKILL');
|
|
} catch {}
|
|
}
|
|
}
|
|
|
|
// The command script is fed to sh via stdin rather than -c: a single argv
|
|
// entry is capped by the kernel (MAX_ARG_STRLEN, ~128KB) and the largest %f
|
|
// expansion is already 80KB+.
|
|
export function runShell(command: string, opts: {cwd: string, signal: AbortSignal}): Promise<ExecResult> {
|
|
return new Promise((resolve, reject) => {
|
|
let start = performance.now();
|
|
// detached: own process group, so an abort kills grandchildren
|
|
// (magick, optipng, ...) with one signal
|
|
let child = spawn('sh', [], {cwd: opts.cwd, detached: true, stdio: ['pipe', 'pipe', 'pipe']});
|
|
if (child.pid !== undefined) {
|
|
livePids.add(child.pid);
|
|
}
|
|
let chunks: Buffer[] = [];
|
|
child.stdout.on('data', c => chunks.push(c));
|
|
child.stderr.on('data', c => chunks.push(c));
|
|
child.stdin.on('error', () => {}); // EPIPE if the shell exits early
|
|
child.stdin.end(command + '\n');
|
|
|
|
let killTimer: NodeJS.Timeout | undefined;
|
|
let kill = (sig: NodeJS.Signals) => {
|
|
if (child.pid === undefined) {
|
|
return;
|
|
}
|
|
try {
|
|
process.kill(-child.pid, sig);
|
|
} catch {}
|
|
};
|
|
let onAbort = () => {
|
|
kill('SIGTERM');
|
|
killTimer = setTimeout(() => kill('SIGKILL'), 5000);
|
|
killTimer.unref();
|
|
};
|
|
if (opts.signal.aborted) {
|
|
onAbort();
|
|
} else {
|
|
opts.signal.addEventListener('abort', onAbort, {once: true});
|
|
}
|
|
|
|
let cleanup = () => {
|
|
if (child.pid !== undefined) {
|
|
livePids.delete(child.pid);
|
|
}
|
|
opts.signal.removeEventListener('abort', onAbort);
|
|
if (killTimer !== undefined) {
|
|
clearTimeout(killTimer);
|
|
}
|
|
};
|
|
child.on('error', err => {
|
|
cleanup();
|
|
reject(err);
|
|
});
|
|
child.on('close', (code, signal) => {
|
|
cleanup();
|
|
resolve({
|
|
code,
|
|
signal,
|
|
output: Buffer.concat(chunks).toString(),
|
|
durationMs: performance.now() - start,
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|