|
1
|
import { exec, spawnSync, SpawnSyncOptions } from "child_process" |
|
2
|
import util from "util" |
|
3
|
import { getAbortError } from "./create-abort-controller.js" |
|
4
|
|
|
5
|
const promiseExec = util.promisify(exec) |
|
6
|
|
|
7
|
export type ExecuteResult = { |
|
8
|
stdout?: string |
|
9
|
stderr?: string |
|
10
|
} |
|
11
|
|
|
12
|
export type VerboseOptions = { |
|
13
|
verbose?: boolean |
|
14
|
// Since spawn doesn't allow us to both retrieve the |
|
15
|
// output and output it live without using events, |
|
16
|
// enabling this option, which is only useful if `verbose` is `true`, |
|
17
|
// defers the output of the process until after the process is executed |
|
18
|
// instead of outputting the log in realtime, which is the default. |
|
19
|
// it prioritizes retrieving the output over outputting it in real-time. |
|
20
|
needOutput?: boolean |
|
21
|
} |
|
22
|
|
|
23
|
type PromiseExecParams = Parameters<typeof promiseExec> |
|
24
|
type SpawnParams = [string, SpawnSyncOptions] |
|
25
|
|
|
26
|
const execute = async ( |
|
27
|
command: SpawnParams | PromiseExecParams, |
|
28
|
{ verbose = false, needOutput = false }: VerboseOptions |
|
29
|
): Promise<ExecuteResult> => { |
|
30
|
if (verbose) { |
|
31
|
const [commandStr, options] = command as SpawnParams |
|
32
|
const childProcess = spawnSync(commandStr, { |
|
33
|
...options, |
|
34
|
shell: true, |
|
35
|
stdio: needOutput |
|
36
|
? "pipe" |
|
37
|
: [process.stdin, process.stdout, process.stderr], |
|
38
|
env: { |
|
39
|
...process.env, |
|
40
|
...(options.env || {}), |
|
41
|
}, |
|
42
|
}) |
|
43
|
|
|
44
|
if (childProcess.error || childProcess.status !== 0) { |
|
45
|
throw ( |
|
46
|
childProcess.error || |
|
47
|
childProcess.stderr?.toString() || |
|
48
|
`${commandStr} failed with status ${childProcess.status}` |
|
49
|
) |
|
50
|
} |
|
51
|
|
|
52
|
if ( |
|
53
|
childProcess.signal && |
|
54
|
["SIGINT", "SIGTERM"].includes(childProcess.signal) |
|
55
|
) { |
|
56
|
throw getAbortError() |
|
57
|
} |
|
58
|
|
|
59
|
if (needOutput) { |
|
60
|
console.log( |
|
61
|
childProcess.stdout?.toString() || childProcess.stderr?.toString() |
|
62
|
) |
|
63
|
} |
|
64
|
|
|
65
|
return { |
|
66
|
stdout: childProcess.stdout?.toString() || "", |
|
67
|
stderr: childProcess.stderr?.toString() || "", |
|
68
|
} |
|
69
|
} else { |
|
70
|
const [commandStr, options] = command as PromiseExecParams |
|
71
|
const childProcess = await promiseExec(commandStr, { |
|
72
|
...options, |
|
73
|
env: { |
|
74
|
...process.env, |
|
75
|
...(options?.env || {}), |
|
76
|
}, |
|
77
|
}) |
|
78
|
|
|
79
|
return { |
|
80
|
stdout: childProcess.stdout as string, |
|
81
|
stderr: childProcess.stderr as string, |
|
82
|
} |
|
83
|
} |
|
84
|
} |
|
85
|
|
|
86
|
export default execute |