index.js 7.5 KB

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