Fix errors, early errors and `result.all` edge cases
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 63ddae6 · Browse files · 15 files·+293 added−21 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+293 added−21 removed
- tests:+227 added−8 removed
- other:+66 added−13 removed
Provenance
- Commit
c4262ff- Tree
f614886- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
63ddae6
15 files changed+293 added−21 removed
modified:docs/errors.md+1 added-1 removed
8 unmodified lines910111213131415161795 unmodified lines8 unmodified lines## Subprocess failure
When the subprocess fails, the promise returned by [`execa()`](api.md#execafile-arguments-options) is rejected with an [`ExecaError`](api.md#execaerror) instance. The `error` has the same shape as successful [results](api.md#result), with a few additional [error-specific fields](api.md#execaerror). [`error.failed`](api.md#resultfailed) is always `true`.
When the subprocess fails to spawn, its output ([`error.stdout`](api.md#resultstdout), [`error.stderr`](api.md#resultstderr), [`error.all`](api.md#resultall) and [`error.stdio`](api.md#resultstdio)) is usually empty. With some errors, it is `undefined` instead.When the subprocess fails to spawn, its output ([`error.stdout`](api.md#resultstdout), [`error.stderr`](api.md#resultstderr), [`error.all`](api.md#resultall) and [`error.stdio`](api.md#resultstdio)) is empty, like when it succeeds without printing anything.
```jsimport {execa, ExecaError} from 'execa';
95 unmodified linesmodified:lib/methods/main-sync.js+7 added-1 removed
1 import {spawnSync} from 'node:child_process';2 import {handleCommand} from '../arguments/command.js';3 import {normalizeOptions} from '../arguments/options.js';4 import {concatenateShell} from '../arguments/shell.js';5-import {makeError, makeEarlyError, makeSuccessResult} from '../return/result.js';5+import {6+ makeError,7+ makeEarlyError,8+ makeSuccessResult,9+ getEarlyErrorOutput,10+} from '../return/result.js';11 import {handleResult} from '../return/reject.js';12 import {handleStdioSync} from '../stdio/handle-sync.js';13 import {stripNewline} from '../io/strip-newline.js';14 import {addInputOptionsSync} from '../io/input-sync.js';121 unmodified lines136 fileDescriptors,137 options,138 startTime,139 isSync: true,140+ ...getEarlyErrorOutput(fileDescriptors, options),141 });142 }143 };144 31 unmodified linesmodified:lib/resolve/all-sync.js+14 added-3 removed
1234523 unmodified lines29303132323334353436373837394041424344454647484950515253542 unmodified linesimport {Buffer} from 'node:buffer';import {isUint8Array, concatUint8Arrays} from '../utils/uint-array.js';import {splitLinesSync} from '../transform/split.js';import {getStripFinalNewline} from '../io/strip-newline.js';
23 unmodified lines if (hasLines(options)) { return [splitAllLines(stdout, allFds, options), splitAllLines(stderr, allFds, options)].flat(); }
// Without the `lines` option, arrays can only come from object mode, which does not apply to the other file descriptor // Without the `lines` option, arrays can only come from object mode, which does not apply to the other file descriptor. // Like asynchronous methods, that other file descriptor is omitted when it is empty. if (Array.isArray(stdout) || Array.isArray(stderr)) { return [stdout, stderr].flat(); return [stdout, stderr].filter(value => value.length > 0).flat(); }
return isUint8Array(stdout) && isUint8Array(stderr) ? concatUint8Arrays([stdout, stderr]) : `${stdout}${stderr}`; if (isUint8Array(stdout) && isUint8Array(stderr)) { return concatUint8Arrays([stdout, stderr]); }
return BASE64_ENCODINGS.has(options.encoding) ? concatBase64(stdout, stderr, options.encoding) : `${stdout}${stderr}`;};
// Unlike other encodings, base64 strings cannot be concatenated, since the first one might end with paddingconst concatBase64 = (stdout, stderr, encoding) => Buffer.concat([Buffer.from(stdout, encoding), Buffer.from(stderr, encoding)]).toString(encoding);
const BASE64_ENCODINGS = new Set(['base64', 'base64url']);
const hasLines = ({lines}) => Boolean(lines[1] || lines[2]);
// Each file descriptor is either already split into lines, or is a string which still needs to be splitconst splitAllLines = (value, allFds, options) => value === undefined || Array.isArray(value) || !hasLines(options)2 unmodified linesmodified:lib/return/early-error.js+5 added-1 removed
5 unmodified lines6 Writable,7 Duplex,8 } from 'node:stream';9 import {cleanupCustomStreams} from '../stdio/handle.js';10-import {makeEarlyError} from './result.js';10+import {makeEarlyError, getEarlyErrorOutput} from './result.js';11 import {handleResult} from './reject.js';12 13 // When the subprocess fails to spawn.14 // We ensure the returned error is always both a promise and a subprocess.38 unmodified lines53 });54 return all;55 };56 57+// Writing to an ended stream emits an error, which would crash the current process when the user writes to `subprocess.stdin`.58+// Like when the subprocess exits before reading its input, that input is discarded instead.59 const createDummyStream = () => {60 const stream = new PassThrough();61+ stream.on('error', () => {});62 stream.end();63 return stream;64 };65 45 unmodified lines111 fileDescriptors,112 options,113 startTime,114 isSync: false,115+ ...getEarlyErrorOutput(fileDescriptors, options),116 });117 return handleResult(earlyError, verboseInfo, options);118 };modified:lib/return/final-error.js+2 added-1 removed
30 unmodified lines31 export const isExecaError = error => isErrorInstance(error) && execaErrorSymbol in error;32 33 const execaErrorSymbol = Symbol('isExecaError');34 35+// `instanceof` handles `DOMException` and subclasses with a custom `Symbol.toStringTag`, `Object.prototype.toString()` handles other realms35-export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';36+export const isErrorInstance = value => value instanceof Error || Object.prototype.toString.call(value) === '[object Error]';37 38 // We use two different Error classes for async/sync methods since they have slightly different shape and types39 export class ExecaError extends Error {}40 // eslint-disable-next-line unicorn/no-top-level-side-effects -- `error.name` must be set as soon as the class is defined5 unmodified linesmodified:lib/return/message.js+10 added-3 removed
26 unmodified lines27 maxBuffer,28 timeout,29 cwd,30 }) => {31- const errorCode = originalError?.code;31+ const errorCode = getErrorCode(originalError);32 const prefix = getErrorPrefix({33 originalError,34 timedOut,35 timeout,24 unmodified lines60 .join('\n\n');61 return {originalMessage, shortMessage, message};62 };63 64+// `DOMException`, e.g. the default `cancelSignal` reason, has a legacy numeric `code`, which is not an error code like `ENOENT`65+export const getErrorCode = error => typeof error?.code === 'string' ? error.code : undefined;66+67 const getErrorPrefix = ({68 originalError,69 timedOut,70 timeout,56 unmodified lines127 if (originalError instanceof DiscardedError) {128 return;129 }130 131+ // An `ExecaError` has no `originalMessage` when it was not caused by another error, e.g. with a non-zero exit code132 const originalMessage = isExecaError(originalError)129- ? originalError.originalMessage133+ ? originalError.originalMessage ?? ''134 : String(originalError?.message ?? originalError);135 const escapedOriginalMessage = escapeLines(fixCwdError(originalMessage, cwd));136 return escapedOriginalMessage === '' ? undefined : escapedOriginalMessage;137 };1 unmodified line139 const serializeIpcMessage = ipcMessage => typeof ipcMessage === 'string'140 ? ipcMessage141 : inspect(ipcMessage);142 143+// With the `lines` option, empty lines are kept. Only objects are omitted.144 const serializeMessagePart = messagePart => Array.isArray(messagePart)140- ? messagePart.map(messageItem => stripFinalNewline(serializeMessageItem(messageItem))).filter(Boolean).join('\n')145+ ? messagePart.filter(messageItem => isTextItem(messageItem)).map(messageItem => stripFinalNewline(serializeMessageItem(messageItem))).join('\n')146 : serializeMessageItem(messagePart);147 148+const isTextItem = messageItem => typeof messageItem === 'string' || isUint8Array(messageItem);149+150 const serializeMessageItem = messageItem => {151 if (typeof messageItem === 'string') {152 return messageItem;153 }3 unmodified linesmodified:lib/return/result.js+27 added-3 removed
1 import {getSignalDescription} from '../terminate/signal.js';2+import {getAllSync, getAllSyncFds} from '../resolve/all-sync.js';3 import {getDurationMs} from './duration.js';4 import {getFinalError} from './final-error.js';4-import {createMessages} from './message.js';5+import {createMessages, getErrorCode} from './message.js';6 7 // Object returned on subprocess success8 export const makeSuccessResult = ({9 command,32 unmodified lines42 fileDescriptors,43 options,44 startTime,45 isSync,46+ stdio = Array.from({length: fileDescriptors.length}),47+ all,48 }) => makeError({49 error,50 command,51 escapedCommand,2 unmodified lines54 isCanceled: false,55 isGracefullyCanceled: false,56 isMaxBuffer: false,57 isForcefullyTerminated: false,55- stdio: Array.from({length: fileDescriptors.length}),58+ stdio,59+ all,60 ipcOutput: [],61 options,62 isSync,63 });64 65+// When the subprocess fails to spawn, its output is empty, with the same shape as when it spawns but prints nothing66+export const getEarlyErrorOutput = (fileDescriptors, options) => {67+ const stdio = fileDescriptors.map((fileDescriptor, fdNumber) => getEmptyOutput(fileDescriptor, fdNumber, options));68+ return {stdio, all: getAllSync(stdio, getAllSyncFds(stdio), options)};69+};70+71+const getEmptyOutput = ({direction, objectMode}, fdNumber, {stdio, buffer, lines, encoding}) => {72+ if (direction === 'input' || !PIPED_STDIO.has(stdio[fdNumber]) || !buffer[fdNumber]) {73+ return;74+ }75+76+ if (objectMode || lines[fdNumber]) {77+ return [];78+ }79+80+ return encoding === 'buffer' ? new Uint8Array() : '';81+};82+83+const PIPED_STDIO = new Set(['pipe', 'overlapped']);84+85 // Object returned on subprocess failure86 export const makeError = ({87 error: originalError,88 command,99 unmodified lines188 isForcefullyTerminated,189 exitCode,190 signal,191 signalDescription,168- code: error.cause?.code,192+ code: getErrorCode(error.cause),193 stdout: stdio[1],194 stderr: stdio[2],195 all,196 stdio,14 unmodified linesmodified:test/resolve/all.js+42 added-1 removed
1+import {Buffer} from 'node:buffer';2 import assert from 'node:assert/strict';3 import test from 'node:test';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {defaultHighWaterMark} from '../helpers/stream.js';6-import {foobarString} from '../helpers/input.js';7+import {foobarString, foobarObject} from '../helpers/input.js';8+import {outputObjectGenerator} from '../helpers/generator.js';9 10 setFixtureDirectory();11 12 const textEncoder = new TextEncoder();18 unmodified lines31 assert.equal(exitCode, isFailure ? 1 : 0);32 assert.deepEqual(all, expectedOutput);33 };34 35+// With encodings like base64, the bytes must be merged before being encoded, otherwise the padding of the first output would end up in the middle36+const testAllBinaryEncoding = (encoding, execaMethod) => testAllBoth(Buffer.from(doubleFoobarStringFull).toString(encoding), encoding, false, false, false, execaMethod);37+38+test('result.all is defined, encoding "base64"', () => testAllBinaryEncoding('base64', execa));39+test('result.all is defined, encoding "base64url"', () => testAllBinaryEncoding('base64url', execa));40+test('result.all is defined, encoding "hex"', () => testAllBinaryEncoding('hex', execa));41+test('result.all is defined, encoding "latin1"', () => testAllBinaryEncoding('latin1', execa));42+test('result.all is defined, encoding "base64", sync', () => testAllBinaryEncoding('base64', execaSync));43+test('result.all is defined, encoding "base64url", sync', () => testAllBinaryEncoding('base64url', execaSync));44+test('result.all is defined, encoding "hex", sync', () => testAllBinaryEncoding('hex', execaSync));45+test('result.all is defined, encoding "latin1", sync', () => testAllBinaryEncoding('latin1', execaSync));46+47+// An empty output is not interleaved with the objects of the other file descriptor48+const testAllObjectModeEmpty = async (fixtureName, commandArguments, options, expectedAll) => {49+ const {all} = await execa(fixtureName, commandArguments, {...options, all: true});50+ assert.deepEqual(all, expectedAll);51+ const {all: allSync} = execaSync(fixtureName, commandArguments, {...options, all: true});52+ assert.deepEqual(allSync, expectedAll);53+};54+55+test('result.all omits empty stderr with objectMode stdout', () => testAllObjectModeEmpty('noop.js', [foobarString], {stdout: outputObjectGenerator()}, [foobarObject]));56+test('result.all omits empty stdout with objectMode stderr', () => testAllObjectModeEmpty('noop-fd.js', ['2', foobarString], {stderr: outputObjectGenerator()}, [foobarObject]));57+test('result.all omits empty stderr with objectMode stdout, encoding "buffer"', () => testAllObjectModeEmpty('noop.js', [foobarString], {stdout: outputObjectGenerator(), encoding: 'buffer'}, [foobarObject]));58+test('result.all keeps non-empty stderr with objectMode stdout', () => testAllObjectModeEmpty('noop-both.js', [foobarString], {stdout: outputObjectGenerator()}, [foobarObject, `${foobarString}\n`]));59+60 const fdOne = {stderr: true};61 const fdBoth = {stdout: true, stderr: true};62 63 test('result.all is defined', () => testAllBoth(doubleFoobarStringFull, 'utf8', false, false, false, execa));203 unmodified lines267 test('result.all is undefined when no file descriptor is buffered', () => testAllNoFd(false, execa));268 test('result.all is undefined when no file descriptor is buffered, lines', () => testAllNoFd(true, execa));269 test('result.all is undefined when no file descriptor is buffered, sync', () => testAllNoFd(false, execaSync));270 test('result.all is undefined when no file descriptor is buffered, lines, sync', () => testAllNoFd(true, execaSync));271+272+const testUtf16LinesAll = async execaMethod => {273+ const script = 'process.stdout.write(Buffer.from(\'a\\r\\nb\\n\', \'utf16le\')); process.stderr.write(Buffer.from(\'c\\n\', \'utf16le\'))';274+ const {all} = await execaMethod('node', ['-e', script], {275+ all: true,276+ lines: true,277+ encoding: 'utf16le',278+ stripFinalNewline: false,279+ });280+ assert.deepEqual(all, ['a\r\n', 'b\n', 'c\n']);281+};282+283+test('result.all splits lines with utf16le encoding', () => testUtf16LinesAll(execa));284+test('result.all splits lines with utf16le encoding, sync', () => testUtf16LinesAll(execaSync));modified:test/return/early-error.js+62 added-1 removed
1 unmodified line2 import {arch} from 'node:os';3 import process from 'node:process';4 import {once} from 'node:events';5 import {finished} from 'node:stream/promises';6+import {setImmediate} from 'node:timers/promises';7 import test from 'node:test';8 import {assertThrows, assertRejects} from '../helpers/assert.js';9 import {10 execa,4 unmodified lines15 } from '../../index.js';16 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';17 import {foobarString, foobarUint8Array} from '../helpers/input.js';18 import {fullStdio} from '../helpers/stdio.js';18-import {getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';19+import {getOutputGenerator, convertTransformToFinal, noopGenerator} from '../helpers/generator.js';20 import {21 earlyErrorOptions,22 getEarlyErrorSubprocess,23 getEarlyErrorSubprocessSync,39 unmodified lines63 test('execaSync() output is undefined when the command does not exist, with buffer: false', () => testSpawnFailureOutput({buffer: false}));64 test('execaSync() output is empty when the cwd does not exist', () => testSpawnFailureOutput({cwd: '/nonexistent-directory-for-execa'}));65 test('execaSync() output runs the final of transforms when the command does not exist', () => testSpawnFailureOutput({stdout: convertTransformToFinal(getOutputGenerator(foobarString)(), true)}));66 67+// When `child_process.spawn()` throws, the output must be the same as when the subprocess spawns and fails right away68+const testEarlyErrorOutput = async options => {69+ const {stdio, all} = await execa('nonexistent-command-for-execa', {...options, reject: false});70+ const earlyError = await getEarlyErrorSubprocess({...options, reject: false});71+ assert.deepEqual(earlyError.stdio, stdio);72+ assert.deepEqual(earlyError.all, all);73+ assert.deepEqual(earlyError.stdout, stdio[1]);74+ assert.deepEqual(earlyError.stderr, stdio[2]);75+ const earlyErrorSync = getEarlyErrorSubprocessSync({...options, reject: false});76+ assert.deepEqual(earlyErrorSync.stdio, stdio);77+ assert.deepEqual(earlyErrorSync.all, all);78+};79+80+test('Early errors output is empty', () => testEarlyErrorOutput({}));81+test('Early errors output is empty, with encoding: buffer', () => testEarlyErrorOutput({encoding: 'buffer'}));82+test('Early errors output is empty, with encoding: hex', () => testEarlyErrorOutput({encoding: 'hex'}));83+test('Early errors output is empty, with lines: true', () => testEarlyErrorOutput({lines: true}));84+test('Early errors output is empty, with lines: true and encoding: buffer', () => testEarlyErrorOutput({lines: true, encoding: 'buffer'}));85+test('Early errors output is empty, with all: true', () => testEarlyErrorOutput({all: true}));86+test('Early errors output is empty, with all: true and lines: true', () => testEarlyErrorOutput({all: true, lines: true}));87+test('Early errors output is empty, with all: true and encoding: buffer', () => testEarlyErrorOutput({all: true, encoding: 'buffer'}));88+test('Early errors output is empty, with an additional file descriptor', () => testEarlyErrorOutput(fullStdio));89+test('Early errors output is empty, with an object mode transform', () => testEarlyErrorOutput({stdout: noopGenerator(true)}));90+test('Early errors output is empty, with an object mode transform and all: true', () => testEarlyErrorOutput({stdout: noopGenerator(true), all: true}));91+test('Early errors output is undefined, with stdout: ignore', () => testEarlyErrorOutput({stdout: 'ignore'}));92+test('Early errors output is undefined, with stdout: inherit', () => testEarlyErrorOutput({stdout: 'inherit', all: true}));93+test('Early errors output is undefined, with buffer: false', () => testEarlyErrorOutput({buffer: false}));94+test('Early errors output is undefined, with buffer.stdout: false', () => testEarlyErrorOutput({buffer: {stdout: false}, all: true}));95+96+test('Early errors output is empty, with inputFile, sync', () => {97+ const {stdout, stderr, stdio} = execaSync('stdin.js', {inputFile: 'does_not_exist', reject: false});98+ assert.equal(stdout, '');99+ assert.equal(stderr, '');100+ assert.deepEqual(stdio, [undefined, '', '']);101+});102+103 const testEarlyErrorShape = async reject => {104 const subprocess = getEarlyErrorSubprocess({reject});105 assert.doesNotThrow(() => {106 subprocess.catch(() => {});215 unmodified lines322 test('child_process.spawn() early errors can use .stdio[1]', () => testEarlyErrorStream(({stdio}) => stdio[1]));323 test('child_process.spawn() early errors can use .stdio[3]', () => testEarlyErrorStream(({stdio}) => stdio[3], fullStdio));324 test('child_process.spawn() early errors can use .all', () => testEarlyErrorStream(({all}) => all, {all: true}));325 326+// The subprocess never spawned, so the input is discarded, like when the subprocess exits before reading it327+const testEarlyErrorWrite = async (getStreamProperty, options) => {328+ const subprocess = getEarlyErrorSubprocess(options);329+ const stream = getStreamProperty(subprocess);330+ stream.write(foobarString);331+ stream.end(foobarString);332+ await assertRejects(subprocess, expectedEarlyError);333+ // Write errors are emitted asynchronously334+ await setImmediate();335+};336+337+test('child_process.spawn() early errors can write to .stdin', () => testEarlyErrorWrite(({stdin}) => stdin));338+test('child_process.spawn() early errors can write to .stdio[0]', () => testEarlyErrorWrite(({stdio}) => stdio[0]));339+test('child_process.spawn() early errors can write to .stdio[3]', () => testEarlyErrorWrite(({stdio}) => stdio[3], {stdio: ['pipe', 'pipe', 'pipe', {value: 'pipe', input: true}]}));340+341+test('child_process.spawn() early errors call the .stdin write callback', async () => {342+ const subprocess = getEarlyErrorSubprocess();343+ const {promise, resolve} = Promise.withResolvers();344+ subprocess.stdin.write(foobarString, resolve);345+ const error = await promise;346+ assert.equal(error.code, 'ERR_STREAM_WRITE_AFTER_END');347+ await assertRejects(subprocess, expectedEarlyError);348+});349+350 // Reading the `inputFile` happens after the file descriptors are set up, so a missing file is reported as an early error, like with asynchronous methods351 test('inputFile which does not exist is an early error', async () => {352 const error = await assertRejects(execa('stdin.js', {inputFile: 'does_not_exist'}));353 assert.ok(error instanceof ExecaError);10 unmodified linesmodified:test/return/final-error.js+49 added
108 unmodified lines109 assert.equal(error.signal, 'SIGTERM');110 assert.equal(error.cause, cause);111 });112 113+// An `ExecaError` from a non-zero exit code has no `error.originalMessage`114+test('error.cause can be an ExecaError without originalMessage, with .kill(error)', async () => {115+ const previousError = await assertRejects(execa('fail.js'));116+ assert.equal(previousError.originalMessage, undefined);117+ const subprocess = execa('forever.js');118+ subprocess.kill(previousError);119+ const error = await assertRejects(subprocess);120+ assert.equal(error.cause, previousError);121+ assert.equal(error.isTerminated, true);122+ assert.equal(error.originalMessage, undefined);123+ assert.equal(error.shortMessage, 'Command was killed with SIGTERM (Termination): forever.js');124+});125+126+test('error.cause can be an ExecaError without originalMessage, with cancelSignal', async () => {127+ const previousError = await assertRejects(execa('fail.js'));128+ const controller = new AbortController();129+ const subprocess = execa('forever.js', {cancelSignal: controller.signal});130+ controller.abort(previousError);131+ const error = await assertRejects(subprocess);132+ assert.equal(error.cause, previousError);133+ assert.equal(error.isCanceled, true);134+ assert.equal(error.originalMessage, undefined);135+ assert.equal(error.shortMessage, 'Command was canceled: forever.js');136+});137+138+const testExecaErrorTransform = async execaMethod => {139+ const transform = function * (line) {140+ execaSync('fail.js');141+ yield line;142+ };143+144+ const error = await execaMethod('noop.js', [foobarString], {stdout: transform, reject: false});145+ assert.ok(error.cause instanceof ExecaSyncError);146+ assert.equal(error.originalMessage, undefined);147+ assert.ok(error.shortMessage.endsWith(`: noop.js ${foobarString}`));148+};149+150+test('error.cause can be an ExecaError without originalMessage, thrown by a transform', () => testExecaErrorTransform(execa));151+test('error.cause can be an ExecaError without originalMessage, thrown by a transform, sync', () => testExecaErrorTransform(execaSync));152+153+test('error.code is not set to the numeric code of the default cancelSignal reason', async () => {154+ const controller = new AbortController();155+ const subprocess = execa('forever.js', {cancelSignal: controller.signal});156+ controller.abort();157+ const error = await assertRejects(subprocess);158+ assert.equal(error.cause.name, 'AbortError');159+ assert.equal(error.code, undefined);160+});161+162 test('error.cause is not set if error.isTerminated with .kill(error)', async () => {163 const subprocess = execa('forever.js');164 const error = new Error('test');165 subprocess.kill(error);50 unmodified linesmodified:test/return/message.js+15 added
61 unmodified lines62 test('error.message handles "lines: true", stripFinalNewline, sync', () => testLinesMessage('utf8', true, execaSync));63 test('error.message handles "lines: true", buffer, sync', () => testLinesMessage('buffer', false, execaSync));64 test('error.message handles "lines: true", buffer, stripFinalNewline, sync', () => testLinesMessage('buffer', true, execaSync));65 66+// `lines: true` must not change `error.message`, including its empty lines67+const testLinesMessageEmptyLines = async (output, stripFinalNewline, execaMethod) => {68+ const options = {stripFinalNewline, reject: false};69+ const {message} = await execaMethod('noop-fail.js', ['1', output], options);70+ const {message: linesMessage} = await execaMethod('noop-fail.js', ['1', output], {...options, lines: true});71+ assert.equal(linesMessage, message);72+};73+74+test('error.message keeps empty lines with "lines: true"', () => testLinesMessageEmptyLines(`${foobarString}\n\n${foobarString}\n`, true, execa));75+test('error.message keeps empty lines with "lines: true", stripFinalNewline false', () => testLinesMessageEmptyLines(`${foobarString}\n\n${foobarString}\n`, false, execa));76+test('error.message keeps several empty lines with "lines: true"', () => testLinesMessageEmptyLines(`${foobarString}\n\n\n\n${foobarString}`, true, execa));77+test('error.message keeps leading empty lines with "lines: true"', () => testLinesMessageEmptyLines(`\n\n${foobarString}`, true, execa));78+test('error.message keeps empty lines with "lines: true", sync', () => testLinesMessageEmptyLines(`${foobarString}\n\n${foobarString}\n`, true, execaSync));79+test('error.message keeps empty lines with "lines: true", stripFinalNewline false, sync', () => testLinesMessageEmptyLines(`${foobarString}\n\n${foobarString}\n`, false, execaSync));80+81 const testPartialIgnoreMessage = async (fdNumber, stdioOption, output) => {82 const {message} = await assertRejects(execa('echo-fail.js', getStdio(fdNumber, stdioOption, 4)));83 assert.ok(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));84 };51 unmodified linesmodified:test/return/output.js+5 added-4 removed
89 unmodified lines90 const {stdio} = await assertRejects(execa('fail.js', {input: 'test'}));91 assert.equal(stdio[0], undefined);92 });93 94+// The subprocess never spawned, so its output is empty95 const validateSpawnErrorStdio = ({stdout, stderr, stdio, all}) => {95- assert.equal(stdout, undefined);96- assert.equal(stderr, undefined);97- assert.equal(all, undefined);98- assert.deepEqual(stdio, [undefined, undefined, undefined]);96+ assert.equal(stdout, '');97+ assert.equal(stderr, '');98+ assert.equal(all, '');99+ assert.deepEqual(stdio, [undefined, '', '']);100 };101 102 test('stdout/stderr/all/stdio on subprocess spawning errors', async () => {103 const error = await assertRejects(getEarlyErrorSubprocess({all: true}));35 unmodified linesmodified:test/stdio/lines-main.js+5 added
106 unmodified lines107 const error = await assertRejects(subprocess);108 assert.equal(error.cause, cause);109 assert.deepEqual(error.stdout, []);110 });111+112+test('"lines: true" keeps the trailing carriage return of an unterminated final line', () => testStreamLines(1, 'a\r\nb\r', ['a', 'b\r'], true, true, execa));113+test('"lines: true" keeps the trailing carriage return of an unterminated final line, sync', () => testStreamLines(1, 'a\r\nb\r', ['a', 'b\r'], true, true, execaSync));114+test('"lines: true" keeps newlines of an unterminated final line', () => testStreamLines(1, 'a\r\nb\r', ['a\r\n', 'b\r'], true, false, execa));115+test('"lines: true" keeps newlines of an unterminated final line, sync', () => testStreamLines(1, 'a\r\nb\r', ['a\r\n', 'b\r'], true, false, execaSync));modified:test/terminate/kill-error.js+46 added
4 unmodified lines5 import isRunning from 'is-running';6 import {assertRejects} from '../helpers/assert.js';7 import {execa} from '../../index.js';8 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9+import {foobarString} from '../helpers/input.js';10 11 setFixtureDirectory();12 13 test('.kill(error) propagates error', async () => {29 unmodified lines43 assert.equal(error.cause, cause);44 assert.equal(error.signal, 'SIGINT');45 });46 47+// Their `Object.prototype.toString()` is not `[object Error]`48+class TaggedError extends Error {49+ get [Symbol.toStringTag]() {50+ return 'TaggedError';51+ }52+}53+54+const testKillErrorSubclass = async cause => {55+ const subprocess = execa('forever.js');56+ assert.ok(subprocess.kill(cause));57+ const error = await assertRejects(subprocess);58+ assert.equal(error.cause, cause);59+ assert.equal(error.signal, 'SIGTERM');60+ assert.equal(error.originalMessage, cause.message);61+ assert.ok(error.shortMessage.startsWith('Command was killed with SIGTERM'));62+ return error;63+};64+65+test('.kill(error) works with DOMException', async () => {66+ const error = await testKillErrorSubclass(AbortSignal.abort().reason);67+ // `DOMException` has a legacy numeric `code`, which is not an error code like `ENOENT`68+ assert.equal(error.code, undefined);69+});70+71+test('.kill(error) works with Error subclasses with a custom Symbol.toStringTag', () => testKillErrorSubclass(new TaggedError('test')));72+73+test('.kill(error) ignores numeric error codes', async () => {74+ const error = await testKillErrorSubclass(Object.assign(new Error('test'), {code: 42}));75+ assert.equal(error.code, undefined);76+ assert.ok(!error.shortMessage.includes('42'));77+});78+79+test('.kill(error) keeps string error codes', async () => {80+ const subprocess = execa('forever.js');81+ subprocess.kill(Object.assign(new Error('test'), {code: 'ECUSTOM'}));82+ const error = await assertRejects(subprocess);83+ assert.equal(error.code, 'ECUSTOM');84+});85+86 test('.kill(error) is a noop if subprocess already exited', async () => {87 const subprocess = execa('empty.js');88 await subprocess;89 assert.ok(!isRunning(subprocess.pid));32 unmodified lines122 subprocess.kill(cause);123 const error = await Promise.race([assertRejects(subprocess), once(subprocess.nodeChildProcess, 'error')]);124 assert.equal(error.cause, cause);125 });126+127+test('.kill(error) returns false once the subprocess has settled', async () => {128+ const subprocess = execa('noop.js', [foobarString]);129+ await subprocess;130+ assert.ok(!subprocess.kill(new Error('test')));131+});modified:test/verbose/custom-result.js+3 added-2 removed
42 unmodified lines43 const result = JSON.parse(lastLine);44 assertLike(result, expectedOutput);45 assert.equal(result.failed, true);46 assert.equal(result.exitCode, undefined);47- assert.equal(result.stdout, undefined);48- assert.equal(result.stderr, undefined);47+ // The subprocess never spawned, so its output is empty48+ assert.equal(result.stdout, '');49+ assert.equal(result.stderr, '');50 assert.equal(typeof result.durationMs, 'number');51 assert.deepEqual(result.ipcOutput, []);52 };53 25 unmodified lines