-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathexecute-process.ts
More file actions
202 lines (188 loc) · 5.19 KB
/
execute-process.ts
File metadata and controls
202 lines (188 loc) · 5.19 KB
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
import {
type ChildProcess,
type ChildProcessByStdio,
type SpawnOptionsWithStdioTuple,
type StdioPipe,
spawn,
} from 'node:child_process';
import type { Readable, Writable } from 'node:stream';
import { quote } from 'shell-quote';
import { isVerbose } from './env.js';
import { formatCommandLog } from './format-command-log.js';
import { ui } from './logging.js';
import { calcDuration } from './reports/utils.js';
/**
* Represents the process result.
* @category Types
* @public
* @property {string} stdout - The stdout of the process.
* @property {string} stderr - The stderr of the process.
* @property {number | null} code - The exit code of the process.
*/
export type ProcessResult = {
stdout: string;
stderr: string;
code: number | null;
date: string;
duration: number;
};
/**
* Error class for process errors.
* Contains additional information about the process result.
* @category Error
* @public
* @class
* @extends Error
* @example
* const result = await executeProcess({})
* .catch((error) => {
* if (error instanceof ProcessError) {
* console.error(error.code);
* console.error(error.stderr);
* console.error(error.stdout);
* }
* });
*
*/
export class ProcessError extends Error {
code: number | null;
stderr: string;
stdout: string;
constructor(result: ProcessResult) {
super(result.stderr);
this.code = result.code;
this.stderr = result.stderr;
this.stdout = result.stdout;
}
}
/**
* Process config object. Contains the command, args and observer.
* @param cfg - process config object with command, args and observer (optional)
* @category Types
* @public
* @property {string} command - The command to execute.
* @property {string[]} args - The arguments for the command.
* @property {ProcessObserver} observer - The observer for the process.
*
* @example
*
* // bash command
* const cfg = {
* command: 'bash',
* args: ['-c', 'echo "hello world"']
* };
*
* // node command
* const cfg = {
* command: 'node',
* args: ['--version']
* };
*
* // npx command
* const cfg = {
* command: 'npx',
* args: ['--version']
*
*/
export type ProcessConfig = Omit<
SpawnOptionsWithStdioTuple<StdioPipe, StdioPipe, StdioPipe>,
'stdio'
> & {
command: string;
args?: string[];
observer?: ProcessObserver;
ignoreExitCode?: boolean;
};
/**
* Process observer object. Contains the onStdout, error and complete function.
* @category Types
* @public
* @property {function} onStdout - The onStdout function of the observer (optional).
* @property {function} onError - The error function of the observer (optional).
* @property {function} onComplete - The complete function of the observer (optional).
*
* @example
* const observer = {
* onStdout: (stdout) => console.info(stdout)
* }
*/
export type ProcessObserver = {
onStdout?: (stdout: string, sourceProcess?: ChildProcess) => void;
onStderr?: (stderr: string, sourceProcess?: ChildProcess) => void;
onError?: (error: ProcessError) => void;
onComplete?: () => void;
};
/**
* Executes a process and returns a promise with the result as `ProcessResult`.
*
* @example
*
* // sync process execution
* const result = await executeProcess({
* command: 'node',
* args: ['--version']
* });
*
* console.info(result);
*
* // async process execution
* const result = await executeProcess({
* command: 'node',
* args: ['download-data.js'],
* observer: {
* onStdout: updateProgress,
* error: handleError,
* complete: cleanLogs,
* }
* });
*
* console.info(result);
*
* @param cfg - see {@link ProcessConfig}
*/
export function executeProcess(cfg: ProcessConfig): Promise<ProcessResult> {
const { command, args, observer, ignoreExitCode = false, ...options } = cfg;
const { onStdout, onStderr, onError, onComplete } = observer ?? {};
const date = new Date().toISOString();
const start = performance.now();
if (isVerbose()) {
ui().logger.log(
formatCommandLog(command, args, `${cfg.cwd ?? process.cwd()}`),
);
}
const bin = [command, quote(args ?? [])].join(' ');
return new Promise((resolve, reject) => {
// shell:true tells Windows to use shell command for spawning a child process
const spawnedProcess = spawn(bin, {
shell: true,
windowsHide: true,
...options,
}) as ChildProcessByStdio<Writable, Readable, Readable>;
// eslint-disable-next-line functional/no-let
let stdout = '';
// eslint-disable-next-line functional/no-let
let stderr = '';
spawnedProcess.stdout.on('data', data => {
stdout += String(data);
onStdout?.(String(data), spawnedProcess);
});
spawnedProcess.stderr.on('data', data => {
stderr += String(data);
onStderr?.(String(data), spawnedProcess);
});
spawnedProcess.on('error', err => {
stderr += err.toString();
});
spawnedProcess.on('close', code => {
const timings = { date, duration: calcDuration(start) };
if (code === 0 || ignoreExitCode) {
onComplete?.();
resolve({ code, stdout, stderr, ...timings });
} else {
const errorMsg = new ProcessError({ code, stdout, stderr, ...timings });
onError?.(errorMsg);
reject(errorMsg);
}
});
});
}