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
Provenance
- Commit
79356cc- Tree
423bc83- Author
Ammar <binfaisal.ammar@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
dca1504
3 files changed+89 added−6 removed
modified:index.js+23 added-6 removed
141 unmodified lines142 143 function 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;147 148 const [exitCodeName, exitCode] = getCode(result, code);149 150 if (!(error instanceof Error)) {151 const message = [joinedCommand, stderr, stdout].filter(Boolean).join('\n');152 error = new Error(message);153 }154 155- 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}`;157 158 error.code = exitCode || exitCodeName;159 error.exitCode = exitCode;5 unmodified lines165 // it to `undefined`166 error.signal = signal || undefined;167 error.cmd = joinedCommand;168 error.timedOut = Boolean(timedOut);169+ error.isCanceled = isCanceled;170 171 if ('all' in result) {172 error.all = result.all;173 }12 unmodified lines186 187 return [];188 }189 189-function getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode}) {190+function getErrorPrefix({timedOut, timeout, signal, exitCodeName, exitCode, isCanceled}) {191 if (timedOut) {192 return `timed out after ${timeout} milliseconds`;193 }194 195+ if (isCanceled) {196+ return 'was canceled';197+ }198+199 if (signal) {200 return `was killed with ${signal}`;201 }202 42 unmodified lines245 }246 247 let timeoutId;248 let timedOut = false;249+ let isCanceled = false;250 251 const cleanup = () => {252 if (timeoutId !== undefined) {253 clearTimeout(timeoutId);57 unmodified lines311 result.stdout = results[1];312 result.stderr = results[2];313 result.all = results[3];314 309- 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 });322 323 // TODO: missing some timeout logic for killed324 // https://github.com/nodejs/node/blob/master/lib/child_process.js#L20316 unmodified lines341 exitCodeName: 'SUCCESS',342 failed: false,343 killed: false,344 cmd: joinedCommand,338- timedOut: false345+ timedOut: false,346+ isCanceled: false347 };348 }), destroy);349 350 crossSpawn._enoent.hookChildProcess(spawned, parsed.parsed);4 unmodified lines355 356 // 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+ }363 364+ if (spawned.kill()) {365+ isCanceled = true;366+ }367+ };368+369 // TOOD: Remove the `if`-guard when targeting Node.js 10370 if (Promise.prototype.finally) {371 spawned.finally = onFinally => handlePromise().finally(onFinally);372 }55 unmodified linesmodified:readme.md+12 added
50 unmodified lines51 // Run a shell command52 const {stdout} = await execa.shell('echo unicorns');53 //=> 'unicorns'54 55+ // 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+ }64 65 // Catching an error66 try {67 await execa.shell('exit 3');50 unmodified lines118 Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) which is enhanced to be a `Promise`.119 120 It exposes an additional `.all` stream, with `stdout` and `stderr` interleaved.121 122+It can be canceled with `.cancel` method which throws an error with `error.isCanceled` equal to `true`, provided that the process gets canceled.123+Process would not get canceled if it has already exited.124+125 The promise result is an `Object` with `stdout`, `stderr` and `all` properties.126 127 ### execa.stdout(file, [arguments], [options])128 224 unmodified linesmodified:test.js+54 added
584 unmodified lines585 }));586 t.is(result.message, 'called');587 });588 }589+590+test('cancel method kills the spawned process', t => {591+ const spawned = execa('node');592+ spawned.cancel();593+ t.true(spawned.killed);594+});595+596+test('result.isCanceled is false when spawned.cancel isn\'t called', async t => {597+ const result = await execa('noop');598+ t.false(result.isCanceled);599+});600+601+test('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+});606+607+test('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+});613+614+test('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+});620+621+test('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+});629+630+test('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+});636+637+test('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+});