index.js 7.5 KB

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