2 const childProcess = require('child_process');
3 const util = require('util');
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 if (opts && opts.env && opts.extendEnv !== false) {
20 opts.env = Object.assign({}, process.env, opts.env);
23 if (opts && opts.__winShell === true) {
24 delete opts.__winShell;
33 parsed = crossSpawn._parse(cmd, args, opts);
36 opts = Object.assign({
37 maxBuffer: TEN_MEGABYTES,
40 localDir: parsed.options.cwd || process.cwd(),
46 opts.stdio = stdio(opts);
48 if (opts.preferLocal) {
49 opts.env = npmRunPath.env(Object.assign({}, opts, {cwd: opts.localDir}));
60 function handleInput(spawned, opts) {
61 const input = opts.input;
63 if (input === null || input === undefined) {
67 if (isStream(input)) {
68 input.pipe(spawned.stdin);
70 spawned.stdin.end(input);
74 function handleOutput(opts, val) {
75 if (val && opts.stripEof) {
82 function handleShell(fn, cmd, opts) {
84 let args = ['-c', cmd];
86 opts = Object.assign({}, opts);
88 if (process.platform === 'win32') {
89 opts.__winShell = true;
90 file = process.env.comspec || 'cmd.exe';
91 args = ['/s', '/c', `"${cmd}"`];
92 opts.windowsVerbatimArguments = true;
100 return fn(file, args, opts);
103 function getStream(process, stream, encoding, maxBuffer) {
104 if (!process[stream]) {
111 ret = _getStream(process[stream], {
116 ret = _getStream.buffer(process[stream], {maxBuffer});
119 return ret.catch(err => {
121 err.message = `${stream} ${err.message}`;
126 module.exports = (cmd, args, opts) => {
129 if (Array.isArray(args) && args.length > 0) {
130 joinedCmd += ' ' + args.join(' ');
133 const parsed = handleArgs(cmd, args, opts);
134 const encoding = parsed.opts.encoding;
135 const maxBuffer = parsed.opts.maxBuffer;
139 spawned = childProcess.spawn(parsed.cmd, parsed.args, parsed.opts);
141 return Promise.reject(err);
144 let removeExitHandler;
145 if (parsed.opts.cleanup) {
146 removeExitHandler = onExit(() => {
151 let timeoutId = null;
152 let timedOut = false;
154 const cleanupTimeout = () => {
156 clearTimeout(timeoutId);
161 if (parsed.opts.timeout > 0) {
162 timeoutId = setTimeout(() => {
165 spawned.kill(parsed.opts.killSignal);
166 }, parsed.opts.timeout);
169 const processDone = new Promise(resolve => {
170 spawned.on('exit', (code, signal) => {
172 resolve({code, signal});
175 spawned.on('error', err => {
181 spawned.stdin.on('error', err => {
189 if (spawned.stdout) {
190 spawned.stdout.destroy();
193 if (spawned.stderr) {
194 spawned.stderr.destroy();
198 const promise = pFinally(Promise.all([
200 getStream(spawned, 'stdout', encoding, maxBuffer),
201 getStream(spawned, 'stderr', encoding, maxBuffer)
203 const result = arr[0];
204 const stdout = arr[1];
205 const stderr = arr[2];
207 let err = result.err;
208 const code = result.code;
209 const signal = result.signal;
211 if (removeExitHandler) {
215 if (err || code !== 0 || signal !== null) {
219 if (Array.isArray(parsed.opts.stdio)) {
220 if (parsed.opts.stdio[2] !== 'inherit') {
221 output += output.length > 0 ? stderr : `\n${stderr}`;
224 if (parsed.opts.stdio[1] !== 'inherit') {
225 output += `\n${stdout}`;
227 } else if (parsed.opts.stdio !== 'inherit') {
228 output = `\n${stderr}${stdout}`;
231 err = new Error(`Command failed: ${joinedCmd}${output}`);
232 err.code = code < 0 ? errname(code) : code;
235 // TODO: missing some timeout logic for killed
236 // https://github.com/nodejs/node/blob/master/lib/child_process.js#L203
237 // err.killed = spawned.killed || killed;
238 err.killed = err.killed || spawned.killed;
243 err.signal = signal || null;
245 err.timedOut = timedOut;
247 if (!parsed.opts.reject) {
255 stdout: handleOutput(parsed.opts, stdout),
256 stderr: handleOutput(parsed.opts, stderr),
266 crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
268 handleInput(spawned, parsed.opts);
270 spawned.then = promise.then.bind(promise);
271 spawned.catch = promise.catch.bind(promise);
276 module.exports.stdout = function () {
277 // TODO: set `stderr: 'ignore'` when that option is implemented
278 return module.exports.apply(null, arguments).then(x => x.stdout);
281 module.exports.stderr = function () {
282 // TODO: set `stdout: 'ignore'` when that option is implemented
283 return module.exports.apply(null, arguments).then(x => x.stderr);
286 module.exports.shell = (cmd, opts) => handleShell(module.exports, cmd, opts);
288 module.exports.sync = (cmd, args, opts) => {
289 const parsed = handleArgs(cmd, args, opts);
291 if (isStream(parsed.opts.input)) {
292 throw new TypeError('The `input` option cannot be a stream in sync mode');
295 const result = childProcess.spawnSync(parsed.cmd, parsed.args, parsed.opts);
297 if (result.error || result.status !== 0) {
298 throw (result.error || new Error(result.stderr === '' ? result.stdout : result.stderr));
301 result.stdout = handleOutput(parsed.opts, result.stdout);
302 result.stderr = handleOutput(parsed.opts, result.stderr);
307 module.exports.shellSync = (cmd, opts) => handleShell(module.exports.sync, cmd, opts);
309 module.exports.spawn = util.deprecate(module.exports, 'execa.spawn() is deprecated. Use execa() instead.');