1 | const cp = require('child_process');
|
2 | const _ = require('lodash');
|
3 |
|
4 | function execSync(command) {
|
5 | const normalized = normalizeSpace(command);
|
6 | console.log(normalized);
|
7 | cp.execSync(normalized, { stdio: ['inherit', 'inherit', 'inherit'] });
|
8 | }
|
9 |
|
10 | function execSyncSilent(command) {
|
11 | const normalized = normalizeSpace(command);
|
12 | cp.execSync(normalized, { stdio: ['ignore', 'ignore', 'ignore'] });
|
13 | }
|
14 |
|
15 | function execSyncRead(command) {
|
16 | const normalized = normalizeSpace(command);
|
17 | console.log(normalized);
|
18 | return _.trim(String(cp.execSync(normalized, { stdio: ['inherit', 'pipe', 'inherit'] })));
|
19 | }
|
20 |
|
21 | function execAsync(command) {
|
22 | const normalized = normalizeSpace(command);
|
23 | return new Promise((resolve, reject) => {
|
24 | const child = cp.exec(normalized, (err, stdout, stderr) => {
|
25 | if (err) {
|
26 | reject(err);
|
27 | } else {
|
28 | resolve({ stdout, stderr });
|
29 | }
|
30 | });
|
31 | child.stdout.pipe(process.stdout);
|
32 | child.stderr.pipe(process.stderr);
|
33 | });
|
34 | }
|
35 |
|
36 | function kill(process) {
|
37 | execSyncSilent(`pkill -f "${process}" || true`);
|
38 | }
|
39 |
|
40 | function killPort(port) {
|
41 | execSync(`lsof -t -i :${port} | xargs kill || true`);
|
42 | }
|
43 |
|
44 | function which(what) {
|
45 | try {
|
46 | return execSyncRead(`which ${what}`);
|
47 | } catch (e) {
|
48 | return undefined;
|
49 | }
|
50 | }
|
51 |
|
52 | module.exports = {
|
53 | execSync,
|
54 | execSyncSilent,
|
55 | execSyncRead,
|
56 | execAsync,
|
57 | kill,
|
58 | which,
|
59 | killPort
|
60 | };
|
61 |
|
62 | const WHITESPACE_REGEX = /\s+/g;
|
63 |
|
64 | function normalizeSpace(str) {
|
65 | if (!_.isString(str)) {
|
66 | return '';
|
67 | }
|
68 | return _.replace(_.trim(str), WHITESPACE_REGEX, ' ');
|
69 | }
|
70 |
|