4d5134555274b015eb61389144b3a23f4321063b75d6b02a6f74f1f974a6c9072b14c70d1fafaacd55ef04c09f2a21f0d97d897fb5fb8cccb569e61a3d3290 6.7 KB

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