-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
315 lines (303 loc) · 11.4 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
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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
const childProcess = require("child_process");
const { Stream } = require("stream");
const passThruColorizer = s => s;
const defaultColor = findColorPackage(
"ansi-colors",
"colorette",
"chalk",
"kleur"
) || {
prompt: passThruColorizer,
command: passThruColorizer,
stdout: passThruColorizer,
stderr: passThruColorizer
};
function findColorPackage(...packages) {
while (packages.length) {
const pkg = packages.shift();
try {
return require(pkg);
} catch (error) {
// ignore optional dependencies.
continue;
}
}
return null;
}
const SUCCESSFUL_EXIT_CODE = 0;
function getStreamDataReducer(capture, quiet, encoding) {
if (capture) {
if (quiet) {
return (acc, chunk) => acc + chunk.toString(encoding);
}
return (acc, chunk, stream, colorize) => {
const s = chunk.toString(encoding);
stream.write(colorize(s));
return acc + s;
};
} else {
if (quiet) {
return null;
}
return (acc, chunk, stream, colorize) => {
const s = chunk.toString(encoding);
stream.write(colorize(s));
return null;
};
}
}
function escapeSingleQuotes(s) {
return s.replace(/['\\]/g, m => `\\${m}`);
}
function makeSingleQuoted(s) {
return `'${escapeSingleQuotes(s)}'`;
}
function safeMakeDoubleQuoted(s) {
return `"${s}"`;
}
const hasSpacesRe = /\s/;
const hasSingleQuotesRe = /'/;
const hasShellCharsRe = /[&|;!$"\\]/;
function prettyValue(arg) {
const hasSpaces = hasSpacesRe.test(arg);
const hasSingleQuotes = hasSingleQuotesRe.test(arg);
const hasShellChars = hasShellCharsRe.test(arg);
if (hasShellChars) {
return makeSingleQuoted(arg);
} else if (hasSingleQuotes || hasSpaces) {
return safeMakeDoubleQuoted(arg);
}
return arg;
}
function prettyCommand(args, env) {
const envOverride =
Object.keys(env).length === 0
? ""
: Object.entries(env)
.map(([k, v]) => `${prettyValue(k)}=${prettyValue(v)}`)
.join(" ") + " ";
return envOverride + args.map(prettyValue).join(" ");
}
function getColorizer(_color) {
const color = !_color ? {} : _color === true ? defaultColor : _color;
const colorizer = {
prompt: color.prompt || color.command || color.gray || color.grey,
command: color.command || color.gray || color.grey,
stdout: color.stdout || color.green,
stderr: color.stderr || color.red
};
Object.keys(colorizer).forEach(propName => {
const method = colorizer[propName] || defaultColor[propName];
const bindTarget = method ? color : defaultColor;
if (method) {
colorizer[propName] =
(method.bind && method.bind(bindTarget)) ||
(method.apply && (s => method.apply(bindTarget, [s]))) ||
method;
}
});
return colorizer;
}
/**
*
* @param {Array<String>} command The command to excute, as an array of arguments (starting with
* the command itself).
* @param {Object} [config]
* @param {Object} [config.env={}] An object of environment variables. If not given, the
* current process's environment is used. If this is given, it is **merged**
* with the current process's environment (overwriting any existing env vars for the child).
* @param {boolean} [config.capture=true] Whether or not to capture STDOUT and STDERR into
* in-memory buffers. This is done by default so they can be returned in the fulfillment
* value, and also used in Errors. However, if the command produces a huge amount of output
* that you don't actually need, you can set this to false to save the memory.
* @param {boolean} [config.quiet=false] Default behavior is to write the command being
* executed, plus STDOUT and STDERR from the child process to this process's output
* streams. Set this to ``true`` to supress this.
* @param {null|Stream|Buffer|string|number} [config.stdin] Optionally, provide STDIN for the subprocess.
* If `undefined` or not given, then the current process's STDIN is used. If `null`, then the STDIN of
* the subprocess will be connected to a closed stream (e.g. /dev/null). If a `Stream`, the stream is used,
* but keep in mind that the Stream must have an underlying file-descriptor (see
* https://nodejs.org/api/child_process.html#child_process_options_stdio). If a `Buffer` or a `string`,
* then the contents are written to the subprocess's STDIN which is then closed (encoding for a string
* is "utf-8", if you need another encoding, turn it into a `Buffer` yourself). If a number, it is
* passed as the file descriptor to use for STDIN.
* @param {String} [config.encoding="utf8"] Optionally, provide the encoding for
* the STDOUT and STDERR streams from the child process.
* @param {boolean} [config.propagateSignals=true] By default, SIGINT and SIGTERM signals
* that terminate the child process are caught and forwarded to the parent process as well.
* If you set this to `false` instead, those signals will not be forwarded to the parent
* process.
* @param {Object|boolean} [config.color=true] An object providing methods that are used to colorize
* output. This is ignored if `quiet` is true. If `chalk` or `ansi-color` are available,
* they are used as the defaut colors. If not available, the default will not transform the output
* at all. If you don't want any colors, pass `false`. Otherwise,
* use the default or pass in an object which has methods named `prompt`, `command`, `stdout`, and
* `stderr` to return the colorized versionsof the different parts of the output. If those methods
* are not available, a series of defaults will be applied, generally reaching to `gray`, `gray`,
* `green`, and `red` respectively. If these defaults still aren't found, the string will be passed
* through unmodified.
*
* @async
* @returns A promise to fulfill when the child process completes successfully.
* Successful completion is considered to be that the process exits with an
* exit code of 0. When this happens, the promise fulfills with an object that
* has a `code` property equal to the child process's exit code (therefore, 0).
* If `capture` is enabled (the default), then the fulfillment value also has
* `stdout` and `stderr` properties which are the captured output Strings from
* the process.
*
* If the child process fails to launch, if it exits with a non-zero exit code,
* or if it terminates with an unhandled signal, then the returned promise will
* reject. If `capture` is enabled, the rejection error will include `stdout`
* and `stderr` properties containing the captured output Strings from the
* child process. The error will also have `command`, `args`, and `shellCommand`
* properties attached to it, giving, respectively, the first command line argument,
* the remaining command line arguments, and a String meant to represent the command
* as it might be invoked in the shell (ymmv). If the process exited with a non-zero
* exit code, this is attached to the error in a `code` property, or if the process
* exits due to an unhandled signal, the name of the signal is attached to the error
* in a `signal` property.
*/
module.exports = function justRunThis(
_args,
{
env = {},
capture = true,
quiet = false,
stdin = process.stdin,
encoding = "utf8",
propagateSignals = true,
color: _color = true,
dryRun = false
} = {}
) {
const errorSource = new Error();
const shellCommand = prettyCommand(_args, env);
const [command, ...args] = _args;
let stdout = null;
let stderr = null;
if (capture) {
stdout = "";
stderr = "";
}
const createError = (error, props = {}) => {
const errorMessage = error instanceof Error ? error.message : error;
const e = new Error(errorMessage);
e.stack = errorSource.stack.replace(/^Error/, `Error: ${errorMessage}`);
if (error instanceof Error) {
e.cause = error;
e.stack += `\n caused by: ${error.stack}`;
}
e.command = command;
e.args = args;
e.shellCommand = shellCommand;
e.stdout = stdout;
e.stderr = stderr;
Object.assign(e, props);
return e;
};
return new Promise((resolve, reject) => {
const color = getColorizer(_color);
const printCommand = () => {
if (!quiet) {
console.log(color.prompt("> ") + color.command(shellCommand));
}
};
printCommand();
if (dryRun) {
resolve();
return;
}
const outputOpt = capture || !quiet ? "pipe" : "ignore";
const [stdinOption, feedStdin] = getStdinOption(stdin);
const proc = childProcess.spawn(command, args, {
stdio: [stdinOption, outputOpt, outputOpt],
env: {
...process.env,
...env
}
});
const streamReducer = getStreamDataReducer(
capture,
quiet,
encoding,
color
);
if (streamReducer) {
proc.stdout.on("data", chunk => {
stdout = streamReducer(
stdout,
chunk,
process.stdout,
color.stdout
);
});
proc.stderr.on("data", chunk => {
stderr = streamReducer(
stderr,
chunk,
process.stderr,
color.stderr
);
});
}
feedStdin(proc.stdin);
proc.on("error", error => reject(createError(error)));
proc.on("exit", (code, signal) => {
if (code === SUCCESSFUL_EXIT_CODE) {
if (capture) {
resolve({ code, stdout, stderr });
} else {
resolve({ code });
}
} else if (code !== null) {
reject(
createError(
`Command process exited with error code ${code}`,
{ code }
)
);
} else {
if (
propagateSignals &&
(signal === "SIGINT" || signal === "SIGTERM")
) {
process.kill(process.pid, signal);
}
reject(
createError(
`Command process exited due to signal ${signal}`,
{ signal }
)
);
}
});
});
};
function getStdinOption(stdin, encoding = "utf-8") {
if (stdin instanceof Stream) {
return [stdin, () => {}];
} else if (stdin instanceof Buffer) {
return [
"pipe",
pipe => {
pipe.write(stdin);
pipe.end();
}
];
} else if (typeof stdin === "string") {
return [
"pipe",
pipe => {
pipe.write(stdin, encoding);
pipe.end();
}
];
} else if (stdin === null) {
return ["ignore", () => {}];
} else if (typeof stdin === "undefined") {
return process.stdin;
} else {
return [stdin, () => {}];
}
}