2 const path = require('path');
3 const childProcess = require('child_process');
4 const crossSpawn = require('cross-spawn');
5 const stripEof = require('strip-eof');
6 const npmRunPath = require('npm-run-path');
7 const isStream = require('is-stream');
8 const _getStream = require('get-stream');
9 const pFinally = require('p-finally');
10 const onExit = require('signal-exit');
11 const errname = require('./lib/errname');
12 const stdio = require('./lib/stdio');
14 const TEN_MEGABYTES = 1000 * 1000 * 10;
16 function handleArgs(cmd, args, opts) {
19 opts = Object.assign({
25 opts.env = Object.assign({}, process.env, opts.env);
28 if (opts.__winShell === true) {
29 delete opts.__winShell;
41 parsed = crossSpawn._parse(cmd, args, opts);
44 opts = Object.assign({
45 maxBuffer: TEN_MEGABYTES,
49 localDir: parsed.options.cwd || process.cwd(),
55 opts.stdio = stdio(opts);
57 if (opts.preferLocal) {
58 opts.env = npmRunPath.env(Object.assign({}, opts, {cwd: opts.localDir}));
66 if (process.platform === 'win32' && path.basename(parsed.command) === 'cmd.exe') {
68 parsed.args.unshift('/q');
79 function handleInput(spawned, input) {
80 if (input === null || input === undefined) {
84 if (isStream(input)) {
85 input.pipe(spawned.stdin);
87 spawned.stdin.end(input);
91 function handleOutput(opts, val) {
92 if (val && opts.stripEof) {
99 function handleShell(fn, cmd, opts) {
100 let file = '/bin/sh';
101 let args = ['-c', cmd];
103 opts = Object.assign({}, opts);
105 if (process.platform === 'win32') {
106 opts.__winShell = true;
107 file = process.env.comspec || 'cmd.exe';
108 args = ['/s', '/c', `"${cmd}"`];
109 opts.windowsVerbatimArguments = true;
117 return fn(file, args, opts);
120 function getStream(process, stream, {encoding, buffer, maxBuffer}) {
121 if (!process[stream]) {
128 // TODO: Use `ret = util.promisify(stream.finished)(process[stream]);` when targeting Node.js 10
129 ret = new Promise((resolve, reject) => {
131 .once('end', resolve)
132 .once('error', reject);
134 } else if (encoding) {
135 ret = _getStream(process[stream], {
140 ret = _getStream.buffer(process[stream], {maxBuffer});
143 return ret.catch(err => {
145 err.message = `${stream} ${err.message}`;
150 function makeError(result, options) {
151 const {stdout, stderr} = result;
153 let err = result.error;
154 const {code, signal} = result;
156 const {parsed, joinedCmd} = options;
157 const timedOut = options.timedOut || false;
162 if (Array.isArray(parsed.opts.stdio)) {
163 if (parsed.opts.stdio[2] !== 'inherit') {
164 output += output.length > 0 ? stderr : `\n${stderr}`;
167 if (parsed.opts.stdio[1] !== 'inherit') {
168 output += `\n${stdout}`;
170 } else if (parsed.opts.stdio !== 'inherit') {
171 output = `\n${stderr}${stdout}`;
174 err = new Error(`Command failed: ${joinedCmd}${output}`);
175 err.code = code < 0 ? errname(code) : code;
181 err.signal = signal || null;
183 err.timedOut = timedOut;
188 function joinCmd(cmd, args) {
191 if (Array.isArray(args) && args.length > 0) {
192 joinedCmd += ' ' + args.join(' ');
198 module.exports = (cmd, args, opts) => {
199 const parsed = handleArgs(cmd, args, opts);
200 const {encoding, buffer, maxBuffer} = parsed.opts;
201 const joinedCmd = joinCmd(cmd, args);
205 spawned = childProcess.spawn(parsed.cmd, parsed.args, parsed.opts);
207 return Promise.reject(err);
210 let removeExitHandler;
211 if (parsed.opts.cleanup) {
212 removeExitHandler = onExit(() => {
217 let timeoutId = null;
218 let timedOut = false;
220 const cleanup = () => {
222 clearTimeout(timeoutId);
226 if (removeExitHandler) {
231 if (parsed.opts.timeout > 0) {
232 timeoutId = setTimeout(() => {
235 spawned.kill(parsed.opts.killSignal);
236 }, parsed.opts.timeout);
239 const processDone = new Promise(resolve => {
240 spawned.on('exit', (code, signal) => {
242 resolve({code, signal});
245 spawned.on('error', err => {
247 resolve({error: err});
251 spawned.stdin.on('error', err => {
253 resolve({error: err});
259 if (spawned.stdout) {
260 spawned.stdout.destroy();
263 if (spawned.stderr) {
264 spawned.stderr.destroy();
268 const handlePromise = () => pFinally(Promise.all([
270 getStream(spawned, 'stdout', {encoding, buffer, maxBuffer}),
271 getStream(spawned, 'stderr', {encoding, buffer, maxBuffer})
273 const result = arr[0];
274 result.stdout = arr[1];
275 result.stderr = arr[2];
277 if (result.error || result.code !== 0 || result.signal !== null) {
278 const err = makeError(result, {
284 // TODO: missing some timeout logic for killed
285 // https://github.com/nodejs/node/blob/master/lib/child_process.js#L203
286 // err.killed = spawned.killed || killed;
287 err.killed = err.killed || spawned.killed;
289 if (!parsed.opts.reject) {
297 stdout: handleOutput(parsed.opts, result.stdout),
298 stderr: handleOutput(parsed.opts, result.stderr),
308 crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
310 handleInput(spawned, parsed.opts.input);
312 spawned.then = (onfulfilled, onrejected) => handlePromise().then(onfulfilled, onrejected);
313 spawned.catch = onrejected => handlePromise().catch(onrejected);
318 // TODO: set `stderr: 'ignore'` when that option is implemented
319 module.exports.stdout = (...args) => module.exports(...args).then(x => x.stdout);
321 // TODO: set `stdout: 'ignore'` when that option is implemented
322 module.exports.stderr = (...args) => module.exports(...args).then(x => x.stderr);
324 module.exports.shell = (cmd, opts) => handleShell(module.exports, cmd, opts);
326 module.exports.sync = (cmd, args, opts) => {
327 const parsed = handleArgs(cmd, args, opts);
328 const joinedCmd = joinCmd(cmd, args);
330 if (isStream(parsed.opts.input)) {
331 throw new TypeError('The `input` option cannot be a stream in sync mode');
334 const result = childProcess.spawnSync(parsed.cmd, parsed.args, parsed.opts);
335 result.code = result.status;
337 if (result.error || result.status !== 0 || result.signal !== null) {
338 const err = makeError(result, {
343 if (!parsed.opts.reject) {
351 stdout: handleOutput(parsed.opts, result.stdout),
352 stderr: handleOutput(parsed.opts, result.stderr),
361 module.exports.shellSync = (cmd, opts) => handleShell(module.exports.sync, cmd, opts);