-
-
Notifications
You must be signed in to change notification settings - Fork 436
/
Copy pathexec-util.ts
70 lines (68 loc) · 2.86 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
67
68
69
70
import * as os from 'os';
import * as which from 'which';
import * as semver from 'semver';
import { join } from 'path';
import { spawn } from 'child_process';
export async function getExecPath(commandName: string, onError: (error: Error) => void = (error) => console.log(error), versionArg?: string, inBinDir?: boolean): Promise<string> {
const execName = `${commandName}${os.platform() === 'win32' ? '.exe' : ''}`;
const relativePath = ['..', '..', 'build'];
if (inBinDir) {
relativePath.push('bin');
}
const buildCommand = join(__dirname, ...relativePath, execName);
if (!versionArg) {
return buildCommand;
}
const versionRegexp = /\d+\.\d+\.\d+/;
const buildVersion = await spawnCommand(`"${buildCommand}"`, [versionArg], onError);
const buildShortVersion = (buildVersion.match(versionRegexp) || [])[0];
const pathCommand = await new Promise<string | undefined>(resolve => which(execName, (error, path) => resolve(error ? undefined : path)));
if (!pathCommand) {
return buildCommand;
}
const pathVersion = await spawnCommand(`"${pathCommand}"`, [versionArg], onError);
const pathShortVersion = (pathVersion.match(versionRegexp) || [])[0];
if (semver.gt(pathShortVersion, buildShortVersion)) {
return pathCommand;
}
return buildCommand;
}
export function spawnCommand(command: string, args: string[], onError: (error: Error) => void = (error) => console.log(error)): Promise<string> {
return new Promise<string>((resolve, reject) => {
const cp = spawn(command, args, { windowsHide: true, shell: 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').trim()
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;
}
});
});
}