-
-
Notifications
You must be signed in to change notification settings - Fork 436
/
Copy pathexec-util.ts
66 lines (63 loc) · 1.95 KB
/
exec-util.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
import { spawn } from 'node:child_process';
import os from 'node:os';
import { join } from 'node:path';
export type ArduinoBinaryName =
| 'arduino-cli'
| 'arduino-fwuploader'
| 'arduino-language-server';
export type ClangBinaryName = 'clangd' | 'clang-format';
export type BinaryName = ArduinoBinaryName | ClangBinaryName;
export function getExecPath(binaryName: BinaryName): string {
const filename = `${binaryName}${os.platform() === 'win32' ? '.exe' : ''}`;
return join(__dirname, '..', '..', 'build', filename);
}
export function spawnCommand(
command: string,
args: string[],
onError: (error: Error) => void = (error) => console.log(error),
stdIn?: string
): Promise<string> {
return new Promise<string>((resolve, reject) => {
const cp = spawn(command, args, { windowsHide: true });
const outBuffers: Buffer[] = [];
const errBuffers: Buffer[] = [];
cp.stdout.on('data', (b: Buffer) => outBuffers.push(b));
cp.stderr.on('data', (b: Buffer) => errBuffers.push(b));
cp.on('error', (error) => {
onError(error);
reject(error);
});
cp.on('exit', (code, signal) => {
if (code === 0) {
const result = Buffer.concat(outBuffers).toString('utf8');
resolve(result);
return;
}
if (errBuffers.length > 0) {
const message = Buffer.concat(errBuffers).toString('utf8').trim();
const error = new Error(
`Error executing ${command} ${args.join(' ')}: ${message}`
);
onError(error);
reject(error);
return;
}
if (signal) {
const error = new Error(`Process exited with signal: ${signal}`);
onError(error);
reject(error);
return;
}
if (code) {
const error = new Error(`Process exited with exit code: ${code}`);
onError(error);
reject(error);
return;
}
});
if (stdIn !== undefined) {
cp.stdin.write(stdIn);
cp.stdin.end();
}
});
}