forked from gajus/turbowatch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcreateSpawn.ts
165 lines (130 loc) · 3.93 KB
/
createSpawn.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
// cspell:words nothrow
import { AbortError, UnexpectedError } from './errors';
import { findNearestDirectory } from './findNearestDirectory';
import { killPsTree } from './killPsTree';
import { Logger } from './Logger';
import { type Throttle } from './types';
import chalk from 'chalk';
import randomColor from 'randomcolor';
import { throttle } from 'throttle-debounce';
import { $ } from 'zx';
const log = Logger.child({
namespace: 'createSpawn',
});
const prefixLines = (subject: string, prefix: string): string => {
const response: string[] = [];
for (const fragment of subject.split('\n')) {
response.push(prefix + fragment);
}
return response.join('\n');
};
export const createSpawn = (
taskId: string,
{
cwd = process.cwd(),
abortSignal,
throttleOutput,
}: {
abortSignal?: AbortSignal;
cwd?: string;
throttleOutput?: Throttle;
} = {},
) => {
let stdoutBuffer: string[] = [];
let stderrBuffer: string[] = [];
const flush = () => {
if (stdoutBuffer.length) {
// eslint-disable-next-line no-console
console.log(stdoutBuffer.join('\n'));
}
if (stderrBuffer.length) {
// eslint-disable-next-line no-console
console.error(stderrBuffer.join('\n'));
}
stdoutBuffer = [];
stderrBuffer = [];
};
const output = throttle(
throttleOutput?.delay,
() => {
flush();
},
{
noLeading: true,
},
);
const colorText = chalk.hex(randomColor({ luminosity: 'dark' }));
return async (pieces: TemplateStringsArray, ...args: any[]) => {
const binPath = (await findNearestDirectory('node_modules', cwd)) + '/.bin';
$.cwd = cwd;
$.prefix = `set -euo pipefail; export PATH="${binPath}:$PATH";`;
let onStdout: (chunk: Buffer) => void;
let onStderr: (chunk: Buffer) => void;
const formatChunk = (chunk: Buffer) => {
return prefixLines(chunk.toString().trimEnd(), colorText(taskId) + ' > ');
};
if (throttleOutput?.delay) {
onStdout = (chunk: Buffer) => {
stdoutBuffer.push(formatChunk(chunk));
output();
};
onStderr = (chunk: Buffer) => {
stderrBuffer.push(formatChunk(chunk));
output();
};
} else {
onStdout = (chunk: Buffer) => {
// eslint-disable-next-line no-console
console.log(formatChunk(chunk));
};
onStderr = (chunk: Buffer) => {
// eslint-disable-next-line no-console
console.error(formatChunk(chunk));
};
}
if (abortSignal?.aborted) {
throw new UnexpectedError(
'Attempted to spawn a process after the task was aborted.',
);
}
// eslint-disable-next-line promise/prefer-await-to-then
const processPromise = $(pieces, ...args)
.nothrow()
.quiet();
processPromise.stdout.on('data', onStdout);
processPromise.stderr.on('data', onStderr);
if (abortSignal) {
const kill = () => {
const pid = processPromise.child?.pid;
if (!pid) {
log.warn('no process to kill');
return;
}
// TODO make this configurable
// eslint-disable-next-line promise/prefer-await-to-then
killPsTree(pid, 5_000).then(() => {
log.debug('task %s was killed', taskId);
processPromise.stdout.off('data', onStdout);
processPromise.stderr.off('data', onStderr);
});
};
abortSignal.addEventListener('abort', kill, {
once: true,
});
// eslint-disable-next-line promise/prefer-await-to-then
processPromise.finally(() => {
abortSignal.removeEventListener('abort', kill);
});
}
const result = await processPromise;
flush();
if (result.exitCode === 0) {
return result;
}
if (abortSignal?.aborted) {
throw new AbortError('Program was aborted.');
}
log.error('task %s exited with an error', taskId);
throw new Error('Program exited with code ' + result.exitCode + '.');
};
};