Skip to content
Myr

Make the spawned process cancelable (#189)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Fixes #113

authored by Ammar · committed by Sindre Sorhus · parent dca1504 · Browse files · 3 files+89 added−6 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+89 added−6 removed

  • other:+89 added−6 removed

3 files+89 added−6 removed

modified:index.js+23 added-6 removed
141 unmodified lines
142143function makeError(result, options) {144 const {stdout, stderr, code, signal} = result;145 let {error} = result;146 const {joinedCommand, timedOut, parsed: {options: {timeout}}} = options;146 const {joinedCommand, timedOut, isCanceled, parsed: {options: {timeout}}} = options;147148 const [exitCodeName, exitCode] = getCode(result, code);149150 if (!(error instanceof Error)) {151 const message = [joinedCommand, stderr, stdout].filter(Boolean).join('\n');152 error = new Error(message);153 }154155 const prefix = getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode});155 const prefix = getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled});156 error.message = `Command ${prefix}: ${error.message}`;157158 error.code = exitCode || exitCodeName;159 error.exitCode = exitCode;
5 unmodified lines
165 // it to `undefined`166 error.signal = signal || undefined;167 error.cmd = joinedCommand;168 error.timedOut = Boolean(timedOut);169 error.isCanceled = isCanceled;170171 if ('all' in result) {172 error.all = result.all;173 }
12 unmodified lines
186187 return [];188}189189function getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode}) {190function getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled}) {191 if (timedOut) {192 return `timed out after ${timeout} milliseconds`;193 }194195 if (isCanceled) {196 return 'was canceled';197 }198199 if (signal) {200 return `was killed with ${signal}`;201 }202
42 unmodified lines
245 }246247 let timeoutId;248 let timedOut = false;249 let isCanceled = false;250251 const cleanup = () => {252 if (timeoutId !== undefined) {253 clearTimeout(timeoutId);
57 unmodified lines
311 result.stdout = results[1];312 result.stderr = results[2];313 result.all = results[3];314309 if (result.error || result.code !== 0 || result.signal !== null) {315 if (result.error || result.code !== 0 || result.signal !== null || isCanceled) {316 const error = makeError(result, {317 joinedCommand,318 parsed,313 timedOut319 timedOut,320 isCanceled321 });322323 // TODO: missing some timeout logic for killed324 // https://github.com/nodejs/node/blob/master/lib/child_process.js#L203
16 unmodified lines
341 exitCodeName: 'SUCCESS',342 failed: false,343 killed: false,344 cmd: joinedCommand,338 timedOut: false345 timedOut: false,346 isCanceled: false347 };348 }), destroy);349350 crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);
4 unmodified lines
355356 // eslint-disable-next-line promise/prefer-await-to-then357 spawned.then = (onFulfilled, onRejected) => handlePromise().then(onFulfilled, onRejected);358 spawned.catch = onRejected => handlePromise().catch(onRejected);359 spawned.cancel = () => {360 if (spawned.killed) {361 return;362 }363364 if (spawned.kill()) {365 isCanceled = true;366 }367 };368369 // TOOD: Remove the `if`-guard when targeting Node.js 10370 if (Promise.prototype.finally) {371 spawned.finally = onFinally => handlePromise().finally(onFinally);372 }
55 unmodified lines
modified:readme.md+12 added
50 unmodified lines
51 // Run a shell command52 const {stdout} = await execa.shell('echo unicorns');53 //=> 'unicorns'5455 // Cancelling a spawned process56 const subprocess = execa('node');57 setTimeout(() => { spawned.cancel() }, 1000);58 try {59 await subprocess;60 } catch (error) {61 console.log(subprocess.killed); // true62 console.log(error.isCanceled); // true63 }6465 // Catching an error66 try {67 await execa.shell('exit 3');
50 unmodified lines
118Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) which is enhanced to be a `Promise`.119120It exposes an additional `.all` stream, with `stdout` and `stderr` interleaved.121122It can be canceled with `.cancel` method which throws an error with `error.isCanceled` equal to `true`, provided that the process gets canceled.123Process would not get canceled if it has already exited.124125The promise result is an `Object` with `stdout`, `stderr` and `all` properties.126127### execa.stdout(file, [arguments], [options])128
224 unmodified lines
modified:test.js+54 added
584 unmodified lines
585 }));586 t.is(result.message, 'called');587 });588}589590test('cancel method kills the spawned process', t => {591 const spawned = execa('node');592 spawned.cancel();593 t.true(spawned.killed);594});595596test('result.isCanceled is false when spawned.cancel isn\'t called', async t => {597 const result = await execa('noop');598 t.false(result.isCanceled);599});600601test('calling cancel method throws an error with message "Command was canceled"', async t => {602 const spawned = execa('noop');603 spawned.cancel();604 await t.throwsAsync(spawned, {message: /Command was canceled/});605});606607test('error.isCanceled is true when cancel method is used', async t => {608 const spawned = execa('noop');609 spawned.cancel();610 const error = await t.throwsAsync(spawned);611 t.true(error.isCanceled);612});613614test('error.isCanceled is false when kill method is used', async t => {615 const spawned = execa('noop');616 spawned.kill();617 const error = await t.throwsAsync(spawned);618 t.false(error.isCanceled);619});620621test('calling cancel method twice should show the same behaviour as calling it once', async t => {622 const spawned = execa('noop');623 spawned.cancel();624 spawned.cancel();625 const error = await t.throwsAsync(spawned);626 t.true(error.isCanceled);627 t.true(spawned.killed);628});629630test('calling cancel method on a successfuly completed process does not make result.cancel true', async t => {631 const spawned = execa('noop');632 const result = await spawned;633 spawned.cancel();634 t.false(result.isCanceled);635});636637test('calling cancel method on a process which has been killed does not make error.isCanceled true', async t => {638 const spawned = execa('noop');639 spawned.kill();640 const error = await t.throwsAsync(spawned);641 t.false(error.isCanceled);642});