-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
75 lines (70 loc) · 2.15 KB
/
index.js
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
import cp from "child_process"
import sh from "shelljs"
import _pwd from "shelljs/src/pwd.js"
import through2 from "through2"
import streamToString from "stream-to-string"
const redColor = "\u001b[31m";
const resetColor = "\u001b[0m";
export async function exec(command, options = {}) {
const child = sh.exec(command, { async: true, silent: true });
return new Promise((resolve, reject) => {
const stringStdout = streamToString(child.stdout);
child.on('close', async (code) => {
if (code !== 0) {
return reject(`exit code (${code})`);
}
resolve(await stringStdout);
});
if (options.silent) {
return void 0;
}
child.stdout.pipe(process.stdout);
child.stderr.pipe((() => {
let isHead = true;
return through2(function(buf, enc, next) {
if (isHead) {
isHead = false;
return next(null, Buffer.concat([Buffer.from("\u001b[31m"), buf, Buffer.from(resetColor)]));
}
return next(null, buf);
}, function(flush) {
this.push(Buffer.from(resetColor))
flush();
})
})()).pipe(process.stderr);
});
}
export async function spawn(command, args, options = {}) {
const child = cp.spawn(command, args, {
cwd: _pwd(),
stdio: ['pipe', options.stdoutInherit ? 'inherit' : 'pipe', 'pipe']
});
return new Promise((resolve, reject) => {
const stringStdout = child.stdout ? streamToString(child.stdout) : Promise.resolve(null);
child.on('close', async (code) => {
if (code !== 0) {
return reject(`exit code (${code})`);
}
resolve(await stringStdout);
});
if (options.silent) {
return void 0;
}
if (!options.stdoutInherit) {
child.stdout.pipe(process.stdout);
}
child.stderr.pipe((() => {
let isHead = true;
return through2(function(buf, enc, next) {
if (isHead) {
isHead = false;
return next(null, Buffer.concat([Buffer.from(redColor), buf, Buffer.from(resetColor)]));
}
return next(null, buf);
}, function(flush) {
this.push(Buffer.from(resetColor))
flush();
})
})()).pipe(process.stderr);
});
}