index.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  1. 'use strict';
  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');
  13. const TEN_MEGABYTES = 1000 * 1000 * 10;
  14. function handleArgs(cmd, args, opts) {
  15. let parsed;
  16. if (opts && opts.env && opts.extendEnv !== false) {
  17. opts.env = Object.assign({}, process.env, opts.env);
  18. }
  19. if (opts && opts.__winShell === true) {
  20. delete opts.__winShell;
  21. parsed = {
  22. command: cmd,
  23. args,
  24. options: opts,
  25. file: cmd,
  26. original: cmd
  27. };
  28. } else {
  29. parsed = crossSpawn._parse(cmd, args, opts);
  30. }
  31. opts = Object.assign({
  32. maxBuffer: TEN_MEGABYTES,
  33. stripEof: true,
  34. preferLocal: true,
  35. localDir: parsed.options.cwd || process.cwd(),
  36. encoding: 'utf8',
  37. reject: true,
  38. cleanup: true
  39. }, parsed.options);
  40. opts.stdio = stdio(opts);
  41. if (opts.preferLocal) {
  42. opts.env = npmRunPath.env(Object.assign({}, opts, {cwd: opts.localDir}));
  43. }
  44. return {
  45. cmd: parsed.command,
  46. args: parsed.args,
  47. opts,
  48. parsed
  49. };
  50. }
  51. function handleInput(spawned, opts) {
  52. const input = opts.input;
  53. if (input === null || input === undefined) {
  54. return;
  55. }
  56. if (isStream(input)) {
  57. input.pipe(spawned.stdin);
  58. } else {
  59. spawned.stdin.end(input);
  60. }
  61. }
  62. function handleOutput(opts, val) {
  63. if (val && opts.stripEof) {
  64. val = stripEof(val);
  65. }
  66. return val;
  67. }
  68. function handleShell(fn, cmd, opts) {
  69. let file = '/bin/sh';
  70. let args = ['-c', cmd];
  71. opts = Object.assign({}, opts);
  72. if (process.platform === 'win32') {
  73. opts.__winShell = true;
  74. file = process.env.comspec || 'cmd.exe';
  75. args = ['/s', '/c', `"${cmd}"`];
  76. opts.windowsVerbatimArguments = true;
  77. }
  78. if (opts.shell) {
  79. file = opts.shell;
  80. delete opts.shell;
  81. }
  82. return fn(file, args, opts);
  83. }
  84. function getStream(process, stream, encoding, maxBuffer) {
  85. if (!process[stream]) {
  86. return null;
  87. }
  88. let ret;
  89. if (encoding) {
  90. ret = _getStream(process[stream], {
  91. encoding,
  92. maxBuffer
  93. });
  94. } else {
  95. ret = _getStream.buffer(process[stream], {maxBuffer});
  96. }
  97. return ret.catch(err => {
  98. err.stream = stream;
  99. err.message = `${stream} ${err.message}`;
  100. throw err;
  101. });
  102. }
  103. module.exports = (cmd, args, opts) => {
  104. let joinedCmd = cmd;
  105. if (Array.isArray(args) && args.length > 0) {
  106. joinedCmd += ' ' + args.join(' ');
  107. }
  108. const parsed = handleArgs(cmd, args, opts);
  109. const encoding = parsed.opts.encoding;
  110. const maxBuffer = parsed.opts.maxBuffer;
  111. let spawned;
  112. try {
  113. spawned = childProcess.spawn(parsed.cmd, parsed.args, parsed.opts);
  114. } catch (err) {
  115. return Promise.reject(err);
  116. }
  117. let removeExitHandler;
  118. if (parsed.opts.cleanup) {
  119. removeExitHandler = onExit(() => {
  120. spawned.kill();
  121. });
  122. }
  123. let timeoutId = null;
  124. let timedOut = false;
  125. const cleanupTimeout = () => {
  126. if (timeoutId) {
  127. clearTimeout(timeoutId);
  128. timeoutId = null;
  129. }
  130. };
  131. if (parsed.opts.timeout > 0) {
  132. timeoutId = setTimeout(() => {
  133. timeoutId = null;
  134. timedOut = true;
  135. spawned.kill(parsed.opts.killSignal);
  136. }, parsed.opts.timeout);
  137. }
  138. const processDone = new Promise(resolve => {
  139. spawned.on('exit', (code, signal) => {
  140. cleanupTimeout();
  141. resolve({code, signal});
  142. });
  143. spawned.on('error', err => {
  144. cleanupTimeout();
  145. resolve({err});
  146. });
  147. if (spawned.stdin) {
  148. spawned.stdin.on('error', err => {
  149. cleanupTimeout();
  150. resolve({err});
  151. });
  152. }
  153. });
  154. function destroy() {
  155. if (spawned.stdout) {
  156. spawned.stdout.destroy();
  157. }
  158. if (spawned.stderr) {
  159. spawned.stderr.destroy();
  160. }
  161. }
  162. const promise = pFinally(Promise.all([
  163. processDone,
  164. getStream(spawned, 'stdout', encoding, maxBuffer),
  165. getStream(spawned, 'stderr', encoding, maxBuffer)
  166. ]).then(arr => {
  167. const result = arr[0];
  168. const stdout = arr[1];
  169. const stderr = arr[2];
  170. let err = result.err;
  171. const code = result.code;
  172. const signal = result.signal;
  173. if (removeExitHandler) {
  174. removeExitHandler();
  175. }
  176. if (err || code !== 0 || signal !== null) {
  177. if (!err) {
  178. let output = '';
  179. if (Array.isArray(parsed.opts.stdio)) {
  180. if (parsed.opts.stdio[2] !== 'inherit') {
  181. output += output.length > 0 ? stderr : `\n${stderr}`;
  182. }
  183. if (parsed.opts.stdio[1] !== 'inherit') {
  184. output += `\n${stdout}`;
  185. }
  186. } else if (parsed.opts.stdio !== 'inherit') {
  187. output = `\n${stderr}${stdout}`;
  188. }
  189. err = new Error(`Command failed: ${joinedCmd}${output}`);
  190. err.code = code < 0 ? errname(code) : code;
  191. }
  192. // TODO: missing some timeout logic for killed
  193. // https://github.com/nodejs/node/blob/master/lib/child_process.js#L203
  194. // err.killed = spawned.killed || killed;
  195. err.killed = err.killed || spawned.killed;
  196. err.stdout = stdout;
  197. err.stderr = stderr;
  198. err.failed = true;
  199. err.signal = signal || null;
  200. err.cmd = joinedCmd;
  201. err.timedOut = timedOut;
  202. if (!parsed.opts.reject) {
  203. return err;
  204. }
  205. throw err;
  206. }
  207. return {
  208. stdout: handleOutput(parsed.opts, stdout),
  209. stderr: handleOutput(parsed.opts, stderr),
  210. code: 0,
  211. failed: false,
  212. killed: false,
  213. signal: null,
  214. cmd: joinedCmd,
  215. timedOut: false
  216. };
  217. }), destroy);
  218. crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
  219. handleInput(spawned, parsed.opts);
  220. spawned.then = promise.then.bind(promise);
  221. spawned.catch = promise.catch.bind(promise);
  222. return spawned;
  223. };
  224. module.exports.stdout = function () {
  225. // TODO: set `stderr: 'ignore'` when that option is implemented
  226. return module.exports.apply(null, arguments).then(x => x.stdout);
  227. };
  228. module.exports.stderr = function () {
  229. // TODO: set `stdout: 'ignore'` when that option is implemented
  230. return module.exports.apply(null, arguments).then(x => x.stderr);
  231. };
  232. module.exports.shell = (cmd, opts) => handleShell(module.exports, cmd, opts);
  233. module.exports.sync = (cmd, args, opts) => {
  234. const parsed = handleArgs(cmd, args, opts);
  235. if (isStream(parsed.opts.input)) {
  236. throw new TypeError('The `input` option cannot be a stream in sync mode');
  237. }
  238. const result = childProcess.spawnSync(parsed.cmd, parsed.args, parsed.opts);
  239. if (result.error || result.status !== 0) {
  240. throw (result.error || new Error(result.stderr === '' ? result.stdout : result.stderr));
  241. }
  242. result.stdout = handleOutput(parsed.opts, result.stdout);
  243. result.stderr = handleOutput(parsed.opts, result.stderr);
  244. return result;
  245. };
  246. module.exports.shellSync = (cmd, opts) => handleShell(module.exports.sync, cmd, opts);
  247. module.exports.spawn = util.deprecate(module.exports, 'execa.spawn() is deprecated. Use execa() instead.');