Add `result.stdio` and `error.stdio` (#676)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 698fbda · Browse files · 38 files·+1013 added−823 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
38 files+1013 added−823 removed
- tests:+925 added−757 removed
- other:+88 added−66 removed
Provenance
- Commit
62a5207- Tree
f701550- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
698fbda
38 files changed+1013 added−823 removed
modified:lib/stdio/handle.js+1 added-1 removed
11 unmodified lines1213141516161718192078 unmodified lines11 unmodified lines .map(stdioStreams => validateStreams(stdioStreams)) .map(stdioStreams => addStreamDirection(stdioStreams)) .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties)); options.stdio = transformStdio(stdioStreamsGroups); return stdioStreamsGroups.flat(); return {stdioStreams: stdioStreamsGroups.flat(), stdioLength: stdioStreamsGroups.length};};
// We make sure passing an array with a single item behaves the same as passing that item without an array.// This is what users would expect.78 unmodified linesmodified:lib/stdio/sync.js+2 added-2 removed
4 unmodified lines5678991011111213141562 unmodified lines4 unmodified linesimport {bufferToUint8Array} from './utils.js';
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync modeexport const handleInputSync = options => { const stdioStreams = handleInput(addPropertiesSync, options); const {stdioStreams, stdioLength} = handleInput(addPropertiesSync, options); addInputOptionSync(stdioStreams, options); return stdioStreams; return {stdioStreams, stdioLength};};
const forbiddenIfStreamSync = ({value, optionName}) => { if (isNodeStream(value)) {62 unmodified linesmodified:lib/error.js+7 added-5 removed
24 unmodified lines25 return 'failed';26 };27 28 export const makeError = ({29- stdout,30- stderr,29+ stdio,30 all,31 error,32 signal,33 exitCode,2 unmodified lines36 timedOut,37 isCanceled,38 options: {timeout, cwd = process.cwd()},39 }) => {40+ stdio = stdio.map(stdioOutput => stdioOutput ?? '');41+42 // `signal` and `exitCode` emitted on `spawned.on('exit')` event can be `null`.43 // We normalize them to `undefined`44 exitCode = exitCode === null ? undefined : exitCode;45 signal = signal === null ? undefined : signal;4 unmodified lines50 const prefix = getErrorPrefix({timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled});51 const execaMessage = `Command ${prefix}: ${command}`;52 const isError = Object.prototype.toString.call(error) === '[object Error]';53 const shortMessage = isError ? `${execaMessage}\n${error.message}` : execaMessage;53- const message = [shortMessage, stderr, stdout].filter(Boolean).join('\n');54+ const message = [shortMessage, stdio[2], stdio[1], ...stdio.slice(3)].filter(Boolean).join('\n');55 56 if (isError) {57 error.originalMessage = error.message;58 error.message = message;6 unmodified lines65 error.escapedCommand = escapedCommand;66 error.exitCode = exitCode;67 error.signal = signal;68 error.signalDescription = signalDescription;68- error.stdout = stdout;69- error.stderr = stderr;69+ error.stdio = stdio;70+ error.stdout = stdio[1];71+ error.stderr = stdio[2];72 error.cwd = cwd;73 74 if (all !== undefined) {75 error.all = all;13 unmodified linesmodified:lib/stream.js+8 added-6 removed
33 unmodified lines34 return error.bufferedData === undefined ? undefined : applyEncoding(error.bufferedData, encoding);35 }36 };37 38+const getStdioPromise = ({stream, index, stdioStreams, encoding, buffer, maxBuffer}) => {39+ const stdioStream = stdioStreams.find(stdioStream => stdioStream.index === index);40+ return stdioStream?.direction === 'output' ? getStreamPromise(stream, {encoding, buffer, maxBuffer}) : undefined;41+};42+43 const getStreamPromise = async (stream, {encoding, buffer, maxBuffer}) => {44 if (!stream || !buffer) {45 return;46 }69 unmodified lines116 const finalizers = [];117 cleanupOnExit(spawned, cleanup, detached, finalizers);118 const customStreams = getCustomStreams(stdioStreams);119 115- const stdoutPromise = getStreamPromise(spawned.stdout, {encoding, buffer, maxBuffer});116- const stderrPromise = getStreamPromise(spawned.stderr, {encoding, buffer, maxBuffer});120+ const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, index, stdioStreams, encoding, buffer, maxBuffer}));121 const allPromise = getStreamPromise(spawned.all, {encoding, buffer, maxBuffer: maxBuffer * 2});122 123 try {124 return await Promise.race([125 Promise.all([126 once(spawned, 'exit'),123- stdoutPromise,124- stderrPromise,127+ Promise.all(stdioPromises),128 allPromise,129 ...waitForCustomStreamsEnd(customStreams),130 ]),131 ...throwOnCustomStreamsError(customStreams),3 unmodified lines135 } catch (error) {136 spawned.kill();137 const results = await Promise.all([138 [undefined, context.signal, error],136- getBufferedData(stdoutPromise, encoding),137- getBufferedData(stderrPromise, encoding),139+ Promise.all(stdioPromises.map(stdioPromise => getBufferedData(stdioPromise, encoding))),140 getBufferedData(allPromise, encoding),141 ]);142 cleanupStdioStreams(customStreams, error);143 return results;6 unmodified linesmodified:test/fixtures/echo-fail.js+2 added
12345678#!/usr/bin/env nodeimport process from 'node:process';import {writeSync} from 'node:fs';
console.log('stdout');console.error('stderr');writeSync(3, 'fd3');process.exit(1);modified:test/fixtures/max-buffer.js+10 added-4 removed
123445675678910111213#!/usr/bin/env nodeimport process from 'node:process';import {writeSync} from 'node:fs';
const output = process.argv[2] || 'stdout';const bytes = Number(process.argv[3] || 1e7);
process[output].write('.'.repeat(bytes - 1) + '\n');const index = Number(process.argv[2]);const bytes = '.'.repeat(Number(process.argv[3] || 1e7));if (index === 1) { process.stdout.write(bytes);} else if (index === 2) { process.stderr.write(bytes);} else { writeSync(index, bytes);}modified:test/fixtures/nested-multiple-stderr.js+1 added-1 removed
1 unmodified line2 import process from 'node:process';3 import {execa} from '../../index.js';4 5 const [options] = process.argv.slice(2);6-const result = await execa('noop-err.js', ['foobar'], {stderr: JSON.parse(options)});6+const result = await execa('noop-fd.js', ['2', 'foobar'], {stderr: JSON.parse(options)});7 process.stdout.write(`nested ${result.stderr}`);modified:test/fixtures/nested-stdio.js+1 added-1 removed
8 unmodified lines9 ? [process[optionValue[0]], ...optionValue.slice(1)]10 : optionValue;11 const stdio = ['ignore', 'inherit', 'inherit'];12 stdio[index] = optionValue;13-const childProcess = execa(file, args, {stdio});13+const childProcess = execa(file, [`${index}`, ...args], {stdio});14 15 const shouldPipe = Array.isArray(optionValue) && optionValue.includes('pipe');16 const hasPipe = childProcess.stdio[index] !== null;17 9 unmodified linesmodified:test/fixtures/noop-delay.js+3 added-2 removed
1 #!/usr/bin/env node2 import process from 'node:process';3+import {writeSync} from 'node:fs';4 import {setTimeout} from 'node:timers/promises';5 5-console.log(process.argv[2]);6-await setTimeout((Number(process.argv[3]) || 1) * 1e3);6+writeSync(Number(process.argv[2]), 'foobar');7+await setTimeout(100);deleted:test/fixtures/noop-err.js-4 removed
1-#!/usr/bin/env node2-import process from 'node:process';3-4-console.error(process.argv[2]);modified:test/fixtures/noop-fail.js+2 added-1 removed
1 #!/usr/bin/env node2 import process from 'node:process';3+import {writeSync} from 'node:fs';4 4-console.log(process.argv[2]);5+writeSync(Number(process.argv[2]), 'foobar');6 process.exit(2);added:test/fixtures/noop-fd.js+5 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {writeSync} from 'node:fs';4+5+writeSync(Number(process.argv[2]), process.argv[3] || 'foobar');deleted:test/fixtures/noop-fd3.js-6 removed
1-#!/usr/bin/env node2-import process from 'node:process';3-import {writeSync} from 'node:fs';4-5-const fileDescriptorIndex = Number(process.argv[3] || 3);6-writeSync(fileDescriptorIndex, `${process.argv[2]}\n`);deleted:test/fixtures/noop-no-newline.js-4 removed
1-#!/usr/bin/env node2-import process from 'node:process';3-4-process.stdout.write(process.argv[2]);deleted:test/fixtures/noop-throw.js-5 removed
1-#!/usr/bin/env node2-import process from 'node:process';3-4-console.error(process.argv[2]);5-process.exit(2);added:test/fixtures/stdin-fd.js+10 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {readFileSync} from 'node:fs';4+5+const fileDescriptorIndex = Number(process.argv[2]);6+if (fileDescriptorIndex === 0) {7+ process.stdin.pipe(process.stdout);8+} else {9+ process.stdout.write(readFileSync(fileDescriptorIndex));10+}deleted:test/fixtures/stdin-fd3.js-6 removed
1-#!/usr/bin/env node2-import process from 'node:process';3-import {readFileSync} from 'node:fs';4-5-const fileDescriptorIndex = Number(process.argv[2] || 3);6-console.log(readFileSync(fileDescriptorIndex, {encoding: 'utf8'}));added:test/helpers/run.js+6 added
1+import {execa, execaSync, $} from '../../index.js';2+3+export const runExeca = (file, options) => execa(file, options);4+export const runExecaSync = (file, options) => execaSync(file, options);5+export const runScript = (file, options) => $(options)`${file}`;6+export const runScriptSync = (file, options) => $(options).sync`${file}`;modified:test/helpers/stdio.js+15 added-8 removed
1-export const getStdinOption = stdioOption => ({stdin: stdioOption});2-export const getStdoutOption = stdioOption => ({stdout: stdioOption});3-export const getStderrOption = stdioOption => ({stderr: stdioOption});4-export const getStdioOption = stdioOption => ({stdio: ['pipe', 'pipe', 'pipe', stdioOption]});5-export const getInputOption = input => ({input});6-export const getInputFileOption = inputFile => ({inputFile});1+import process from 'node:process';2 8-export const getScriptSync = $ => $.sync;9-3 export const identity = value => value;4+5+export const getStdio = (indexOrName, stdioOption) => {6+ if (typeof indexOrName === 'string') {7+ return {[indexOrName]: stdioOption};8+ }9+10+ const stdio = ['pipe', 'pipe', 'pipe'];11+ stdio[indexOrName] = stdioOption;12+ return {stdio};13+};14+15+export const fullStdio = getStdio(3, 'pipe');16+17+export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];modified:test/stdio/array.js+149 added-159 removed
1 unmodified line2 import process from 'node:process';3 import test from 'ava';4 import tempfile from 'tempfile';5 import {execa, execaSync} from '../../index.js';6-import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption} from '../helpers/stdio.js';6+import {fullStdio, getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';7 import {stringGenerator} from '../helpers/generator.js';8 import {setFixtureDir} from '../helpers/fixtures-dir.js';9 10 setFixtureDir();11 12-const testEmptyArray = (t, getOptions, optionName, execaMethod) => {12+const testEmptyArray = (t, index, optionName, execaMethod) => {13 t.throws(() => {14- execaMethod('noop.js', getOptions([]));14+ execaMethod('empty.js', getStdio(index, []));15 }, {message: `The \`${optionName}\` option must not be an empty array.`});16 };17 18-test('Cannot pass an empty array to stdin', testEmptyArray, getStdinOption, 'stdin', execa);19-test('Cannot pass an empty array to stdout', testEmptyArray, getStdoutOption, 'stdout', execa);20-test('Cannot pass an empty array to stderr', testEmptyArray, getStderrOption, 'stderr', execa);21-test('Cannot pass an empty array to stdio[*]', testEmptyArray, getStdioOption, 'stdio[3]', execa);22-test('Cannot pass an empty array to stdin - sync', testEmptyArray, getStdinOption, 'stdin', execaSync);23-test('Cannot pass an empty array to stdout - sync', testEmptyArray, getStdoutOption, 'stdout', execaSync);24-test('Cannot pass an empty array to stderr - sync', testEmptyArray, getStderrOption, 'stderr', execaSync);25-test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, getStdioOption, 'stdio[3]', execaSync);18+test('Cannot pass an empty array to stdin', testEmptyArray, 0, 'stdin', execa);19+test('Cannot pass an empty array to stdout', testEmptyArray, 1, 'stdout', execa);20+test('Cannot pass an empty array to stderr', testEmptyArray, 2, 'stderr', execa);21+test('Cannot pass an empty array to stdio[*]', testEmptyArray, 3, 'stdio[3]', execa);22+test('Cannot pass an empty array to stdin - sync', testEmptyArray, 0, 'stdin', execaSync);23+test('Cannot pass an empty array to stdout - sync', testEmptyArray, 1, 'stdout', execaSync);24+test('Cannot pass an empty array to stderr - sync', testEmptyArray, 2, 'stderr', execaSync);25+test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, 3, 'stdio[3]', execaSync);26 27-const testNoPipeOption = async (t, stdioOption, streamName) => {28- const childProcess = execa('empty.js', {[streamName]: stdioOption});29- t.is(childProcess[streamName], null);27+const testNoPipeOption = async (t, stdioOption, index) => {28+ const childProcess = execa('empty.js', getStdio(index, stdioOption));29+ t.is(childProcess.stdio[index], null);30 await childProcess;31 };32 33-test('stdin can be "ignore"', testNoPipeOption, 'ignore', 'stdin');34-test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 'stdin');35-test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 'stdin');36-test('stdin can be "ipc"', testNoPipeOption, 'ipc', 'stdin');37-test('stdin can be ["ipc"]', testNoPipeOption, ['ipc'], 'stdin');38-test('stdin can be "inherit"', testNoPipeOption, 'inherit', 'stdin');39-test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 'stdin');40-test('stdin can be 0', testNoPipeOption, 0, 'stdin');41-test('stdin can be [0]', testNoPipeOption, [0], 'stdin');42-test('stdout can be "ignore"', testNoPipeOption, 'ignore', 'stdout');43-test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 'stdout');44-test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 'stdout');45-test('stdout can be "ipc"', testNoPipeOption, 'ipc', 'stdout');46-test('stdout can be ["ipc"]', testNoPipeOption, ['ipc'], 'stdout');47-test('stdout can be "inherit"', testNoPipeOption, 'inherit', 'stdout');48-test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 'stdout');49-test('stdout can be 1', testNoPipeOption, 1, 'stdout');50-test('stdout can be [1]', testNoPipeOption, [1], 'stdout');51-test('stderr can be "ignore"', testNoPipeOption, 'ignore', 'stderr');52-test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 'stderr');53-test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 'stderr');54-test('stderr can be "ipc"', testNoPipeOption, 'ipc', 'stderr');55-test('stderr can be ["ipc"]', testNoPipeOption, ['ipc'], 'stderr');56-test('stderr can be "inherit"', testNoPipeOption, 'inherit', 'stderr');57-test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 'stderr');58-test('stderr can be 2', testNoPipeOption, 2, 'stderr');59-test('stderr can be [2]', testNoPipeOption, [2], 'stderr');33+test('stdin can be "ignore"', testNoPipeOption, 'ignore', 0);34+test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 0);35+test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 0);36+test('stdin can be "ipc"', testNoPipeOption, 'ipc', 0);37+test('stdin can be ["ipc"]', testNoPipeOption, ['ipc'], 0);38+test('stdin can be "inherit"', testNoPipeOption, 'inherit', 0);39+test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 0);40+test('stdin can be 0', testNoPipeOption, 0, 0);41+test('stdin can be [0]', testNoPipeOption, [0], 0);42+test('stdout can be "ignore"', testNoPipeOption, 'ignore', 1);43+test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 1);44+test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 1);45+test('stdout can be "ipc"', testNoPipeOption, 'ipc', 1);46+test('stdout can be ["ipc"]', testNoPipeOption, ['ipc'], 1);47+test('stdout can be "inherit"', testNoPipeOption, 'inherit', 1);48+test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 1);49+test('stdout can be 1', testNoPipeOption, 1, 1);50+test('stdout can be [1]', testNoPipeOption, [1], 1);51+test('stderr can be "ignore"', testNoPipeOption, 'ignore', 2);52+test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 2);53+test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 2);54+test('stderr can be "ipc"', testNoPipeOption, 'ipc', 2);55+test('stderr can be ["ipc"]', testNoPipeOption, ['ipc'], 2);56+test('stderr can be "inherit"', testNoPipeOption, 'inherit', 2);57+test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 2);58+test('stderr can be 2', testNoPipeOption, 2, 2);59+test('stderr can be [2]', testNoPipeOption, [2], 2);60+test('stdio[*] can be "ignore"', testNoPipeOption, 'ignore', 3);61+test('stdio[*] can be ["ignore"]', testNoPipeOption, ['ignore'], 3);62+test('stdio[*] can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 3);63+test('stdio[*] can be "ipc"', testNoPipeOption, 'ipc', 3);64+test('stdio[*] can be ["ipc"]', testNoPipeOption, ['ipc'], 3);65+test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);66+test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);67+test('stdio[*] can be 3', testNoPipeOption, 3, 3);68+test('stdio[*] can be [3]', testNoPipeOption, [3], 3);69 61-const testNoPipeStdioOption = async (t, stdioOption) => {62- const childProcess = execa('empty.js', {stdio: ['pipe', 'pipe', 'pipe', stdioOption]});63- t.is(childProcess.stdio[3], null);64- await childProcess;65-};66-67-test('stdio[*] can be "ignore"', testNoPipeStdioOption, 'ignore');68-test('stdio[*] can be ["ignore"]', testNoPipeStdioOption, ['ignore']);69-test('stdio[*] can be ["ignore", "ignore"]', testNoPipeStdioOption, ['ignore', 'ignore']);70-test('stdio[*] can be "ipc"', testNoPipeStdioOption, 'ipc');71-test('stdio[*] can be ["ipc"]', testNoPipeStdioOption, ['ipc']);72-test('stdio[*] can be "inherit"', testNoPipeStdioOption, 'inherit');73-test('stdio[*] can be ["inherit"]', testNoPipeStdioOption, ['inherit']);74-test('stdio[*] can be 3', testNoPipeStdioOption, 3);75-test('stdio[*] can be [3]', testNoPipeStdioOption, [3]);76-77-const testInvalidArrayValue = (t, invalidStdio, getOptions, execaMethod) => {70+const testInvalidArrayValue = (t, invalidStdio, index, execaMethod) => {71 t.throws(() => {79- execaMethod('noop.js', getOptions(['pipe', invalidStdio]));72+ execaMethod('empty.js', getStdio(index, ['pipe', invalidStdio]));73 }, {message: /must not include/});74 };75 83-test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', getStdinOption, execa);84-test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', getStdoutOption, execa);85-test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', getStderrOption, execa);86-test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', getStdioOption, execa);87-test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', getStdinOption, execaSync);88-test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', getStdoutOption, execaSync);89-test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', getStderrOption, execaSync);90-test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', getStdioOption, execaSync);91-test('Cannot pass "ipc" and another value to stdin', testInvalidArrayValue, 'ipc', getStdinOption, execa);92-test('Cannot pass "ipc" and another value to stdout', testInvalidArrayValue, 'ipc', getStdoutOption, execa);93-test('Cannot pass "ipc" and another value to stderr', testInvalidArrayValue, 'ipc', getStderrOption, execa);94-test('Cannot pass "ipc" and another value to stdio[*]', testInvalidArrayValue, 'ipc', getStdioOption, execa);95-test('Cannot pass "ipc" and another value to stdin - sync', testInvalidArrayValue, 'ipc', getStdinOption, execaSync);96-test('Cannot pass "ipc" and another value to stdout - sync', testInvalidArrayValue, 'ipc', getStdoutOption, execaSync);97-test('Cannot pass "ipc" and another value to stderr - sync', testInvalidArrayValue, 'ipc', getStderrOption, execaSync);98-test('Cannot pass "ipc" and another value to stdio[*] - sync', testInvalidArrayValue, 'ipc', getStdioOption, execaSync);76+test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', 0, execa);77+test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', 1, execa);78+test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', 2, execa);79+test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', 3, execa);80+test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', 0, execaSync);81+test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', 1, execaSync);82+test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', 2, execaSync);83+test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', 3, execaSync);84+test('Cannot pass "ipc" and another value to stdin', testInvalidArrayValue, 'ipc', 0, execa);85+test('Cannot pass "ipc" and another value to stdout', testInvalidArrayValue, 'ipc', 1, execa);86+test('Cannot pass "ipc" and another value to stderr', testInvalidArrayValue, 'ipc', 2, execa);87+test('Cannot pass "ipc" and another value to stdio[*]', testInvalidArrayValue, 'ipc', 3, execa);88+test('Cannot pass "ipc" and another value to stdin - sync', testInvalidArrayValue, 'ipc', 0, execaSync);89+test('Cannot pass "ipc" and another value to stdout - sync', testInvalidArrayValue, 'ipc', 1, execaSync);90+test('Cannot pass "ipc" and another value to stderr - sync', testInvalidArrayValue, 'ipc', 2, execaSync);91+test('Cannot pass "ipc" and another value to stdio[*] - sync', testInvalidArrayValue, 'ipc', 3, execaSync);92 93 const testInputOutput = (t, stdioOption, execaMethod) => {94 t.throws(() => {102- execaMethod('noop.js', getStdioOption([new ReadableStream(), stdioOption]));95+ execaMethod('empty.js', getStdio(3, [new ReadableStream(), stdioOption]));96 }, {message: /readable and writable/});97 };98 99 test('Cannot pass both readable and writable values to stdio[*] - WritableStream', testInputOutput, new WritableStream(), execa);8 unmodified lines108 test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', testInputOutput, process.stderr, execaSync);109 110 const testAmbiguousDirection = async (t, execaMethod) => {111 const [filePathOne, filePathTwo] = [tempfile(), tempfile()];119- await execaMethod('noop-fd3.js', ['foobar'], getStdioOption([{file: filePathOne}, {file: filePathTwo}]));120- t.deepEqual(await Promise.all([readFile(filePathOne, 'utf8'), readFile(filePathTwo, 'utf8')]), ['foobar\n', 'foobar\n']);112+ await execaMethod('noop-fd.js', ['3', 'foobar'], getStdio(3, [{file: filePathOne}, {file: filePathTwo}]));113+ t.deepEqual(114+ await Promise.all([readFile(filePathOne, 'utf8'), readFile(filePathTwo, 'utf8')]),115+ ['foobar', 'foobar'],116+ );117 await Promise.all([rm(filePathOne), rm(filePathTwo)]);118 };119 120 test('stdio[*] default direction is output', testAmbiguousDirection, execa);121 test('stdio[*] default direction is output - sync', testAmbiguousDirection, execaSync);122 127-const testAmbiguousMultiple = async (t, fixtureName, getOptions) => {123+const testAmbiguousMultiple = async (t, index) => {124 const filePath = tempfile();125 await writeFile(filePath, 'foobar');130- const {stdout} = await execa(fixtureName, getOptions([{file: filePath}, stringGenerator()]));126+ const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [{file: filePath}, stringGenerator()]));127 t.is(stdout, 'foobarfoobar');128 await rm(filePath);129 };130 135-test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 'stdin.js', getStdinOption);136-test('stdio[*] ambiguous direction is influenced by other values', testAmbiguousMultiple, 'stdin-fd3.js', getStdioOption);131+test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 0);132+test('stdio[*] ambiguous direction is influenced by other values', testAmbiguousMultiple, 3);133 138-const testRedirectInput = async (t, stdioOption, index, fixtureName) => {139- const {stdout} = await execa('nested-stdio.js', [JSON.stringify(stdioOption), String(index), fixtureName], {input: 'foobar'});140- t.is(stdout, 'foobar');134+const testRedirect = async (t, stdioOption, index, isInput) => {135+ const {fixtureName, ...options} = isInput136+ ? {fixtureName: 'stdin-fd.js', input: 'foobar'}137+ : {fixtureName: 'noop-fd.js'};138+ const {stdio} = await execa('nested-stdio.js', [JSON.stringify(stdioOption), `${index}`, fixtureName, 'foobar'], options);139+ const resultIndex = isStderrDescriptor(stdioOption) ? 2 : 1;140+ t.is(stdio[resultIndex], 'foobar');141 };142 143-test.serial('stdio[*] can be 0', testRedirectInput, 0, 3, 'stdin-fd3.js');144-test.serial('stdio[*] can be [0]', testRedirectInput, [0], 3, 'stdin-fd3.js');145-test.serial('stdio[*] can be [0, "pipe"]', testRedirectInput, [0, 'pipe'], 3, 'stdin-fd3.js');146-test.serial('stdio[*] can be process.stdin', testRedirectInput, 'stdin', 3, 'stdin-fd3.js');147-test.serial('stdio[*] can be [process.stdin]', testRedirectInput, ['stdin'], 3, 'stdin-fd3.js');148-test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirectInput, ['stdin', 'pipe'], 3, 'stdin-fd3.js');143+const isStderrDescriptor = stdioOption => stdioOption === 2144+ || stdioOption === 'stderr'145+ || (Array.isArray(stdioOption) && isStderrDescriptor(stdioOption[0]));146 150-const OUTPUT_DESCRIPTOR_FIXTURES = ['noop.js', 'noop-err.js', 'noop-fd3.js'];147+test.serial('stdio[*] can be 0', testRedirect, 0, 3, true);148+test.serial('stdio[*] can be [0]', testRedirect, [0], 3, true);149+test.serial('stdio[*] can be [0, "pipe"]', testRedirect, [0, 'pipe'], 3, true);150+test.serial('stdio[*] can be process.stdin', testRedirect, 'stdin', 3, true);151+test.serial('stdio[*] can be [process.stdin]', testRedirect, ['stdin'], 3, true);152+test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirect, ['stdin', 'pipe'], 3, true);153+test('stdout can be 2', testRedirect, 2, 1, false);154+test('stdout can be [2]', testRedirect, [2], 1, false);155+test('stdout can be [2, "pipe"]', testRedirect, [2, 'pipe'], 1, false);156+test('stdout can be process.stderr', testRedirect, 'stderr', 1, false);157+test('stdout can be [process.stderr]', testRedirect, ['stderr'], 1, false);158+test('stdout can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 1, false);159+test('stderr can be 1', testRedirect, 1, 2, false);160+test('stderr can be [1]', testRedirect, [1], 2, false);161+test('stderr can be [1, "pipe"]', testRedirect, [1, 'pipe'], 2, false);162+test('stderr can be process.stdout', testRedirect, 'stdout', 2, false);163+test('stderr can be [process.stdout]', testRedirect, ['stdout'], 2, false);164+test('stderr can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 2, false);165+test('stdio[*] can be 1', testRedirect, 1, 3, false);166+test('stdio[*] can be [1]', testRedirect, [1], 3, false);167+test('stdio[*] can be [1, "pipe"]', testRedirect, [1, 'pipe'], 3, false);168+test('stdio[*] can be 2', testRedirect, 2, 3, false);169+test('stdio[*] can be [2]', testRedirect, [2], 3, false);170+test('stdio[*] can be [2, "pipe"]', testRedirect, [2, 'pipe'], 3, false);171+test('stdio[*] can be process.stdout', testRedirect, 'stdout', 3, false);172+test('stdio[*] can be [process.stdout]', testRedirect, ['stdout'], 3, false);173+test('stdio[*] can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 3, false);174+test('stdio[*] can be process.stderr', testRedirect, 'stderr', 3, false);175+test('stdio[*] can be [process.stderr]', testRedirect, ['stderr'], 3, false);176+test('stdio[*] can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 3, false);177 152-const isStdoutDescriptor = stdioOption => stdioOption === 1153- || stdioOption === 'stdout'154- || (Array.isArray(stdioOption) && isStdoutDescriptor(stdioOption[0]));155-156-const testRedirectOutput = async (t, stdioOption, index) => {157- const fixtureName = OUTPUT_DESCRIPTOR_FIXTURES[index - 1];158- const result = await execa('nested-stdio.js', [JSON.stringify(stdioOption), String(index), fixtureName, 'foobar']);159- const streamName = isStdoutDescriptor(stdioOption) ? 'stdout' : 'stderr';160- t.is(result[streamName], 'foobar');161-};162-163-test('stdout can be 2', testRedirectOutput, 2, 1);164-test('stdout can be [2]', testRedirectOutput, [2], 1);165-test('stdout can be [2, "pipe"]', testRedirectOutput, [2, 'pipe'], 1);166-test('stdout can be process.stderr', testRedirectOutput, 'stderr', 1);167-test('stdout can be [process.stderr]', testRedirectOutput, ['stderr'], 1);168-test('stdout can be [process.stderr, "pipe"]', testRedirectOutput, ['stderr', 'pipe'], 1);169-test('stderr can be 1', testRedirectOutput, 1, 2);170-test('stderr can be [1]', testRedirectOutput, [1], 2);171-test('stderr can be [1, "pipe"]', testRedirectOutput, [1, 'pipe'], 2);172-test('stderr can be process.stdout', testRedirectOutput, 'stdout', 2);173-test('stderr can be [process.stdout]', testRedirectOutput, ['stdout'], 2);174-test('stderr can be [process.stdout, "pipe"]', testRedirectOutput, ['stdout', 'pipe'], 2);175-test('stdio[*] can be 1', testRedirectOutput, 1, 3);176-test('stdio[*] can be [1]', testRedirectOutput, [1], 3);177-test('stdio[*] can be [1, "pipe"]', testRedirectOutput, [1, 'pipe'], 3);178-test('stdio[*] can be 2', testRedirectOutput, 2, 3);179-test('stdio[*] can be [2]', testRedirectOutput, [2], 3);180-test('stdio[*] can be [2, "pipe"]', testRedirectOutput, [2, 'pipe'], 3);181-test('stdio[*] can be process.stdout', testRedirectOutput, 'stdout', 3);182-test('stdio[*] can be [process.stdout]', testRedirectOutput, ['stdout'], 3);183-test('stdio[*] can be [process.stdout, "pipe"]', testRedirectOutput, ['stdout', 'pipe'], 3);184-test('stdio[*] can be process.stderr', testRedirectOutput, 'stderr', 3);185-test('stdio[*] can be [process.stderr]', testRedirectOutput, ['stderr'], 3);186-test('stdio[*] can be [process.stderr, "pipe"]', testRedirectOutput, ['stderr', 'pipe'], 3);187-178 const testInheritStdin = async (t, stdin) => {179 const {stdout} = await execa('nested-multiple-stdin.js', [JSON.stringify(stdin)], {input: 'foobar'});180 t.is(stdout, 'foobarfoobar');181 };18 unmodified lines200 201 test('stderr can be ["inherit", "pipe"]', testInheritStderr, ['inherit', 'pipe']);202 test('stderr can be [2, "pipe"]', testInheritStderr, [2, 'pipe']);203 214-const testOverflowStream = async (t, stdio) => {215- const {stdout} = await execa('nested.js', [JSON.stringify({stdio}), 'empty.js'], {stdio: ['pipe', 'pipe', 'pipe', 'pipe']});204+const testOverflowStream = async (t, index, stdioOption) => {205+ const {stdout} = await execa('nested.js', [JSON.stringify(getStdio(index, stdioOption)), 'empty.js'], fullStdio);206 t.is(stdout, '');207 };208 209 if (process.platform === 'linux') {220- test('stdin can use 4+', testOverflowStream, [4, 'pipe', 'pipe', 'pipe']);221- test('stdin can use [4+]', testOverflowStream, [[4], 'pipe', 'pipe', 'pipe']);222- test('stdout can use 4+', testOverflowStream, ['pipe', 4, 'pipe', 'pipe']);223- test('stdout can use [4+]', testOverflowStream, ['pipe', [4], 'pipe', 'pipe']);224- test('stderr can use 4+', testOverflowStream, ['pipe', 'pipe', 4, 'pipe']);225- test('stderr can use [4+]', testOverflowStream, ['pipe', 'pipe', [4], 'pipe']);226- test('stdio[*] can use 4+', testOverflowStream, ['pipe', 'pipe', 'pipe', 4]);227- test('stdio[*] can use [4+]', testOverflowStream, ['pipe', 'pipe', 'pipe', [4]]);210+ test('stdin can use 4+', testOverflowStream, 0, 4);211+ test('stdin can use [4+]', testOverflowStream, 0, [4]);212+ test('stdout can use 4+', testOverflowStream, 1, 4);213+ test('stdout can use [4+]', testOverflowStream, 1, [4]);214+ test('stderr can use 4+', testOverflowStream, 2, 4);215+ test('stderr can use [4+]', testOverflowStream, 2, [4]);216+ test('stdio[*] can use 4+', testOverflowStream, 3, 4);217+ test('stdio[*] can use [4+]', testOverflowStream, 3, [4]);218 }219 230-test('stdio[*] can use "inherit"', testOverflowStream, ['pipe', 'pipe', 'pipe', 'inherit']);231-test('stdio[*] can use ["inherit"]', testOverflowStream, ['pipe', 'pipe', 'pipe', ['inherit']]);220+test('stdio[*] can use "inherit"', testOverflowStream, 3, 'inherit');221+test('stdio[*] can use ["inherit"]', testOverflowStream, 3, ['inherit']);222 233-const testOverflowStreamArray = (t, stdio) => {223+const testOverflowStreamArray = (t, index, stdioOption) => {224 t.throws(() => {235- execa('noop.js', {stdio});225+ execa('empty.js', getStdio(index, stdioOption));226 }, {message: /no such standard stream/});227 };228 239-test('stdin cannot use 4+ and another value', testOverflowStreamArray, [[4, 'pipe'], 'pipe', 'pipe', 'pipe']);240-test('stdout cannot use 4+ and another value', testOverflowStreamArray, ['pipe', [4, 'pipe'], 'pipe', 'pipe']);241-test('stderr cannot use 4+ and another value', testOverflowStreamArray, ['pipe', 'pipe', [4, 'pipe'], 'pipe']);242-test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, ['pipe', 'pipe', 'pipe', [4, 'pipe']]);243-test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, ['pipe', 'pipe', 'pipe', ['inherit', 'pipe']]);229+test('stdin cannot use 4+ and another value', testOverflowStreamArray, 0, [4, 'pipe']);230+test('stdout cannot use 4+ and another value', testOverflowStreamArray, 1, [4, 'pipe']);231+test('stderr cannot use 4+ and another value', testOverflowStreamArray, 2, [4, 'pipe']);232+test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, 3, [4, 'pipe']);233+test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, 3, ['inherit', 'pipe']);234 245-const testOverlapped = async (t, getOptions) => {246- const {stdout} = await execa('noop.js', ['foobar'], getOptions(['overlapped', 'pipe']));235+const testOverlapped = async (t, index) => {236+ const {stdout} = await execa('noop.js', ['foobar'], getStdio(index, ['overlapped', 'pipe']));237 t.is(stdout, 'foobar');238 };239 250-test('stdin can be ["overlapped", "pipe"]', testOverlapped, getStdinOption);251-test('stdout can be ["overlapped", "pipe"]', testOverlapped, getStdoutOption);252-test('stderr can be ["overlapped", "pipe"]', testOverlapped, getStderrOption);253-test('stdio[*] can be ["overlapped", "pipe"]', testOverlapped, getStdioOption);240+test('stdin can be ["overlapped", "pipe"]', testOverlapped, 0);241+test('stdout can be ["overlapped", "pipe"]', testOverlapped, 1);242+test('stderr can be ["overlapped", "pipe"]', testOverlapped, 2);243+test('stdio[*] can be ["overlapped", "pipe"]', testOverlapped, 3);244 255-const testDestroyStandard = async (t, optionName) => {245+const testDestroyStandard = async (t, index) => {246 await t.throwsAsync(257- execa('forever.js', {timeout: 1, [optionName]: [process[optionName], 'pipe']}),247+ execa('forever.js', {...getStdio(index, [STANDARD_STREAMS[index], 'pipe']), timeout: 1}),248 {message: /timed out/},249 );260- t.false(process[optionName].destroyed);250+ t.false(STANDARD_STREAMS[index].destroyed);251 };252 263-test('Does not destroy process.stdin on errors', testDestroyStandard, 'stdin');264-test('Does not destroy process.stdout on errors', testDestroyStandard, 'stdout');265-test('Does not destroy process.stderr on errors', testDestroyStandard, 'stderr');253+test('Does not destroy process.stdin on errors', testDestroyStandard, 0);254+test('Does not destroy process.stdout on errors', testDestroyStandard, 1);255+test('Does not destroy process.stderr on errors', testDestroyStandard, 2);modified:test/stdio/file-descriptor.js+16 added-18 removed
1 unmodified line2 import test from 'ava';3 import tempfile from 'tempfile';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDir} from '../helpers/fixtures-dir.js';6-import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption} from '../helpers/stdio.js';6+import {getStdio} from '../helpers/stdio.js';7 8 setFixtureDir();9 10-const getStdinProp = ({stdin}) => stdin;11-const getStdioProp = ({stdio}) => stdio[3];12-13-const testFileDescriptorOption = async (t, fixtureName, getOptions, execaMethod) => {10+const testFileDescriptorOption = async (t, index, execaMethod) => {11 const filePath = tempfile();12 const fileDescriptor = await open(filePath, 'w');16- await execaMethod(fixtureName, ['foobar'], getOptions(fileDescriptor));17- t.is(await readFile(filePath, 'utf8'), 'foobar\n');13+ await execaMethod('noop-fd.js', [`${index}`, 'foobar'], getStdio(index, fileDescriptor));14+ t.is(await readFile(filePath, 'utf8'), 'foobar');15 await rm(filePath);16+ await fileDescriptor.close();17 };18 21-test('pass `stdout` to a file descriptor', testFileDescriptorOption, 'noop.js', getStdoutOption, execa);22-test('pass `stderr` to a file descriptor', testFileDescriptorOption, 'noop-err.js', getStderrOption, execa);23-test('pass `stdio[*]` to a file descriptor', testFileDescriptorOption, 'noop-fd3.js', getStdioOption, execa);24-test('pass `stdout` to a file descriptor - sync', testFileDescriptorOption, 'noop.js', getStdoutOption, execaSync);25-test('pass `stderr` to a file descriptor - sync', testFileDescriptorOption, 'noop-err.js', getStderrOption, execaSync);26-test('pass `stdio[*]` to a file descriptor - sync', testFileDescriptorOption, 'noop-fd3.js', getStdioOption, execaSync);19+test('pass `stdout` to a file descriptor', testFileDescriptorOption, 1, execa);20+test('pass `stderr` to a file descriptor', testFileDescriptorOption, 2, execa);21+test('pass `stdio[*]` to a file descriptor', testFileDescriptorOption, 3, execa);22+test('pass `stdout` to a file descriptor - sync', testFileDescriptorOption, 1, execaSync);23+test('pass `stderr` to a file descriptor - sync', testFileDescriptorOption, 2, execaSync);24+test('pass `stdio[*]` to a file descriptor - sync', testFileDescriptorOption, 3, execaSync);25 28-const testStdinWrite = async (t, getStreamProp, fixtureName, getOptions) => {29- const subprocess = execa(fixtureName, getOptions('pipe'));30- getStreamProp(subprocess).end('unicorns');26+const testStdinWrite = async (t, index) => {27+ const subprocess = execa('stdin-fd.js', [`${index}`], getStdio(index, 'pipe'));28+ subprocess.stdio[index].end('unicorns');29 const {stdout} = await subprocess;30 t.is(stdout, 'unicorns');31 };32 35-test('you can write to child.stdin', testStdinWrite, getStdinProp, 'stdin.js', getStdinOption);36-test('you can write to child.stdio[*]', testStdinWrite, getStdioProp, 'stdin-fd3.js', getStdioOption);33+test('you can write to child.stdin', testStdinWrite, 0);34+test('you can write to child.stdio[*]', testStdinWrite, 3);modified:test/stdio/file-path.js+126 added-134 removed
2 unmodified lines3 import process from 'node:process';4 import {pathToFileURL} from 'node:url';5 import test from 'ava';6 import tempfile from 'tempfile';7-import {execa, execaSync, $} from '../../index.js';7+import {execa, execaSync} from '../../index.js';8 import {setFixtureDir} from '../helpers/fixtures-dir.js';9-import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption, getInputFileOption, getScriptSync, identity} from '../helpers/stdio.js';9+import {identity, getStdio} from '../helpers/stdio.js';10+import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';11 12 setFixtureDir();13 14 const textEncoder = new TextEncoder();1 unmodified line16 const nonFileUrl = new URL('https://example.com');17 18 const getAbsolutePath = file => ({file});19 const getRelativePath = filePath => ({file: relative('.', filePath)});19-const getStdinFilePath = file => ({stdin: {file}});20 21+const getStdioFile = (index, file) => getStdio(index, index === 0 ? {file} : file);22+23+const getStdioInput = (index, file) => {24+ if (index === 'string') {25+ return {input: 'foobar'};26+ }27+28+ if (index === 'binary') {29+ return {input: binaryFoobar};30+ }31+32+ return getStdioFile(index, file);33+};34+21-const testStdinFile = async (t, mapFilePath, getOptions, execaMethod) => {35+const testStdinFile = async (t, mapFilePath, index, execaMethod) => {36 const filePath = tempfile();37 await writeFile(filePath, 'foobar');24- const {stdout} = await execaMethod('stdin.js', getOptions(mapFilePath(filePath)));38+ const {stdout} = await execaMethod('stdin.js', getStdio(index, mapFilePath(filePath)));39 t.is(stdout, 'foobar');40 await rm(filePath);41 };42 29-test('inputFile can be a file URL', testStdinFile, pathToFileURL, getInputFileOption, execa);30-test('stdin can be a file URL', testStdinFile, pathToFileURL, getStdinOption, execa);31-test('inputFile can be an absolute file path', testStdinFile, identity, getInputFileOption, execa);32-test('stdin can be an absolute file path', testStdinFile, getAbsolutePath, getStdinOption, execa);33-test('inputFile can be a relative file path', testStdinFile, identity, getInputFileOption, execa);34-test('stdin can be a relative file path', testStdinFile, getRelativePath, getStdinOption, execa);35-test('inputFile can be a file URL - sync', testStdinFile, pathToFileURL, getInputFileOption, execaSync);36-test('stdin can be a file URL - sync', testStdinFile, pathToFileURL, getStdinOption, execaSync);37-test('inputFile can be an absolute file path - sync', testStdinFile, identity, getInputFileOption, execaSync);38-test('stdin can be an absolute file path - sync', testStdinFile, getAbsolutePath, getStdinOption, execaSync);39-test('inputFile can be a relative file path - sync', testStdinFile, identity, getInputFileOption, execaSync);40-test('stdin can be a relative file path - sync', testStdinFile, getRelativePath, getStdinOption, execaSync);43+test('inputFile can be a file URL', testStdinFile, pathToFileURL, 'inputFile', execa);44+test('stdin can be a file URL', testStdinFile, pathToFileURL, 0, execa);45+test('inputFile can be an absolute file path', testStdinFile, identity, 'inputFile', execa);46+test('stdin can be an absolute file path', testStdinFile, getAbsolutePath, 0, execa);47+test('inputFile can be a relative file path', testStdinFile, identity, 'inputFile', execa);48+test('stdin can be a relative file path', testStdinFile, getRelativePath, 0, execa);49+test('inputFile can be a file URL - sync', testStdinFile, pathToFileURL, 'inputFile', execaSync);50+test('stdin can be a file URL - sync', testStdinFile, pathToFileURL, 0, execaSync);51+test('inputFile can be an absolute file path - sync', testStdinFile, identity, 'inputFile', execaSync);52+test('stdin can be an absolute file path - sync', testStdinFile, getAbsolutePath, 0, execaSync);53+test('inputFile can be a relative file path - sync', testStdinFile, identity, 'inputFile', execaSync);54+test('stdin can be a relative file path - sync', testStdinFile, getRelativePath, 0, execaSync);55 42-// eslint-disable-next-line max-params43-const testOutputFile = async (t, mapFile, fixtureName, getOptions, execaMethod) => {56+const testOutputFile = async (t, mapFile, index, execaMethod) => {57 const filePath = tempfile();45- await execaMethod(fixtureName, ['foobar'], getOptions(mapFile(filePath)));46- t.is(await readFile(filePath, 'utf8'), 'foobar\n');58+ await execaMethod('noop-fd.js', [`${index}`, 'foobar'], getStdio(index, mapFile(filePath)));59+ t.is(await readFile(filePath, 'utf8'), 'foobar');60 await rm(filePath);61 };62 50-test('stdout can be a file URL', testOutputFile, pathToFileURL, 'noop.js', getStdoutOption, execa);51-test('stderr can be a file URL', testOutputFile, pathToFileURL, 'noop-err.js', getStderrOption, execa);52-test('stdio[*] can be a file URL', testOutputFile, pathToFileURL, 'noop-fd3.js', getStdioOption, execa);53-test('stdout can be an absolute file path', testOutputFile, getAbsolutePath, 'noop.js', getStdoutOption, execa);54-test('stderr can be an absolute file path', testOutputFile, getAbsolutePath, 'noop-err.js', getStderrOption, execa);55-test('stdio[*] can be an absolute file path', testOutputFile, getAbsolutePath, 'noop-fd3.js', getStdioOption, execa);56-test('stdout can be a relative file path', testOutputFile, getRelativePath, 'noop.js', getStdoutOption, execa);57-test('stderr can be a relative file path', testOutputFile, getRelativePath, 'noop-err.js', getStderrOption, execa);58-test('stdio[*] can be a relative file path', testOutputFile, getRelativePath, 'noop-fd3.js', getStdioOption, execa);59-test('stdout can be a file URL - sync', testOutputFile, pathToFileURL, 'noop.js', getStdoutOption, execaSync);60-test('stderr can be a file URL - sync', testOutputFile, pathToFileURL, 'noop-err.js', getStderrOption, execaSync);61-test('stdio[*] can be a file URL - sync', testOutputFile, pathToFileURL, 'noop-fd3.js', getStdioOption, execaSync);62-test('stdout can be an absolute file path - sync', testOutputFile, getAbsolutePath, 'noop.js', getStdoutOption, execaSync);63-test('stderr can be an absolute file path - sync', testOutputFile, getAbsolutePath, 'noop-err.js', getStderrOption, execaSync);64-test('stdio[*] can be an absolute file path - sync', testOutputFile, getAbsolutePath, 'noop-fd3.js', getStdioOption, execaSync);65-test('stdout can be a relative file path - sync', testOutputFile, getRelativePath, 'noop.js', getStdoutOption, execaSync);66-test('stderr can be a relative file path - sync', testOutputFile, getRelativePath, 'noop-err.js', getStderrOption, execaSync);67-test('stdio[*] can be a relative file path - sync', testOutputFile, getRelativePath, 'noop-fd3.js', getStdioOption, execaSync);63+test('stdout can be a file URL', testOutputFile, pathToFileURL, 1, execa);64+test('stderr can be a file URL', testOutputFile, pathToFileURL, 2, execa);65+test('stdio[*] can be a file URL', testOutputFile, pathToFileURL, 3, execa);66+test('stdout can be an absolute file path', testOutputFile, getAbsolutePath, 1, execa);67+test('stderr can be an absolute file path', testOutputFile, getAbsolutePath, 2, execa);68+test('stdio[*] can be an absolute file path', testOutputFile, getAbsolutePath, 3, execa);69+test('stdout can be a relative file path', testOutputFile, getRelativePath, 1, execa);70+test('stderr can be a relative file path', testOutputFile, getRelativePath, 2, execa);71+test('stdio[*] can be a relative file path', testOutputFile, getRelativePath, 3, execa);72+test('stdout can be a file URL - sync', testOutputFile, pathToFileURL, 1, execaSync);73+test('stderr can be a file URL - sync', testOutputFile, pathToFileURL, 2, execaSync);74+test('stdio[*] can be a file URL - sync', testOutputFile, pathToFileURL, 3, execaSync);75+test('stdout can be an absolute file path - sync', testOutputFile, getAbsolutePath, 1, execaSync);76+test('stderr can be an absolute file path - sync', testOutputFile, getAbsolutePath, 2, execaSync);77+test('stdio[*] can be an absolute file path - sync', testOutputFile, getAbsolutePath, 3, execaSync);78+test('stdout can be a relative file path - sync', testOutputFile, getRelativePath, 1, execaSync);79+test('stderr can be a relative file path - sync', testOutputFile, getRelativePath, 2, execaSync);80+test('stdio[*] can be a relative file path - sync', testOutputFile, getRelativePath, 3, execaSync);81 69-const testStdioNonFileUrl = (t, getOptions, execaMethod) => {82+const testStdioNonFileUrl = (t, index, execaMethod) => {83 t.throws(() => {71- execaMethod('noop.js', getOptions(nonFileUrl));84+ execaMethod('empty.js', getStdio(index, nonFileUrl));85 }, {message: /pathToFileURL/});86 };87 75-test('inputFile cannot be a non-file URL', testStdioNonFileUrl, getInputFileOption, execa);76-test('stdin cannot be a non-file URL', testStdioNonFileUrl, getStdinOption, execa);77-test('stdout cannot be a non-file URL', testStdioNonFileUrl, getStdoutOption, execa);78-test('stderr cannot be a non-file URL', testStdioNonFileUrl, getStderrOption, execa);79-test('stdio[*] cannot be a non-file URL', testStdioNonFileUrl, getStdioOption, execa);80-test('inputFile cannot be a non-file URL - sync', testStdioNonFileUrl, getInputFileOption, execaSync);81-test('stdin cannot be a non-file URL - sync', testStdioNonFileUrl, getStdinOption, execaSync);82-test('stdout cannot be a non-file URL - sync', testStdioNonFileUrl, getStdoutOption, execaSync);83-test('stderr cannot be a non-file URL - sync', testStdioNonFileUrl, getStderrOption, execaSync);84-test('stdio[*] cannot be a non-file URL - sync', testStdioNonFileUrl, getStdioOption, execaSync);88+test('inputFile cannot be a non-file URL', testStdioNonFileUrl, 'inputFile', execa);89+test('stdin cannot be a non-file URL', testStdioNonFileUrl, 0, execa);90+test('stdout cannot be a non-file URL', testStdioNonFileUrl, 1, execa);91+test('stderr cannot be a non-file URL', testStdioNonFileUrl, 2, execa);92+test('stdio[*] cannot be a non-file URL', testStdioNonFileUrl, 3, execa);93+test('inputFile cannot be a non-file URL - sync', testStdioNonFileUrl, 'inputFile', execaSync);94+test('stdin cannot be a non-file URL - sync', testStdioNonFileUrl, 0, execaSync);95+test('stdout cannot be a non-file URL - sync', testStdioNonFileUrl, 1, execaSync);96+test('stderr cannot be a non-file URL - sync', testStdioNonFileUrl, 2, execaSync);97+test('stdio[*] cannot be a non-file URL - sync', testStdioNonFileUrl, 3, execaSync);98 99 const testInvalidInputFile = (t, execaMethod) => {100 t.throws(() => {88- execaMethod('noop.js', getInputFileOption(false));101+ execaMethod('empty.js', getStdio('inputFile', false));102 }, {message: /a file path string or a file URL/});103 };104 105 test('inputFile must be a file URL or string', testInvalidInputFile, execa);106 test('inputFile must be a file URL or string - sync', testInvalidInputFile, execaSync);107 95-const testInputFileValidUrl = async (t, getOptions, execaMethod) => {108+const testInputFileValidUrl = async (t, index, execaMethod) => {109 const filePath = tempfile();110 await writeFile(filePath, 'foobar');111 const currentCwd = process.cwd();112 process.chdir(dirname(filePath));113 114 try {102- const {stdout} = await execaMethod('stdin.js', getOptions(basename(filePath)));115+ const {stdout} = await execaMethod('stdin.js', getStdioFile(index, basename(filePath)));116 t.is(stdout, 'foobar');117 } finally {118 process.chdir(currentCwd);119 await rm(filePath);120 }121 };122 110-test.serial('inputFile does not need to start with . when being a relative file path', testInputFileValidUrl, getInputFileOption, execa);111-test.serial('stdin does not need to start with . when being a relative file path', testInputFileValidUrl, getStdinFilePath, execa);112-test.serial('inputFile does not need to start with . when being a relative file path - sync', testInputFileValidUrl, getInputFileOption, execaSync);113-test.serial('stdin does not need to start with . when being a relative file path - sync', testInputFileValidUrl, getStdinFilePath, execaSync);123+test.serial('inputFile does not need to start with . when being a relative file path', testInputFileValidUrl, 'inputFile', execa);124+test.serial('stdin does not need to start with . when being a relative file path', testInputFileValidUrl, 0, execa);125+test.serial('inputFile does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 'inputFile', execaSync);126+test.serial('stdin does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 0, execaSync);127 115-const testFilePathObject = (t, getOptions, execaMethod) => {128+const testFilePathObject = (t, index, execaMethod) => {129 t.throws(() => {117- execaMethod('noop.js', getOptions('foobar'));130+ execaMethod('empty.js', getStdio(index, 'foobar'));131 }, {message: /must be used/});132 };133 121-test('stdin must be an object when it is a file path string', testFilePathObject, getStdinOption, execa);122-test('stdout must be an object when it is a file path string', testFilePathObject, getStdoutOption, execa);123-test('stderr must be an object when it is a file path string', testFilePathObject, getStderrOption, execa);124-test('stdio[*] must be an object when it is a file path string', testFilePathObject, getStdioOption, execa);125-test('stdin be an object when it is a file path string - sync', testFilePathObject, getStdinOption, execaSync);126-test('stdout be an object when it is a file path string - sync', testFilePathObject, getStdoutOption, execaSync);127-test('stderr be an object when it is a file path string - sync', testFilePathObject, getStderrOption, execaSync);128-test('stdio[*] must be an object when it is a file path string - sync', testFilePathObject, getStdioOption, execaSync);134+test('stdin must be an object when it is a file path string', testFilePathObject, 0, execa);135+test('stdout must be an object when it is a file path string', testFilePathObject, 1, execa);136+test('stderr must be an object when it is a file path string', testFilePathObject, 2, execa);137+test('stdio[*] must be an object when it is a file path string', testFilePathObject, 3, execa);138+test('stdin be an object when it is a file path string - sync', testFilePathObject, 0, execaSync);139+test('stdout be an object when it is a file path string - sync', testFilePathObject, 1, execaSync);140+test('stderr be an object when it is a file path string - sync', testFilePathObject, 2, execaSync);141+test('stdio[*] must be an object when it is a file path string - sync', testFilePathObject, 3, execaSync);142 130-const testFileError = async (t, mapFile, getOptions) => {143+const testFileError = async (t, mapFile, index) => {144 await t.throwsAsync(132- execa('noop.js', getOptions(mapFile('./unknown/file'))),145+ execa('empty.js', getStdio(index, mapFile('./unknown/file'))),146 {code: 'ENOENT'},147 );148 };149 137-test('inputFile file URL errors should be handled', testFileError, pathToFileURL, getInputFileOption);138-test('stdin file URL errors should be handled', testFileError, pathToFileURL, getStdinOption);139-test('stdout file URL errors should be handled', testFileError, pathToFileURL, getStdoutOption);140-test('stderr file URL errors should be handled', testFileError, pathToFileURL, getStderrOption);141-test('stdio[*] file URL errors should be handled', testFileError, pathToFileURL, getStdioOption);142-test('inputFile file path errors should be handled', testFileError, identity, getInputFileOption);143-test('stdin file path errors should be handled', testFileError, getAbsolutePath, getStdinOption);144-test('stdout file path errors should be handled', testFileError, getAbsolutePath, getStdoutOption);145-test('stderr file path errors should be handled', testFileError, getAbsolutePath, getStderrOption);146-test('stdio[*] file path errors should be handled', testFileError, getAbsolutePath, getStdioOption);150+test('inputFile file URL errors should be handled', testFileError, pathToFileURL, 'inputFile');151+test('stdin file URL errors should be handled', testFileError, pathToFileURL, 0);152+test('stdout file URL errors should be handled', testFileError, pathToFileURL, 1);153+test('stderr file URL errors should be handled', testFileError, pathToFileURL, 2);154+test('stdio[*] file URL errors should be handled', testFileError, pathToFileURL, 3);155+test('inputFile file path errors should be handled', testFileError, identity, 'inputFile');156+test('stdin file path errors should be handled', testFileError, getAbsolutePath, 0);157+test('stdout file path errors should be handled', testFileError, getAbsolutePath, 1);158+test('stderr file path errors should be handled', testFileError, getAbsolutePath, 2);159+test('stdio[*] file path errors should be handled', testFileError, getAbsolutePath, 3);160 148-const testFileErrorSync = (t, mapFile, getOptions) => {161+const testFileErrorSync = (t, mapFile, index) => {162 t.throws(() => {150- execaSync('noop.js', getOptions(mapFile('./unknown/file')));163+ execaSync('empty.js', getStdio(index, mapFile('./unknown/file')));164 }, {code: 'ENOENT'});165 };166 154-test('inputFile file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, getInputFileOption);155-test('stdin file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, getStdinOption);156-test('stdout file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, getStdoutOption);157-test('stderr file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, getStderrOption);158-test('stdio[*] file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, getStdioOption);159-test('inputFile file path errors should be handled - sync', testFileErrorSync, identity, getInputFileOption);160-test('stdin file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, getStdinOption);161-test('stdout file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, getStdoutOption);162-test('stderr file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, getStderrOption);163-test('stdio[*] file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, getStdioOption);167+test('inputFile file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 'inputFile');168+test('stdin file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 0);169+test('stdout file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 1);170+test('stderr file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 2);171+test('stdio[*] file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 3);172+test('inputFile file path errors should be handled - sync', testFileErrorSync, identity, 'inputFile');173+test('stdin file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 0);174+test('stdout file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 1);175+test('stderr file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 2);176+test('stdio[*] file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 3);177 165-const testInputFile = async (t, execaMethod) => {166- const inputFile = tempfile();167- await writeFile(inputFile, 'foobar');168- const {stdout} = await execaMethod('stdin.js', {inputFile});169- t.is(stdout, 'foobar');170- await rm(inputFile);171-};172-173-test('inputFile can be set', testInputFile, execa);174-test('inputFile can be set - sync', testInputFile, execa);175-176-const testInputFileScript = async (t, getExecaMethod) => {177- const inputFile = tempfile();178- await writeFile(inputFile, 'foobar');179- const {stdout} = await getExecaMethod($({inputFile}))`stdin.js`;180- t.is(stdout, 'foobar');181- await rm(inputFile);182-};183-184-test('inputFile can be set with $', testInputFileScript, identity);185-test('inputFile can be set with $.sync', testInputFileScript, getScriptSync);186-187-const testMultipleInputs = async (t, allGetOptions, execaMethod) => {178+const testMultipleInputs = async (t, indices, execaMethod) => {179 const filePath = tempfile();180 await writeFile(filePath, 'foobar');190- const options = Object.assign({}, ...allGetOptions.map(getOptions => getOptions(filePath)));181+ const options = Object.assign({}, ...indices.map(index => getStdioInput(index, filePath)));182 const {stdout} = await execaMethod('stdin.js', options);192- t.is(stdout, 'foobar'.repeat(allGetOptions.length));183+ t.is(stdout, 'foobar'.repeat(indices.length));184 await rm(filePath);185 };186 196-const getStringInput = () => ({input: 'foobar'});197-const getBinaryInput = () => ({input: binaryFoobar});198-199-test('input String and inputFile can be both set', testMultipleInputs, [getInputFileOption, getStringInput], execa);200-test('input String and stdin can be both set', testMultipleInputs, [getStdinFilePath, getStringInput], execa);201-test('input Uint8Array and inputFile can be both set', testMultipleInputs, [getInputFileOption, getBinaryInput], execa);202-test('input Uint8Array and stdin can be both set', testMultipleInputs, [getStdinFilePath, getBinaryInput], execa);203-test('stdin and inputFile can be both set', testMultipleInputs, [getStdinFilePath, getInputFileOption], execa);204-test('input String, stdin and inputFile can be all set', testMultipleInputs, [getInputFileOption, getStdinFilePath, getStringInput], execa);205-test('input Uint8Array, stdin and inputFile can be all set', testMultipleInputs, [getInputFileOption, getStdinFilePath, getBinaryInput], execa);206-test('input String and inputFile can be both set - sync', testMultipleInputs, [getInputFileOption, getStringInput], execaSync);207-test('input String and stdin can be both set - sync', testMultipleInputs, [getStdinFilePath, getStringInput], execaSync);208-test('input Uint8Array and inputFile can be both set - sync', testMultipleInputs, [getInputFileOption, getBinaryInput], execaSync);209-test('input Uint8Array and stdin can be both set - sync', testMultipleInputs, [getStdinFilePath, getBinaryInput], execaSync);210-test('stdin and inputFile can be both set - sync', testMultipleInputs, [getStdinFilePath, getInputFileOption], execaSync);211-test('input String, stdin and inputFile can be all set - sync', testMultipleInputs, [getInputFileOption, getStdinFilePath, getStringInput], execaSync);212-test('input Uint8Array, stdin and inputFile can be all set - sync', testMultipleInputs, [getInputFileOption, getStdinFilePath, getBinaryInput], execaSync);187+test('inputFile can be set', testMultipleInputs, ['inputFile'], runExeca);188+test('inputFile can be set - sync', testMultipleInputs, ['inputFile'], runExecaSync);189+test('inputFile can be set with $', testMultipleInputs, ['inputFile'], runScript);190+test('inputFile can be set with $.sync', testMultipleInputs, ['inputFile'], runScriptSync);191+test('input String and inputFile can be both set', testMultipleInputs, ['inputFile', 'string'], execa);192+test('input String and stdin can be both set', testMultipleInputs, [0, 'string'], execa);193+test('input Uint8Array and inputFile can be both set', testMultipleInputs, ['inputFile', 'binary'], execa);194+test('input Uint8Array and stdin can be both set', testMultipleInputs, [0, 'binary'], execa);195+test('stdin and inputFile can be both set', testMultipleInputs, [0, 'inputFile'], execa);196+test('input String, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'string'], execa);197+test('input Uint8Array, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'binary'], execa);198+test('input String and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'string'], execaSync);199+test('input String and stdin can be both set - sync', testMultipleInputs, [0, 'string'], execaSync);200+test('input Uint8Array and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'binary'], execaSync);201+test('input Uint8Array and stdin can be both set - sync', testMultipleInputs, [0, 'binary'], execaSync);202+test('stdin and inputFile can be both set - sync', testMultipleInputs, [0, 'inputFile'], execaSync);203+test('input String, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'string'], execaSync);204+test('input Uint8Array, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'binary'], execaSync);modified:test/stdio/input.js+9 added-15 removed
1 import {Buffer} from 'node:buffer';2 import {Writable} from 'node:stream';3 import test from 'ava';4-import {execa, execaSync, $} from '../../index.js';4+import {execa, execaSync} from '../../index.js';5 import {setFixtureDir} from '../helpers/fixtures-dir.js';6-import {getScriptSync, identity} from '../helpers/stdio.js';6+import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';7 8 setFixtureDir();9 10 const textEncoder = new TextEncoder();7 unmodified lines18 const {stdout} = await execaMethod('stdin.js', {input});19 t.is(stdout, 'foobar');20 };21 22-test('input option can be a String', testInput, 'foobar', execa);23-test('input option can be a String - sync', testInput, 'foobar', execaSync);24-test('input option can be a Uint8Array', testInput, binaryFoobar, execa);25-test('input option can be a Uint8Array - sync', testInput, binaryFoobar, execaSync);22+test('input option can be a String', testInput, 'foobar', runExeca);23+test('input option can be a Uint8Array', testInput, binaryFoobar, runExeca);24+test('input option can be a String - sync', testInput, 'foobar', runExecaSync);25+test('input option can be a Uint8Array - sync', testInput, binaryFoobar, runExecaSync);26+test('input option can be used with $', testInput, 'foobar', runScript);27+test('input option can be used with $.sync', testInput, 'foobar', runScriptSync);28 27-const testInputScript = async (t, getExecaMethod) => {28- const {stdout} = await getExecaMethod($({input: 'foobar'}))`stdin.js`;29- t.is(stdout, 'foobar');30-};31-32-test('input option can be used with $', testInputScript, identity);33-test('input option can be used with $.sync', testInputScript, getScriptSync);34-29 const testInvalidInput = async (t, input, execaMethod) => {30 t.throws(() => {37- execaMethod('noop.js', {input});31+ execaMethod('empty.js', {input});32 }, {message: /a string, a Uint8Array/});33 };34 35 test('input option cannot be a Buffer', testInvalidInput, bufferFoobar, execa);15 unmodified linesmodified:test/stdio/iterable.js+30 added-30 removed
1 import {once} from 'node:events';2 import test from 'ava';3 import {execa, execaSync} from '../../index.js';4 import {setFixtureDir} from '../helpers/fixtures-dir.js';5-import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption} from '../helpers/stdio.js';5+import {getStdio} from '../helpers/stdio.js';6 import {stringGenerator, binaryGenerator, asyncGenerator, throwingGenerator, infiniteGenerator} from '../helpers/generator.js';7 8 setFixtureDir();9 10-const testIterable = async (t, stdioOption, fixtureName, getOptions) => {11- const {stdout} = await execa(fixtureName, getOptions(stdioOption));10+const testIterable = async (t, stdioOption, index) => {11+ const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, stdioOption));12 t.is(stdout, 'foobar');13 };14 15-test('stdin option can be an iterable of strings', testIterable, stringGenerator(), 'stdin.js', getStdinOption);16-test('stdio[*] option can be an iterable of strings', testIterable, stringGenerator(), 'stdin-fd3.js', getStdioOption);17-test('stdin option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 'stdin.js', getStdinOption);18-test('stdio[*] option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 'stdin-fd3.js', getStdioOption);19-test('stdin option can be an async iterable', testIterable, asyncGenerator(), 'stdin.js', getStdinOption);20-test('stdio[*] option can be an async iterable', testIterable, asyncGenerator(), 'stdin-fd3.js', getStdioOption);15+test('stdin option can be an iterable of strings', testIterable, stringGenerator(), 0);16+test('stdio[*] option can be an iterable of strings', testIterable, stringGenerator(), 3);17+test('stdin option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 0);18+test('stdio[*] option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 3);19+test('stdin option can be an async iterable', testIterable, asyncGenerator(), 0);20+test('stdio[*] option can be an async iterable', testIterable, asyncGenerator(), 3);21 22-const testIterableSync = (t, stdioOption, fixtureName, getOptions) => {22+const testIterableSync = (t, stdioOption, index) => {23 t.throws(() => {24- execaSync(fixtureName, getOptions(stdioOption));24+ execaSync('empty.js', getStdio(index, stdioOption));25 }, {message: /an iterable in sync mode/});26 };27 28-test('stdin option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 'stdin.js', getStdinOption);29-test('stdio[*] option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 'stdin-fd3.js', getStdioOption);30-test('stdin option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 'stdin.js', getStdinOption);31-test('stdio[*] option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 'stdin-fd3.js', getStdioOption);28+test('stdin option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 0);29+test('stdio[*] option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 3);30+test('stdin option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 0);31+test('stdio[*] option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 3);32 33-const testIterableError = async (t, fixtureName, getOptions) => {34- const {originalMessage} = await t.throwsAsync(execa(fixtureName, getOptions(throwingGenerator())));33+const testIterableError = async (t, index) => {34+ const {originalMessage} = await t.throwsAsync(execa('stdin-fd.js', [`${index}`], getStdio(index, throwingGenerator())));35 t.is(originalMessage, 'generator error');36 };37 38-test('stdin option handles errors in iterables', testIterableError, 'stdin.js', getStdinOption);39-test('stdio[*] option handles errors in iterables', testIterableError, 'stdin-fd3.js', getStdioOption);38+test('stdin option handles errors in iterables', testIterableError, 0);39+test('stdio[*] option handles errors in iterables', testIterableError, 3);40 41-const testNoIterableOutput = (t, getOptions, execaMethod) => {41+const testNoIterableOutput = (t, index, execaMethod) => {42 t.throws(() => {43- execaMethod('noop.js', getOptions(stringGenerator()));43+ execaMethod('empty.js', getStdio(index, stringGenerator()));44 }, {message: /cannot be an iterable/});45 };46 47-test('stdout option cannot be an iterable', testNoIterableOutput, getStdoutOption, execa);48-test('stderr option cannot be an iterable', testNoIterableOutput, getStderrOption, execa);49-test('stdout option cannot be an iterable - sync', testNoIterableOutput, getStdoutOption, execaSync);50-test('stderr option cannot be an iterable - sync', testNoIterableOutput, getStderrOption, execaSync);47+test('stdout option cannot be an iterable', testNoIterableOutput, 1, execa);48+test('stderr option cannot be an iterable', testNoIterableOutput, 2, execa);49+test('stdout option cannot be an iterable - sync', testNoIterableOutput, 1, execaSync);50+test('stderr option cannot be an iterable - sync', testNoIterableOutput, 2, execaSync);51 52 test('stdin option can be an infinite iterable', async t => {53 const {iterable, abort} = infiniteGenerator();54 try {55- const childProcess = execa('stdin.js', getStdinOption(iterable));55+ const childProcess = execa('stdin.js', getStdio(0, iterable));56 const stdout = await once(childProcess.stdout, 'data');57 t.is(stdout.toString(), 'foo');58 childProcess.kill('SIGKILL');59 await t.throwsAsync(childProcess, {message: /SIGKILL/});1 unmodified line61 abort();62 }63 });64 65-const testMultipleIterable = async (t, fixtureName, getOptions) => {66- const {stdout} = await execa(fixtureName, getOptions([stringGenerator(), asyncGenerator()]));65+const testMultipleIterable = async (t, index) => {66+ const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [stringGenerator(), asyncGenerator()]));67 t.is(stdout, 'foobarfoobar');68 };69 70-test('stdin option can be multiple iterables', testMultipleIterable, 'stdin.js', getStdinOption);71-test('stdio[*] option can be multiple iterables', testMultipleIterable, 'stdin-fd3.js', getStdioOption);70+test('stdin option can be multiple iterables', testMultipleIterable, 0);71+test('stdio[*] option can be multiple iterables', testMultipleIterable, 3);modified:test/stdio/node-stream.js+38 added-37 removed
4 unmodified lines5 import test from 'ava';6 import tempfile from 'tempfile';7 import {execa, execaSync} from '../../index.js';8 import {setFixtureDir} from '../helpers/fixtures-dir.js';9-import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption, getInputOption} from '../helpers/stdio.js';9+import {getStdio} from '../helpers/stdio.js';10 11 setFixtureDir();12 13 const createNoFileReadable = value => {2 unmodified lines16 stream.end();17 return stream;18 };19 20-const testNodeStreamSync = (t, StreamClass, getOptions, optionName) => {20+const testNodeStreamSync = (t, StreamClass, index, optionName) => {21 t.throws(() => {22- execaSync('noop.js', getOptions(new StreamClass()));22+ execaSync('empty.js', getStdio(index, new StreamClass()));23 }, {message: `The \`${optionName}\` option cannot be a Node.js stream in sync mode.`});24 };25 26-test('input cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, getInputOption, 'input');27-test('stdin cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, getStdinOption, 'stdin');28-test('stdio[*] cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, getStdioOption, 'stdio[3]');29-test('stdout cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, getStdoutOption, 'stdout');30-test('stderr cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, getStderrOption, 'stderr');31-test('stdio[*] cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, getStdioOption, 'stdio[3]');26+test('input cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, 'input', 'input');27+test('stdin cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, 0, 'stdin');28+test('stdio[*] cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, 3, 'stdio[3]');29+test('stdout cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, 1, 'stdout');30+test('stderr cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, 2, 'stderr');31+test('stdio[*] cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, 3, 'stdio[3]');32 33 test('input can be a Node.js Readable without a file descriptor', async t => {34 const {stdout} = await execa('stdin.js', {input: createNoFileReadable('foobar')});35 t.is(stdout, 'foobar');36 });37 38-const testNoFileStream = async (t, getOptions, StreamClass) => {39- await t.throwsAsync(execa('noop.js', getOptions(new StreamClass())), {code: 'ERR_INVALID_ARG_VALUE'});38+const testNoFileStream = async (t, index, StreamClass) => {39+ await t.throwsAsync(execa('empty.js', getStdio(index, new StreamClass())), {code: 'ERR_INVALID_ARG_VALUE'});40 };41 42-test('stdin cannot be a Node.js Readable without a file descriptor', testNoFileStream, getStdinOption, Readable);43-test('stdout cannot be a Node.js Writable without a file descriptor', testNoFileStream, getStdoutOption, Writable);44-test('stderr cannot be a Node.js Writable without a file descriptor', testNoFileStream, getStderrOption, Writable);45-test('stdio[*] cannot be a Node.js Readable without a file descriptor', testNoFileStream, getStdioOption, Readable);46-test('stdio[*] cannot be a Node.js Writable without a file descriptor', testNoFileStream, getStdioOption, Writable);42+test('stdin cannot be a Node.js Readable without a file descriptor', testNoFileStream, 0, Readable);43+test('stdout cannot be a Node.js Writable without a file descriptor', testNoFileStream, 1, Writable);44+test('stderr cannot be a Node.js Writable without a file descriptor', testNoFileStream, 2, Writable);45+test('stdio[*] cannot be a Node.js Readable without a file descriptor', testNoFileStream, 3, Readable);46+test('stdio[*] cannot be a Node.js Writable without a file descriptor', testNoFileStream, 3, Writable);47 48-const testFileReadable = async (t, fixtureName, getOptions) => {48+const testFileReadable = async (t, index) => {49 const filePath = tempfile();50 await writeFile(filePath, 'foobar');51 const stream = createReadStream(filePath);52 await once(stream, 'open');53 54- const {stdout} = await execa(fixtureName, getOptions(stream));54+ const indexString = index === 'input' ? '0' : `${index}`;55+ const {stdout} = await execa('stdin-fd.js', [indexString], getStdio(index, stream));56 t.is(stdout, 'foobar');57 58 await rm(filePath);59 };60 60-test('input can be a Node.js Readable with a file descriptor', testFileReadable, 'stdin.js', getInputOption);61-test('stdin can be a Node.js Readable with a file descriptor', testFileReadable, 'stdin.js', getStdinOption);62-test('stdio[*] can be a Node.js Readable with a file descriptor', testFileReadable, 'stdin-fd3.js', getStdioOption);61+test('input can be a Node.js Readable with a file descriptor', testFileReadable, 'input');62+test('stdin can be a Node.js Readable with a file descriptor', testFileReadable, 0);63+test('stdio[*] can be a Node.js Readable with a file descriptor', testFileReadable, 3);64 64-const testFileWritable = async (t, getOptions, fixtureName) => {65+const testFileWritable = async (t, index) => {66 const filePath = tempfile();67 const stream = createWriteStream(filePath);68 await once(stream, 'open');69 69- await execa(fixtureName, ['foobar'], getOptions(stream));70- t.is(await readFile(filePath, 'utf8'), 'foobar\n');70+ await execa('noop-fd.js', [`${index}`, 'foobar'], getStdio(index, stream));71+ t.is(await readFile(filePath, 'utf8'), 'foobar');72 73 await rm(filePath);74 };75 75-test('stdout can be a Node.js Writable with a file descriptor', testFileWritable, getStdoutOption, 'noop.js');76-test('stderr can be a Node.js Writable with a file descriptor', testFileWritable, getStderrOption, 'noop-err.js');77-test('stdio[*] can be a Node.js Writable with a file descriptor', testFileWritable, getStdioOption, 'noop-fd3.js');76+test('stdout can be a Node.js Writable with a file descriptor', testFileWritable, 1);77+test('stderr can be a Node.js Writable with a file descriptor', testFileWritable, 2);78+test('stdio[*] can be a Node.js Writable with a file descriptor', testFileWritable, 3);79 79-const testLazyFileReadable = async (t, fixtureName, getOptions) => {80+const testLazyFileReadable = async (t, index) => {81 const filePath = tempfile();82 await writeFile(filePath, 'foobar');83 const stream = createReadStream(filePath);84 84- const {stdout} = await execa(fixtureName, getOptions([stream, 'pipe']));85+ const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [stream, 'pipe']));86 t.is(stdout, 'foobar');87 88 await rm(filePath);89 };90 90-test('stdin can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 'stdin.js', getStdinOption);91-test('stdio[*] can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 'stdin-fd3.js', getStdioOption);91+test('stdin can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 0);92+test('stdio[*] can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 3);93 93-const testLazyFileWritable = async (t, getOptions, fixtureName) => {94+const testLazyFileWritable = async (t, index) => {95 const filePath = tempfile();96 const stream = createWriteStream(filePath);97 97- await execa(fixtureName, ['foobar'], getOptions([stream, 'pipe']));98- t.is(await readFile(filePath, 'utf8'), 'foobar\n');98+ await execa('noop-fd.js', [`${index}`, 'foobar'], getStdio(index, [stream, 'pipe']));99+ t.is(await readFile(filePath, 'utf8'), 'foobar');100 101 await rm(filePath);102 };103 103-test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, getStdoutOption, 'noop.js');104-test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, getStderrOption, 'noop-err.js');105-test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, getStdioOption, 'noop-fd3.js');104+test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 1);105+test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 2);106+test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 3);modified:test/stdio/typed-array.js+13 added-13 removed
1 import test from 'ava';2 import {execa, execaSync} from '../../index.js';3 import {setFixtureDir} from '../helpers/fixtures-dir.js';4-import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption} from '../helpers/stdio.js';4+import {getStdio} from '../helpers/stdio.js';5 6 setFixtureDir();7 8 const uint8ArrayFoobar = new TextEncoder().encode('foobar');9 10-const testUint8Array = async (t, fixtureName, getOptions) => {11- const {stdout} = await execa(fixtureName, getOptions(uint8ArrayFoobar));10+const testUint8Array = async (t, index) => {11+ const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, uint8ArrayFoobar));12 t.is(stdout, 'foobar');13 };14 15-test('stdin option can be a Uint8Array', testUint8Array, 'stdin.js', getStdinOption);16-test('stdio[*] option can be a Uint8Array', testUint8Array, 'stdin-fd3.js', getStdioOption);17-test('stdin option can be a Uint8Array - sync', testUint8Array, 'stdin.js', getStdinOption);18-test('stdio[*] option can be a Uint8Array - sync', testUint8Array, 'stdin-fd3.js', getStdioOption);15+test('stdin option can be a Uint8Array', testUint8Array, 0);16+test('stdio[*] option can be a Uint8Array', testUint8Array, 3);17+test('stdin option can be a Uint8Array - sync', testUint8Array, 0);18+test('stdio[*] option can be a Uint8Array - sync', testUint8Array, 3);19 20-const testNoUint8ArrayOutput = (t, getOptions, execaMethod) => {20+const testNoUint8ArrayOutput = (t, index, execaMethod) => {21 t.throws(() => {22- execaMethod('noop.js', getOptions(uint8ArrayFoobar));22+ execaMethod('empty.js', getStdio(index, uint8ArrayFoobar));23 }, {message: /cannot be a Uint8Array/});24 };25 26-test('stdout option cannot be a Uint8Array', testNoUint8ArrayOutput, getStdoutOption, execa);27-test('stderr option cannot be a Uint8Array', testNoUint8ArrayOutput, getStderrOption, execa);28-test('stdout option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, getStdoutOption, execaSync);29-test('stderr option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, getStderrOption, execaSync);26+test('stdout option cannot be a Uint8Array', testNoUint8ArrayOutput, 1, execa);27+test('stderr option cannot be a Uint8Array', testNoUint8ArrayOutput, 2, execa);28+test('stdout option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, 1, execaSync);29+test('stderr option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, 2, execaSync);modified:test/stdio/web-stream.js+28 added-28 removed
1 unmodified line2 import {setTimeout} from 'node:timers/promises';3 import test from 'ava';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDir} from '../helpers/fixtures-dir.js';6-import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption} from '../helpers/stdio.js';6+import {getStdio} from '../helpers/stdio.js';7 8 setFixtureDir();9 10-const testReadableStream = async (t, fixtureName, getOptions) => {10+const testReadableStream = async (t, index) => {11 const readableStream = Readable.toWeb(Readable.from('foobar'));12- const {stdout} = await execa(fixtureName, getOptions(readableStream));12+ const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, readableStream));13 t.is(stdout, 'foobar');14 };15 16-test('stdin can be a ReadableStream', testReadableStream, 'stdin.js', getStdinOption);17-test('stdio[*] can be a ReadableStream', testReadableStream, 'stdin-fd3.js', getStdioOption);16+test('stdin can be a ReadableStream', testReadableStream, 0);17+test('stdio[*] can be a ReadableStream', testReadableStream, 3);18 19-const testWritableStream = async (t, fixtureName, getOptions) => {19+const testWritableStream = async (t, index) => {20 const result = [];21 const writableStream = new WritableStream({22 write(chunk) {23 result.push(chunk);24 },25 });26- await execa(fixtureName, ['foobar'], getOptions(writableStream));27- t.is(result.join(''), 'foobar\n');26+ await execa('noop-fd.js', [`${index}`, 'foobar'], getStdio(index, writableStream));27+ t.is(result.join(''), 'foobar');28 };29 30-test('stdout can be a WritableStream', testWritableStream, 'noop.js', getStdoutOption);31-test('stderr can be a WritableStream', testWritableStream, 'noop-err.js', getStderrOption);32-test('stdio[*] can be a WritableStream', testWritableStream, 'noop-fd3.js', getStdioOption);30+test('stdout can be a WritableStream', testWritableStream, 1);31+test('stderr can be a WritableStream', testWritableStream, 2);32+test('stdio[*] can be a WritableStream', testWritableStream, 3);33 34-const testWebStreamSync = (t, StreamClass, getOptions, optionName) => {34+const testWebStreamSync = (t, StreamClass, index, optionName) => {35 t.throws(() => {36- execaSync('noop.js', getOptions(new StreamClass()));36+ execaSync('empty.js', getStdio(index, new StreamClass()));37 }, {message: `The \`${optionName}\` option cannot be a web stream in sync mode.`});38 };39 40-test('stdin cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, getStdinOption, 'stdin');41-test('stdio[*] cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, getStdioOption, 'stdio[3]');42-test('stdout cannot be a WritableStream - sync', testWebStreamSync, WritableStream, getStdoutOption, 'stdout');43-test('stderr cannot be a WritableStream - sync', testWebStreamSync, WritableStream, getStderrOption, 'stderr');44-test('stdio[*] cannot be a WritableStream - sync', testWebStreamSync, WritableStream, getStdioOption, 'stdio[3]');40+test('stdin cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, 0, 'stdin');41+test('stdio[*] cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, 3, 'stdio[3]');42+test('stdout cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 1, 'stdout');43+test('stderr cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 2, 'stderr');44+test('stdio[*] cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 3, 'stdio[3]');45 46-const testLongWritableStream = async (t, getOptions) => {46+const testLongWritableStream = async (t, index) => {47 let result = false;48 const writableStream = new WritableStream({49 async close() {50 await setTimeout(0);51 result = true;52 },53 });54- await execa('empty.js', getOptions(writableStream));54+ await execa('empty.js', getStdio(index, writableStream));55 t.true(result);56 };57 58-test('stdout waits for WritableStream completion', testLongWritableStream, getStdoutOption);59-test('stderr waits for WritableStream completion', testLongWritableStream, getStderrOption);60-test('stdio[*] waits for WritableStream completion', testLongWritableStream, getStdioOption);58+test('stdout waits for WritableStream completion', testLongWritableStream, 1);59+test('stderr waits for WritableStream completion', testLongWritableStream, 2);60+test('stdio[*] waits for WritableStream completion', testLongWritableStream, 3);61 62-const testWritableStreamError = async (t, getOptions) => {62+const testWritableStreamError = async (t, index) => {63 const writableStream = new WritableStream({64 start(controller) {65 controller.error(new Error('foobar'));66 },67 });68- const {originalMessage} = await t.throwsAsync(execa('noop.js', getOptions(writableStream)));68+ const {originalMessage} = await t.throwsAsync(execa('noop.js', getStdio(index, writableStream)));69 t.is(originalMessage, 'foobar');70 };71 72-test('stdout option handles errors in WritableStream', testWritableStreamError, getStdoutOption);73-test('stderr option handles errors in WritableStream', testWritableStreamError, getStderrOption);74-test('stdio[*] option handles errors in WritableStream', testWritableStreamError, getStdioOption);72+test('stdout option handles errors in WritableStream', testWritableStreamError, 1);73+test('stderr option handles errors in WritableStream', testWritableStreamError, 2);74+test('stdio[*] option handles errors in WritableStream', testWritableStreamError, 3);added:test/encoding.js+121 added
1+import {Buffer} from 'node:buffer';2+import {exec} from 'node:child_process';3+import {promisify} from 'node:util';4+import test from 'ava';5+import {execa, execaSync} from '../index.js';6+import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';7+import {fullStdio} from './helpers/stdio.js';8+9+const pExec = promisify(exec);10+11+setFixtureDir();12+13+const checkEncoding = async (t, encoding, index, execaMethod) => {14+ const {stdio} = await execaMethod('noop-fd.js', [`${index}`, STRING_TO_ENCODE], {...fullStdio, encoding});15+ compareValues(t, stdio[index], encoding);16+17+ if (index === 3) {18+ return;19+ }20+21+ const {stdout, stderr} = await pExec(`node noop-fd.js ${index} ${STRING_TO_ENCODE}`, {encoding, cwd: FIXTURES_DIR});22+ compareValues(t, index === 1 ? stdout : stderr, encoding);23+};24+25+const compareValues = (t, value, encoding) => {26+ if (encoding === 'buffer') {27+ t.true(ArrayBuffer.isView(value));28+ t.true(BUFFER_TO_ENCODE.equals(value));29+ } else {30+ t.is(value, BUFFER_TO_ENCODE.toString(encoding));31+ }32+};33+34+// This string gives different outputs with each encoding type35+const STRING_TO_ENCODE = '\u1000.';36+const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);37+38+/* eslint-disable unicorn/text-encoding-identifier-case */39+test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);40+test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);41+test('can pass encoding "utf-8" to stdout', checkEncoding, 'utf-8', 1, execa);42+test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);43+test('can pass encoding "utf-16le" to stdout', checkEncoding, 'utf-16le', 1, execa);44+test('can pass encoding "ucs2" to stdout', checkEncoding, 'ucs2', 1, execa);45+test('can pass encoding "ucs-2" to stdout', checkEncoding, 'ucs-2', 1, execa);46+test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);47+test('can pass encoding "binary" to stdout', checkEncoding, 'binary', 1, execa);48+test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);49+test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);50+test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);51+test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);52+test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);53+test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);54+test('can pass encoding "utf-8" to stderr', checkEncoding, 'utf-8', 2, execa);55+test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);56+test('can pass encoding "utf-16le" to stderr', checkEncoding, 'utf-16le', 2, execa);57+test('can pass encoding "ucs2" to stderr', checkEncoding, 'ucs2', 2, execa);58+test('can pass encoding "ucs-2" to stderr', checkEncoding, 'ucs-2', 2, execa);59+test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);60+test('can pass encoding "binary" to stderr', checkEncoding, 'binary', 2, execa);61+test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);62+test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);63+test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);64+test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);65+test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);66+test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);67+test('can pass encoding "utf-8" to stdio[*]', checkEncoding, 'utf-8', 3, execa);68+test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);69+test('can pass encoding "utf-16le" to stdio[*]', checkEncoding, 'utf-16le', 3, execa);70+test('can pass encoding "ucs2" to stdio[*]', checkEncoding, 'ucs2', 3, execa);71+test('can pass encoding "ucs-2" to stdio[*]', checkEncoding, 'ucs-2', 3, execa);72+test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);73+test('can pass encoding "binary" to stdio[*]', checkEncoding, 'binary', 3, execa);74+test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);75+test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);76+test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);77+test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);78+test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);79+test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);80+test('can pass encoding "utf-8" to stdout - sync', checkEncoding, 'utf-8', 1, execaSync);81+test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);82+test('can pass encoding "utf-16le" to stdout - sync', checkEncoding, 'utf-16le', 1, execaSync);83+test('can pass encoding "ucs2" to stdout - sync', checkEncoding, 'ucs2', 1, execaSync);84+test('can pass encoding "ucs-2" to stdout - sync', checkEncoding, 'ucs-2', 1, execaSync);85+test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);86+test('can pass encoding "binary" to stdout - sync', checkEncoding, 'binary', 1, execaSync);87+test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);88+test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);89+test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);90+test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);91+test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);92+test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);93+test('can pass encoding "utf-8" to stderr - sync', checkEncoding, 'utf-8', 2, execaSync);94+test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);95+test('can pass encoding "utf-16le" to stderr - sync', checkEncoding, 'utf-16le', 2, execaSync);96+test('can pass encoding "ucs2" to stderr - sync', checkEncoding, 'ucs2', 2, execaSync);97+test('can pass encoding "ucs-2" to stderr - sync', checkEncoding, 'ucs-2', 2, execaSync);98+test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);99+test('can pass encoding "binary" to stderr - sync', checkEncoding, 'binary', 2, execaSync);100+test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);101+test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);102+test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);103+test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);104+test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);105+test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);106+test('can pass encoding "utf-8" to stdio[*] - sync', checkEncoding, 'utf-8', 3, execaSync);107+test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);108+test('can pass encoding "utf-16le" to stdio[*] - sync', checkEncoding, 'utf-16le', 3, execaSync);109+test('can pass encoding "ucs2" to stdio[*] - sync', checkEncoding, 'ucs2', 3, execaSync);110+test('can pass encoding "ucs-2" to stdio[*] - sync', checkEncoding, 'ucs-2', 3, execaSync);111+test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);112+test('can pass encoding "binary" to stdio[*] - sync', checkEncoding, 'binary', 3, execaSync);113+test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);114+test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);115+test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);116+test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);117+/* eslint-enable unicorn/text-encoding-identifier-case */118+119+test('validate unknown encodings', async t => {120+ await t.throwsAsync(execa('noop.js', {encoding: 'unknownEncoding'}), {code: 'ERR_UNKNOWN_ENCODING'});121+});modified:test/error.js+65 added-22 removed
1 import process from 'node:process';2 import test from 'ava';3 import {execa, execaSync} from '../index.js';4 import {FIXTURES_DIR, setFixtureDir} from './helpers/fixtures-dir.js';5+import {fullStdio} from './helpers/stdio.js';6 7 const isWindows = process.platform === 'win32';8 9 setFixtureDir();10 11 const TIMEOUT_REGEXP = /timed out after/;12 12-const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);13+test('empty error.stdout/stderr/stdio', async t => {14+ const {stdout, stderr, stdio} = await t.throwsAsync(execa('fail.js'));15+ t.is(stdout, '');16+ t.is(stderr, '');17+ t.deepEqual(stdio, ['', '', '']);18+});19 14-test('stdout/stderr/all available on errors', async t => {15- const {stdout, stderr, all} = await t.throwsAsync(execa('exit.js', ['2'], {all: true}), {message: getExitRegExp('2')});16- t.is(typeof stdout, 'string');17- t.is(typeof stderr, 'string');18- t.is(typeof all, 'string');20+test('empty error.all', async t => {21+ const {all} = await t.throwsAsync(execa('fail.js', {all: true}));22+ t.is(all, '');23 });24 25+test('undefined error.all', async t => {26+ const {all} = await t.throwsAsync(execa('fail.js'));27+ t.is(all, undefined);28+});29+30+test('empty error.stdio[0] even with input', async t => {31+ const {stdio} = await t.throwsAsync(execa('fail.js', {input: 'test'}));32+ t.is(stdio[0], '');33+});34+35 const WRONG_COMMAND = isWindows36 ? '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.'37 : '';38 25-test('stdout/stderr/all on process errors', async t => {26- const {stdout, stderr, all} = await t.throwsAsync(execa('wrong command', {all: true}));39+test('stdout/stderr/all/stdio on process errors', async t => {40+ const {stdout, stderr, all, stdio} = await t.throwsAsync(execa('wrong command', {all: true}));41 t.is(stdout, '');42 t.is(stderr, WRONG_COMMAND);43 t.is(all, WRONG_COMMAND);44+ t.deepEqual(stdio, ['', '', WRONG_COMMAND]);45 });46 32-test('stdout/stderr/all on process errors, in sync mode', t => {33- const {stdout, stderr, all} = t.throws(() => {47+test('stdout/stderr/all/stdio on process errors, in sync mode', t => {48+ const {stdout, stderr, all, stdio} = t.throws(() => {49 execaSync('wrong command');50 });51 t.is(stdout, '');52 t.is(stderr, WRONG_COMMAND);53 t.is(all, undefined);54+ t.deepEqual(stdio, ['', '', WRONG_COMMAND]);55 });56 57+test('error.stdout/stderr/stdio is defined', async t => {58+ const {stdout, stderr, stdio} = await t.throwsAsync(execa('echo-fail.js', fullStdio));59+ t.is(stdout, 'stdout');60+ t.is(stderr, 'stderr');61+ t.deepEqual(stdio, ['', 'stdout', 'stderr', 'fd3']);62+});63+64+test('error.stdout/stderr/stdio is defined, in sync mode', t => {65+ const {stdout, stderr, stdio} = t.throws(() => {66+ execaSync('echo-fail.js', fullStdio);67+ });68+ t.is(stdout, 'stdout');69+ t.is(stderr, 'stderr');70+ t.deepEqual(stdio, ['', 'stdout', 'stderr', 'fd3']);71+});72+73 test('exitCode is 0 on success', async t => {74 const {exitCode} = await execa('noop.js', ['foo']);75 t.is(exitCode, 0);76 });77 78 const testExitCode = async (t, number) => {47- const {exitCode} = await t.throwsAsync(execa('exit.js', [`${number}`]), {message: getExitRegExp(number)});79+ const {exitCode} = await t.throwsAsync(execa('exit.js', [`${number}`]), {message: new RegExp(`failed with exit code ${number}`)});80 t.is(exitCode, number);81 };82 83 test('exitCode is 2', testExitCode, 2);3 unmodified lines87 test('error.message contains the command', async t => {88 await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});89 });90 59-test('error.message contains stdout/stderr if available', async t => {60- const {message} = await t.throwsAsync(execa('echo-fail.js'));61- t.true(message.includes('stderr'));62- t.true(message.includes('stdout'));91+test('error.message contains stdout/stderr/stdio if available', async t => {92+ const {message} = await t.throwsAsync(execa('echo-fail.js', fullStdio));93+ t.true(message.endsWith('stderr\nstdout\nfd3'));94 });95 65-test('error.message does not contain stdout/stderr if not available', async t => {96+test('error.message does not contain stdout if not available', async t => {97+ const {message} = await t.throwsAsync(execa('echo-fail.js', {stdio: ['pipe', 'ignore', 'pipe', 'pipe']}));98+ t.true(message.endsWith('stderr\nfd3'));99+});100+101+test('error.message does not contain stderr if not available', async t => {102+ const {message} = await t.throwsAsync(execa('echo-fail.js', {stdio: ['pipe', 'pipe', 'ignore', 'pipe']}));103+ t.true(message.endsWith('stdout\nfd3'));104+});105+106+test('error.message does not contain stdout/stderr/stdio if not available', async t => {107 const {message} = await t.throwsAsync(execa('echo-fail.js', {stdio: 'ignore'}));108 t.false(message.includes('stderr'));109 t.false(message.includes('stdout'));110+ t.false(message.includes('fd3'));111 });112 71-test('error.shortMessage does not contain stdout/stderr', async t => {72- const {shortMessage} = await t.throwsAsync(execa('echo-fail.js'));113+test('error.shortMessage does not contain stdout/stderr/stdio', async t => {114+ const {shortMessage} = await t.throwsAsync(execa('echo-fail.js', fullStdio));115 t.false(shortMessage.includes('stderr'));116 t.false(shortMessage.includes('stdout'));117+ t.false(shortMessage.includes('fd3'));118 });119 120 test('Original error.message is kept', async t => {121 const {originalMessage} = await t.throwsAsync(execa('noop.js', {cwd: 1}));5 unmodified lines127 t.false(failed);128 });129 130 test('failed is true on failure', async t => {88- const {failed} = await t.throwsAsync(execa('exit.js', ['2']));131+ const {failed} = await t.throwsAsync(execa('fail.js'));132 t.true(failed);133 });134 135 test('error.isTerminated is true if process was killed directly', async t => {94 unmodified lines230 t.is(signal, undefined);231 });232 233 test('result.signal is undefined if process failed, but was not killed', async t => {191- const {signal} = await t.throwsAsync(execa('exit.js', [2]), {message: getExitRegExp('2')});234+ const {signal} = await t.throwsAsync(execa('fail.js'));235 t.is(signal, undefined);236 });237 238 test('result.signalDescription is undefined for successful execution', async t => {11 unmodified lines250 t.is(code, 'ERR_INVALID_ARG_TYPE');251 });252 253 test('error.cwd is defined on failure if applicable', async t => {211- const {cwd} = await t.throwsAsync(execa('noop-throw.js', [], {cwd: FIXTURES_DIR}));254+ const {cwd} = await t.throwsAsync(execa('fail.js', [], {cwd: FIXTURES_DIR}));255 t.is(cwd, FIXTURES_DIR);256 });257 258 test('error.cwd is undefined on failure if not passed as options', async t => {259 const expectedCwd = process.cwd();217- const {cwd} = await t.throwsAsync(execa('noop-throw.js'));260+ const {cwd} = await t.throwsAsync(execa('fail.js'));261 t.is(cwd, expectedCwd);262 });modified:test/kill.js+4 added-3 removed
62 unmodified lines63 test('`forceKillAfterTimeout` should not be NaN', testInvalidForceKill, Number.NaN);64 test('`forceKillAfterTimeout` should not be negative', testInvalidForceKill, -1);65 }66 67-test('execa() returns a promise with kill()', t => {68- const {kill} = execa('noop.js', ['foo']);69- t.is(typeof kill, 'function');67+test('execa() returns a promise with kill()', async t => {68+ const subprocess = execa('noop.js', ['foo']);69+ t.is(typeof subprocess.kill, 'function');70+ await subprocess;71 });72 73 test('timeout kills the process if it times out', async t => {74 const {isTerminated, timedOut} = await t.throwsAsync(execa('noop.js', {timeout: 1}), {message: TIMEOUT_REGEXP});229 unmodified linesmodified:test/node.js+5 added
35 unmodified lines36 37 t.is(stdout, 'foo');38 });39 40+test('node does not return ipc channel\'s output', async t => {41+ const {stdio} = await execaNode('test/fixtures/noop.js', ['foo']);42+ t.deepEqual(stdio, [undefined, 'foo', '', undefined]);43+});44+45 test('node correctly use nodePath', async t => {46 const {stdout} = await execaNode(process.platform === 'win32' ? 'hello.cmd' : 'hello.sh', {47 stdout: 'pipe',48 nodePath: process.platform === 'win32' ? 'cmd.exe' : 'bash',72 unmodified linesmodified:test/pipe.js+28 added-28 removed
7 unmodified lines8 import {setFixtureDir} from './helpers/fixtures-dir.js';9 10 setFixtureDir();11 12-const pipeToProcess = async (t, fixtureName, funcName) => {13- const {stdout} = await execa(fixtureName, ['test'], {all: true})[funcName](execa('stdin.js'));12+const pipeToProcess = async (t, index, funcName) => {13+ const {stdout} = await execa('noop-fd.js', [`${index}`, 'test'], {all: true})[funcName](execa('stdin.js'));14 t.is(stdout, 'test');15 };16 17-test('pipeStdout() can pipe to Execa child processes', pipeToProcess, 'noop.js', 'pipeStdout');18-test('pipeStderr() can pipe to Execa child processes', pipeToProcess, 'noop-err.js', 'pipeStderr');19-test('pipeAll() can pipe stdout to Execa child processes', pipeToProcess, 'noop.js', 'pipeAll');20-test('pipeAll() can pipe stderr to Execa child processes', pipeToProcess, 'noop-err.js', 'pipeAll');17+test('pipeStdout() can pipe to Execa child processes', pipeToProcess, 1, 'pipeStdout');18+test('pipeStderr() can pipe to Execa child processes', pipeToProcess, 2, 'pipeStderr');19+test('pipeAll() can pipe stdout to Execa child processes', pipeToProcess, 1, 'pipeAll');20+test('pipeAll() can pipe stderr to Execa child processes', pipeToProcess, 2, 'pipeAll');21 22-const pipeToStream = async (t, fixtureName, funcName, streamName) => {22+const pipeToStream = async (t, index, funcName) => {23 const stream = new PassThrough();24- const result = await execa(fixtureName, ['test'], {all: true})[funcName](stream);25- t.is(result[streamName], 'test');26- t.is(await getStream(stream), 'test\n');24+ const result = await execa('noop-fd.js', [`${index}`, 'test'], {all: true})[funcName](stream);25+ t.is(result.stdio[index], 'test');26+ t.is(await getStream(stream), 'test');27 };28 29-test('pipeStdout() can pipe to streams', pipeToStream, 'noop.js', 'pipeStdout', 'stdout');30-test('pipeStderr() can pipe to streams', pipeToStream, 'noop-err.js', 'pipeStderr', 'stderr');31-test('pipeAll() can pipe stdout to streams', pipeToStream, 'noop.js', 'pipeAll', 'stdout');32-test('pipeAll() can pipe stderr to streams', pipeToStream, 'noop-err.js', 'pipeAll', 'stderr');29+test('pipeStdout() can pipe to streams', pipeToStream, 1, 'pipeStdout');30+test('pipeStderr() can pipe to streams', pipeToStream, 2, 'pipeStderr');31+test('pipeAll() can pipe stdout to streams', pipeToStream, 1, 'pipeAll');32+test('pipeAll() can pipe stderr to streams', pipeToStream, 2, 'pipeAll');33 34-const pipeToFile = async (t, fixtureName, funcName, streamName) => {34+const pipeToFile = async (t, index, funcName) => {35 const file = tempfile();36- const result = await execa(fixtureName, ['test'], {all: true})[funcName](file);37- t.is(result[streamName], 'test');38- t.is(await readFile(file, 'utf8'), 'test\n');36+ const result = await execa('noop-fd.js', [`${index}`, 'test'], {all: true})[funcName](file);37+ t.is(result.stdio[index], 'test');38+ t.is(await readFile(file, 'utf8'), 'test');39 await rm(file);40 };41 42 // `test.serial()` is due to a race condition: `execa(...).pipe*(file)` might resolve before the file stream has resolved43-test.serial('pipeStdout() can pipe to files', pipeToFile, 'noop.js', 'pipeStdout', 'stdout');44-test.serial('pipeStderr() can pipe to files', pipeToFile, 'noop-err.js', 'pipeStderr', 'stderr');45-test.serial('pipeAll() can pipe stdout to files', pipeToFile, 'noop.js', 'pipeAll', 'stdout');46-test.serial('pipeAll() can pipe stderr to files', pipeToFile, 'noop-err.js', 'pipeAll', 'stderr');43+test.serial('pipeStdout() can pipe to files', pipeToFile, 1, 'pipeStdout');44+test.serial('pipeStderr() can pipe to files', pipeToFile, 2, 'pipeStderr');45+test.serial('pipeAll() can pipe stdout to files', pipeToFile, 1, 'pipeAll');46+test.serial('pipeAll() can pipe stderr to files', pipeToFile, 2, 'pipeAll');47 48 const invalidTarget = (t, funcName, getTarget) => {49- t.throws(() => execa('noop.js', {all: true})[funcName](getTarget()), {49+ t.throws(() => execa('empty.js', {all: true})[funcName](getTarget()), {50 message: /a stream or an Execa child process/,51 });52 };53 14 unmodified lines68 test('Must set "stdout" option to "pipe" to use pipeStdout()', invalidSource, 'pipeStdout');69 test('Must set "stderr" option to "pipe" to use pipeStderr()', invalidSource, 'pipeStderr');70 test('Must set "stdout" or "stderr" option to "pipe" to use pipeAll()', invalidSource, 'pipeAll');71 72-const invalidPipeToProcess = async (t, fixtureName, funcName) => {73- t.throws(() => execa(fixtureName, ['test'], {all: true})[funcName](execa('stdin.js', {stdin: 'ignore'})), {72+const invalidPipeToProcess = async (t, index, funcName) => {73+ t.throws(() => execa('noop-fd.js', [`${index}`, 'test'], {all: true})[funcName](execa('stdin.js', {stdin: 'ignore'})), {74 message: /stdin must be available/,75 });76 };77 78-test('Must set target "stdin" option to "pipe" to use pipeStdout()', invalidPipeToProcess, 'noop.js', 'pipeStdout');79-test('Must set target "stdin" option to "pipe" to use pipeStderr()', invalidPipeToProcess, 'noop-err.js', 'pipeStderr');80-test('Must set target "stdin" option to "pipe" to use pipeAll()', invalidPipeToProcess, 'noop.js', 'pipeAll');78+test('Must set target "stdin" option to "pipe" to use pipeStdout()', invalidPipeToProcess, 1, 'pipeStdout');79+test('Must set target "stdin" option to "pipe" to use pipeStderr()', invalidPipeToProcess, 2, 'pipeStderr');80+test('Must set target "stdin" option to "pipe" to use pipeAll()', invalidPipeToProcess, 1, 'pipeAll');modified:test/stream.js+186 added-168 removed
1 import {Buffer} from 'node:buffer';2-import {exec} from 'node:child_process';2 import {once} from 'node:events';3 import process from 'node:process';4 import {setTimeout} from 'node:timers/promises';6-import {promisify} from 'node:util';5 import test from 'ava';6 import getStream from 'get-stream';9-import {pEvent} from 'p-event';7 import {execa, execaSync} from '../index.js';11-import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';8+import {setFixtureDir} from './helpers/fixtures-dir.js';9+import {fullStdio, getStdio} from './helpers/stdio.js';10 13-const pExec = promisify(exec);14-11 setFixtureDir();12 17-const checkEncoding = async (t, encoding) => {18- const {stdout} = await execa('noop-no-newline.js', [STRING_TO_ENCODE], {encoding});19- t.is(stdout, BUFFER_TO_ENCODE.toString(encoding));20-21- const {stdout: nativeStdout} = await pExec(`node noop-no-newline.js ${STRING_TO_ENCODE}`, {encoding, cwd: FIXTURES_DIR});22- t.is(stdout, nativeStdout);23-};24-25-// This string gives different outputs with each encoding type26-const STRING_TO_ENCODE = '\u1000.';27-const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);28-29-test('can pass encoding "utf8"', checkEncoding, 'utf8');30-test('can pass encoding "utf-8"', checkEncoding, 'utf8');31-test('can pass encoding "utf16le"', checkEncoding, 'utf16le');32-test('can pass encoding "utf-16le"', checkEncoding, 'utf16le');33-test('can pass encoding "ucs2"', checkEncoding, 'utf16le');34-test('can pass encoding "ucs-2"', checkEncoding, 'utf16le');35-test('can pass encoding "latin1"', checkEncoding, 'latin1');36-test('can pass encoding "binary"', checkEncoding, 'latin1');37-test('can pass encoding "ascii"', checkEncoding, 'ascii');38-test('can pass encoding "hex"', checkEncoding, 'hex');39-test('can pass encoding "base64"', checkEncoding, 'base64');40-test('can pass encoding "base64url"', checkEncoding, 'base64url');41-42-const checkBufferEncoding = async (t, execaMethod) => {43- const {stdout} = await execaMethod('noop-no-newline.js', [STRING_TO_ENCODE], {encoding: 'buffer'});44- t.true(ArrayBuffer.isView(stdout));45- t.true(BUFFER_TO_ENCODE.equals(stdout));46-47- const {stdout: nativeStdout} = await pExec(`node noop-no-newline.js ${STRING_TO_ENCODE}`, {encoding: 'buffer', cwd: FIXTURES_DIR});48- t.true(Buffer.isBuffer(nativeStdout));49- t.true(BUFFER_TO_ENCODE.equals(nativeStdout));50-};51-52-test('can pass encoding "buffer"', checkBufferEncoding, execa);53-test('can pass encoding "buffer" - sync', checkBufferEncoding, execaSync);54-55-test('validate unknown encodings', async t => {56- await t.throwsAsync(execa('noop.js', {encoding: 'unknownEncoding'}), {code: 'ERR_UNKNOWN_ENCODING'});57-});58-13 test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {14 const {all} = await execa('noop-132.js', {all: true});15 t.is(all, '132');16 });16 unmodified lines33 34 test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');35 test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');36 83-const testIgnore = async (t, streamName, execaMethod) => {84- const result = await execaMethod('noop.js', {[streamName]: 'ignore'});85- t.is(result[streamName], undefined);37+const testIgnore = async (t, index, execaMethod) => {38+ const result = await execaMethod('noop.js', getStdio(index, 'ignore'));39+ t.is(result.stdio[index], undefined);40 };41 88-test('stdout is undefined if ignored', testIgnore, 'stdout', execa);89-test('stderr is undefined if ignored', testIgnore, 'stderr', execa);90-test('stdout is undefined if ignored - sync', testIgnore, 'stdout', execaSync);91-test('stderr is undefined if ignored - sync', testIgnore, 'stderr', execaSync);42+test('stdout is undefined if ignored', testIgnore, 1, execa);43+test('stderr is undefined if ignored', testIgnore, 2, execa);44+test('stdio[*] is undefined if ignored', testIgnore, 3, execa);45+test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);46+test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);47+test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);48 93-const testMaxBuffer = async (t, streamName) => {94- await t.notThrowsAsync(execa('max-buffer.js', [streamName, '10'], {maxBuffer: 10}));95- const {[streamName]: stream, all} = await t.throwsAsync(96- execa('max-buffer.js', [streamName, '11'], {maxBuffer: 10, all: true}),97- {message: new RegExp(`max-buffer.js ${streamName}`)},49+const maxBuffer = 10;50+51+const testMaxBufferSuccess = async (t, index, all) => {52+ await t.notThrowsAsync(execa('max-buffer.js', [`${index}`, `${maxBuffer}`], {...fullStdio, maxBuffer, all}));53+};54+55+test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, 1, false);56+test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, 2, false);57+test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, 3, false);58+test('maxBuffer does not affect all if too high', testMaxBufferSuccess, 1, true);59+60+const testMaxBufferLimit = async (t, index, all) => {61+ const length = all ? maxBuffer * 2 : maxBuffer;62+ const result = await t.throwsAsync(63+ execa('max-buffer.js', [`${index}`, `${length + 1}`], {...fullStdio, maxBuffer, all}),64+ {message: /maxBuffer exceeded/},65 );99- t.is(stream, '.'.repeat(10));100- t.is(all, '.'.repeat(10));66+ t.is(all ? result.all : result.stdio[index], '.'.repeat(length));67 };68 103-test('maxBuffer affects stdout', testMaxBuffer, 'stdout');104-test('maxBuffer affects stderr', testMaxBuffer, 'stderr');69+test('maxBuffer affects stdout', testMaxBufferLimit, 1, false);70+test('maxBuffer affects stderr', testMaxBufferLimit, 2, false);71+test('maxBuffer affects stdio[*]', testMaxBufferLimit, 3, false);72+test('maxBuffer affects all', testMaxBufferLimit, 1, true);73 106-test('maxBuffer works with encoding buffer', async t => {107- const {stdout} = await t.throwsAsync(108- execa('max-buffer.js', ['stdout', '11'], {maxBuffer: 10, encoding: 'buffer'}),74+const testMaxBufferEncoding = async (t, index) => {75+ const result = await t.throwsAsync(76+ execa('max-buffer.js', [`${index}`, `${maxBuffer + 1}`], {...fullStdio, maxBuffer, encoding: 'buffer'}),77 );78+ const stream = result.stdio[index];110- t.true(stdout instanceof Uint8Array);111- t.is(Buffer.from(stdout).toString(), '.'.repeat(10));112-});79+ t.true(stream instanceof Uint8Array);80+ t.is(Buffer.from(stream).toString(), '.'.repeat(maxBuffer));81+};82 114-test('maxBuffer works with other encodings', async t => {115- const {stdout} = await t.throwsAsync(116- execa('max-buffer.js', ['stdout', '11'], {maxBuffer: 10, encoding: 'hex'}),83+test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, 1);84+test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, 2);85+test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, 3);86+87+const testMaxBufferHex = async (t, index) => {88+ const {stdio} = await t.throwsAsync(89+ execa('max-buffer.js', [`${index}`, `${maxBuffer + 1}`], {...fullStdio, maxBuffer, encoding: 'hex'}),90 );118- t.is(stdout, Buffer.from('.'.repeat(10)).toString('hex'));119-});91+ t.is(stdio[index], Buffer.from('.'.repeat(maxBuffer)).toString('hex'));92+};93 121-const testNoMaxBuffer = async (t, streamName) => {122- const promise = execa('max-buffer.js', [streamName, '10'], {buffer: false});94+test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);95+test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);96+test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);97+98+const testNoMaxBuffer = async (t, index) => {99+ const subprocess = execa('max-buffer.js', [`${index}`, `${maxBuffer}`], {...fullStdio, buffer: false});100 const [result, output] = await Promise.all([124- promise,125- getStream(promise[streamName]),101+ subprocess,102+ getStream(subprocess.stdio[index]),103 ]);127-128- t.is(result[streamName], undefined);129- t.is(output, '.........\n');104+ t.is(result.stdio[index], undefined);105+ t.is(output, '.'.repeat(maxBuffer));106 };107 132-test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 'stdout');133-test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 'stderr');108+test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1);109+test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2);110+test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3);111 135-test('do not buffer when streaming and `buffer` is `false`', async t => {136- const {stdout} = execa('max-buffer.js', ['stdout', '21'], {maxBuffer: 10, buffer: false});137- const result = await getStream(stdout);138- t.is(result, '....................\n');139-});112+const testNoMaxBufferOption = async (t, index) => {113+ const length = maxBuffer + 1;114+ const subprocess = execa('max-buffer.js', [`${index}`, `${length}`], {...fullStdio, maxBuffer, buffer: false});115+ const [result, output] = await Promise.all([116+ subprocess,117+ getStream(subprocess.stdio[index]),118+ ]);119+ t.is(result.stdio[index], undefined);120+ t.is(output, '.'.repeat(length));121+};122 141-test('buffers when streaming and `buffer` is `true`', async t => {142- const childProcess = execa('max-buffer.js', ['stdout', '21'], {maxBuffer: 10});123+test('do not hit maxBuffer when `buffer` is `false` with stdout', testNoMaxBufferOption, 1);124+test('do not hit maxBuffer when `buffer` is `false` with stderr', testNoMaxBufferOption, 2);125+test('do not hit maxBuffer when `buffer` is `false` with stdio[*]', testNoMaxBufferOption, 3);126+127+const testMaxBufferAbort = async (t, index) => {128+ const childProcess = execa('max-buffer.js', [`${index}`, `${maxBuffer + 1}`], {...fullStdio, maxBuffer});129 await Promise.all([130 t.throwsAsync(childProcess, {message: /maxBuffer exceeded/}),145- t.throwsAsync(getStream(childProcess.stdout), {code: 'ABORT_ERR'}),131+ t.throwsAsync(getStream(childProcess.stdio[index]), {code: 'ABORT_ERR'}),132 ]);147-});133+};134 135+test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);136+test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);137+test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);138+139 test('buffer: false > promise resolves', async t => {140 await t.notThrowsAsync(execa('noop.js', {buffer: false}));141 });142 153-test('buffer: false > promise resolves when output is big but is not pipable', async t => {154- await t.notThrowsAsync(execa('max-buffer.js', {buffer: false, stdout: 'ignore'}));143+test('buffer: false > promise rejects when process returns non-zero', async t => {144+ const {exitCode} = await t.throwsAsync(execa('fail.js', {buffer: false}));145+ t.is(exitCode, 2);146 });147 157-test('buffer: false > promise resolves when output is big and is read', async t => {158- const subprocess = execa('max-buffer.js', {buffer: false});159- subprocess.stdout.resume();160- subprocess.stderr.resume();161- await t.notThrowsAsync(subprocess);162-});148+const testStreamEnd = async (t, index, buffer) => {149+ const subprocess = execa('wrong command', {...fullStdio, buffer});150+ await Promise.all([151+ t.throwsAsync(subprocess, {message: /wrong command/}),152+ once(subprocess.stdio[index], 'end'),153+ ]);154+};155 164-test('buffer: false > promise resolves when output is big and "all" is used and is read', async t => {165- const subprocess = execa('max-buffer.js', {buffer: false, all: true});166- subprocess.all.resume();167- await t.notThrowsAsync(subprocess);168-});156+test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);157+test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);158+test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);159+test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);160+test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);161+test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);162 170-test('buffer: false > promise rejects when process returns non-zero', async t => {171- const subprocess = execa('fail.js', {buffer: false});172- const {exitCode} = await t.throwsAsync(subprocess);173- t.is(exitCode, 2);174-});163+const testBufferIgnore = async (t, index, all) => {164+ await t.notThrowsAsync(execa('max-buffer.js', [`${index}`], {...getStdio(index, 'ignore'), buffer: false, all}));165+};166 176-test('buffer: false > emits end event when promise is rejected', async t => {177- const subprocess = execa('wrong command', {buffer: false, reject: false});178- await t.notThrowsAsync(Promise.all([subprocess, pEvent(subprocess.stdout, 'end')]));179-});167+test('Process buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);168+test('Process buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);169+test('Process buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);170 171 // This specific behavior does not happen on Windows.172 // Also, on macOS, it randomly happens, which would make those tests randomly fail.173 if (process.platform === 'linux') {184- const testBufferNotRead = async (t, streamArgument, all) => {185- const {timedOut} = await t.throwsAsync(execa('max-buffer.js', [streamArgument], {buffer: false, all, timeout: 1e3}));174+ const testBufferNotRead = async (t, index, all) => {175+ const {timedOut} = await t.throwsAsync(execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all, timeout: 1e3}));176 t.true(timedOut);177 };178 189- test.serial('Process buffers stdout, which prevents exit if not read and buffer is false', testBufferNotRead, 'stdout', false);190- test.serial('Process buffers stderr, which prevents exit if not read and buffer is false', testBufferNotRead, 'stderr', false);191- test.serial('Process buffers all, which prevents exit if not read and buffer is false', testBufferNotRead, 'stdout', true);179+ test.serial('Process buffers stdout, which prevents exit if not read and buffer is false', testBufferNotRead, 1, false);180+ test.serial('Process buffers stderr, which prevents exit if not read and buffer is false', testBufferNotRead, 2, false);181+ test.serial('Process buffers stdio[*], which prevents exit if not read and buffer is false', testBufferNotRead, 3, false);182+ test.serial('Process buffers all, which prevents exit if not read and buffer is false', testBufferNotRead, 1, true);183 193- const testBufferRead = async (t, streamName, streamArgument, all) => {194- const subprocess = execa('max-buffer.js', [streamArgument], {buffer: false, all, timeout: 1e4});195- subprocess[streamName].resume();196- const {timedOut} = await subprocess;197- t.false(timedOut);184+ const testBufferRead = async (t, index, all) => {185+ const subprocess = execa('max-buffer.js', [`${index}`], {...fullStdio, buffer: false, all, timeout: 1e4});186+ const stream = all ? subprocess.all : subprocess.stdio[index];187+ stream.resume();188+ await t.notThrowsAsync(subprocess);189 };190 200- test.serial('Process buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 'stdout', 'stdout', false);201- test.serial('Process buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 'stderr', 'stderr', false);202- test.serial('Process buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 'all', 'stdout', true);191+ test.serial('Process buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);192+ test.serial('Process buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);193+ test.serial('Process buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);194+ test.serial('Process buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);195 }196 205-test('Errors on streams should make the process exit', async t => {206- const childProcess = execa('forever.js');207- childProcess.stdout.destroy();208- await t.throwsAsync(childProcess, {code: 'ERR_STREAM_PREMATURE_CLOSE'});209-});197+const testStreamDestroy = async (t, index) => {198+ const childProcess = execa('forever.js', fullStdio);199+ const error = new Error('test');200+ childProcess.stdio[index].destroy(error);201+ await t.throwsAsync(childProcess, {message: /test/});202+};203 211-test.serial('Process waits on stdin before exiting', async t => {212- const childProcess = execa('stdin.js');213- await setTimeout(1e3);214- childProcess.stdin.end('foobar');215- const {stdout} = await childProcess;216- t.is(stdout, 'foobar');217-});204+test('Destroying stdin should make the process exit', testStreamDestroy, 0);205+test('Destroying stdout should make the process exit', testStreamDestroy, 1);206+test('Destroying stderr should make the process exit', testStreamDestroy, 2);207+test('Destroying stdio[*] should make the process exit', testStreamDestroy, 3);208 219-test.serial('Process buffers stdout before it is read', async t => {220- const childProcess = execa('noop-delay.js', ['foobar']);221- await setTimeout(5e2);222- const {stdout} = await childProcess;223- t.is(stdout, 'foobar');224-});209+const testStreamError = async (t, index) => {210+ const childProcess = execa('forever.js', fullStdio);211+ await setTimeout(0);212+ const error = new Error('test');213+ childProcess.stdio[index].emit('error', error);214+ await t.throwsAsync(childProcess, {message: /test/});215+};216 226-test.serial('Process buffers stdout right away, on successfully exit', async t => {227- const childProcess = execa('noop.js', ['foobar']);228- await setTimeout(1e3);229- const {stdout} = await childProcess;230- t.is(stdout, 'foobar');231-});217+test('Errors on stdin should make the process exit', testStreamError, 0);218+test('Errors on stdout should make the process exit', testStreamError, 1);219+test('Errors on stderr should make the process exit', testStreamError, 2);220+test('Errors on stdio[*] should make the process exit', testStreamError, 3);221 233-test.serial('Process buffers stdout right away, on failure', async t => {234- const childProcess = execa('noop-fail.js', ['foobar'], {reject: false});235- await setTimeout(1e3);222+const testWaitOnStreamEnd = async (t, index) => {223+ const childProcess = execa('stdin-fd.js', [`${index}`], fullStdio);224+ await setTimeout(100);225+ childProcess.stdio[index].end('foobar');226 const {stdout} = await childProcess;227 t.is(stdout, 'foobar');238-});228+};229 240-test('Process buffers stdout right away, even if directly read', async t => {241- const childProcess = execa('noop.js', ['foobar']);242- const data = await once(childProcess.stdout, 'data');230+test.serial('Process waits on stdin before exiting', testWaitOnStreamEnd, 0);231+test.serial('Process waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);232+233+const testBufferExit = async (t, index, fixtureName, reject) => {234+ const childProcess = execa(fixtureName, [`${index}`], {...fullStdio, reject});235+ await setTimeout(100);236+ const {stdio} = await childProcess;237+ t.is(stdio[index], 'foobar');238+};239+240+test.serial('Process buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);241+test.serial('Process buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);242+test.serial('Process buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);243+test.serial('Process buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);244+test.serial('Process buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);245+test.serial('Process buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);246+test.serial('Process buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);247+test.serial('Process buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);248+test.serial('Process buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);249+250+const testBufferDirect = async (t, index) => {251+ const childProcess = execa('noop-fd.js', [`${index}`], fullStdio);252+ const data = await once(childProcess.stdio[index], 'data');253 t.is(data.toString().trim(), 'foobar');244- const {stdout} = await childProcess;245- t.is(stdout, 'foobar');246-});254+ const result = await childProcess;255+ t.is(result.stdio[index], 'foobar');256+};257 258+test('Process buffers stdout right away, even if directly read', testBufferDirect, 1);259+test('Process buffers stderr right away, even if directly read', testBufferDirect, 2);260+test('Process buffers stdio[*] right away, even if directly read', testBufferDirect, 3);261+248-test('childProcess.stdout|stderr must be read right away', async t => {249- const childProcess = execa('noop.js', ['foobar']);250- const {stdout} = await childProcess;251- t.is(stdout, 'foobar');252- t.true(childProcess.stdout.destroyed);253-});262+const testBufferDestroyOnEnd = async (t, index) => {263+ const childProcess = execa('noop-fd.js', [`${index}`], fullStdio);264+ const result = await childProcess;265+ t.is(result.stdio[index], 'foobar');266+ t.true(childProcess.stdio[index].destroyed);267+};268+269+test('childProcess.stdout must be read right away', testBufferDestroyOnEnd, 1);270+test('childProcess.stderr must be read right away', testBufferDestroyOnEnd, 2);271+test('childProcess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);modified:test/test.js+52 added-60 removed
1 import path from 'node:path';2 import process from 'node:process';3-import {setTimeout} from 'node:timers/promises';3 import {fileURLToPath, pathToFileURL} from 'node:url';4 import test from 'ava';5 import isRunning from 'is-running';6 import getNode from 'get-node';7 import which from 'which';8 import {execa, execaSync, execaNode, $} from '../index.js';9 import {setFixtureDir, PATH_KEY, FIXTURES_DIR_URL} from './helpers/fixtures-dir.js';10+import {identity, fullStdio} from './helpers/stdio.js';11+import {stringGenerator} from './helpers/generator.js';12 13 setFixtureDir();14 process.env.FOO = 'foo';15 16 const ENOENT_REGEXP = process.platform === 'win32' ? /failed with exit code 1/ : /spawn.* ENOENT/;17 17-const identity = value => value;18+const testOutput = async (t, index, execaCommand) => {19+ const {stdout, stderr, stdio} = await execaCommand('noop-fd.js', [`${index}`, 'foobar'], fullStdio);20+ t.is(stdio[index], 'foobar');21 19-test('execa()', async t => {20- const {stdout} = await execa('noop.js', ['foo']);21- t.is(stdout, 'foo');22+ if (index === 1) {23+ t.is(stdio[index], stdout);24+ } else if (index === 2) {25+ t.is(stdio[index], stderr);26+ }27+};28+29+test('can return stdout', testOutput, 1, execa);30+test('can return stderr', testOutput, 2, execa);31+test('can return output stdio[*]', testOutput, 3, execa);32+test('can return stdout - sync', testOutput, 1, execaSync);33+test('can return stderr - sync', testOutput, 2, execaSync);34+test('can return output stdio[*] - sync', testOutput, 3, execaSync);35+36+const testNoStdin = async (t, execaCommand) => {37+ const {stdio} = await execaCommand('noop.js', ['foobar']);38+ t.is(stdio[0], undefined);39+};40+41+test('cannot return stdin', testNoStdin, execa);42+test('cannot return stdin - sync', testNoStdin, execaSync);43+44+test('cannot return input stdio[*]', async t => {45+ const {stdio} = await execa('stdin-fd.js', ['3'], {stdio: ['pipe', 'pipe', 'pipe', stringGenerator()]});46+ t.is(stdio[3], undefined);47 });48 49 if (process.platform === 'win32') {50 test('execa() - cmd file', async t => {6 unmodified lines57 t.is(stdout, 'Hello World');58 });59 }60 36-test('execaSync()', t => {37- const {stdout} = execaSync('noop.js', ['foo']);38- t.is(stdout, 'foo');39-});40-41-test('execaSync() throws error if written to stderr', t => {61+test('execaSync() throws error if ENOENT', t => {62 t.throws(() => {63 execaSync('foo');64 }, {message: ENOENT_REGEXP});65 });7 unmodified lines73 const {exitCode} = execaSync('fail.js', {reject: false});74 t.is(exitCode, 2);75 });76 57-test('stripFinalNewline: true', async t => {58- const {stdout} = await execa('noop.js', ['foo']);59- t.is(stdout, 'foo');60-});77+const testStripFinalNewline = async (t, index, stripFinalNewline, execaCommand) => {78+ const {stdio} = await execaCommand('noop-fd.js', [`${index}`, 'foobar\n'], {...fullStdio, stripFinalNewline});79+ t.is(stdio[index], `foobar${stripFinalNewline ? '' : '\n'}`);80+};81 62-test('stripFinalNewline: false', async t => {63- const {stdout} = await execa('noop.js', ['foo'], {stripFinalNewline: false});64- t.is(stdout, 'foo\n');65-});82+test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, undefined, execa);83+test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, execa);84+test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, undefined, execa);85+test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, execa);86+test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, undefined, execa);87+test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, execa);88+test('stripFinalNewline: true with stdout - sync', testStripFinalNewline, 1, undefined, execaSync);89+test('stripFinalNewline: false with stdout - sync', testStripFinalNewline, 1, false, execaSync);90+test('stripFinalNewline: true with stderr - sync', testStripFinalNewline, 2, undefined, execaSync);91+test('stripFinalNewline: false with stderr - sync', testStripFinalNewline, 2, false, execaSync);92+test('stripFinalNewline: true with stdio[*] - sync', testStripFinalNewline, 3, undefined, execaSync);93+test('stripFinalNewline: false with stdio[*] - sync', testStripFinalNewline, 3, false, execaSync);94 67-test('stripFinalNewline on failure', async t => {68- const {stderr} = await t.throwsAsync(execa('noop-throw.js', ['foo'], {stripFinalNewline: true}));69- t.is(stderr, 'foo');70-});71-72-test('stripFinalNewline in sync mode', t => {73- const {stdout} = execaSync('noop.js', ['foo'], {stripFinalNewline: true});74- t.is(stdout, 'foo');75-});76-77-test('stripFinalNewline in sync mode on failure', t => {78- const {stderr} = t.throws(() => {79- execaSync('noop-throw.js', ['foo'], {stripFinalNewline: true});80- });81- t.is(stderr, 'foo');82-});83-95 const getPathWithoutLocalDir = () => {96 const newPath = process.env[PATH_KEY].split(path.delimiter).filter(pathDir => !BIN_DIR_REGEXP.test(pathDir)).join(path.delimiter);97 return {[PATH_KEY]: newPath};98 };36 unmodified lines135 136 test.serial('execPath option', testExecPath, identity);137 test.serial('execPath option can be a file URL', testExecPath, pathToFileURL);138 128-const emitStdinError = async subprocess => {129- await setTimeout(0);130- subprocess.stdin.emit('error', new Error('test'));131-};132-133-test('stdin errors are handled', async t => {134- const subprocess = execa('forever.js');135- await Promise.all([136- t.throwsAsync(subprocess, {message: /test/}),137- emitStdinError(subprocess),138- ]);139-});140-139 test('child process errors are handled', async t => {140 const subprocess = execa('noop.js');141 subprocess.emit('error', new Error('test'));142 await t.throwsAsync(subprocess, {message: /test/});143 });144 147-test('child process errors rejects promise right away', async t => {148- const subprocess = execa('noop.js');149- subprocess.emit('error', new Error('test'));150- await t.throwsAsync(subprocess, {message: /test/});145+test('execa() returns a promise with pid', async t => {146+ const subprocess = execa('noop.js', ['foo']);147+ t.is(typeof subprocess.pid, 'number');148+ await subprocess;149 });150 153-test('execa() returns a promise with pid', t => {154- const {pid} = execa('noop.js', ['foo']);155- t.is(typeof pid, 'number');156-});157-151 test('child_process.spawn() propagated errors have correct shape', t => {152 const subprocess = execa('noop.js', {uid: -1});153 t.notThrows(() => {154 subprocess.catch(() => {});29 unmodified lines184 });185 186 if (process.platform !== 'win32') {187 test('execa() rejects if running non-executable', async t => {195- const subprocess = execa('non-executable.js');196- await t.throwsAsync(subprocess);188+ await t.throwsAsync(execa('non-executable.js'));189 });190 191 test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async t => {192 await t.throwsAsync(execa('non-executable.js', {input: 'Hey!'}), {message: /EACCES/});113 unmodified linesmodified:index.d.ts+12 added-5 removed
239 unmodified lines240 */241 readonly shell?: boolean | string | URL;242 243 /**244- Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `'buffer'`, then `stdout` and `stderr` will be a `Uint8Array` instead of a string.244+ Specify the character encoding used to decode the `stdout`, `stderr` and `stdio` output. If set to `'buffer'`, then `stdout`, `stderr` and `stdio` will be `Uint8Array`s instead of strings.245 246 @default 'utf8'247 */248 readonly encoding?: EncodingType;5 unmodified lines254 */255 readonly timeout?: number;256 257 /**258- Largest amount of data in bytes allowed on `stdout` or `stderr`. Default: 100 MB.258+ Largest amount of data in bytes allowed on `stdout`, `stderr` and `stdio`. Default: 100 MB.259 260 @default 100_000_000261 */262 readonly maxBuffer?: number;165 unmodified lines428 */429 stderr: StdoutStderrType;430 431 /**432+ The output of the process on `stdin`, `stdout`, `stderr` and other file descriptors.433+434+ Items are `undefined` when their corresponding `stdio` option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).435+ */436+ stdio: [undefined, StdoutStderrType, StdoutStderrType, ...Array<StdoutStderrType | undefined>];437+438+ /**439 Whether the process failed to run.440 */441 failed: boolean;442 52 unmodified lines495 export type ExecaError<IsSync extends boolean = boolean, StdoutStderrType extends StdoutStderrAll = string> = {496 /**497 Error message when the child process failed to run. In addition to the underlying error message, it also contains some information related to why the child process errored.498 492- The child process `stderr` then `stdout` are appended to the end, separated with newlines and not interleaved.499+ The child process `stderr`, `stdout` and other file descriptors' output are appended to the end, separated with newlines and not interleaved.500 */501 message: string;502 503 /**497- This is the same as the `message` property except it does not include the child process `stdout`/`stderr`.504+ This is the same as the `message` property except it does not include the child process `stdout`/`stderr`/`stdio`.505 */506 shortMessage: string;507 508 /**502- Original error message. This is the same as the `message` property excluding the child process `stdout`/`stderr` and some additional information added by Execa.509+ Original error message. This is the same as the `message` property excluding the child process `stdout`/`stderr`/`stdio` and some additional information added by Execa.510 511 This is `undefined` unless the child process exited due to an `error` event or a timeout.512 */513 originalMessage?: string;547 unmodified linesmodified:index.js+23 added-36 removed
78 unmodified lines79 80 return {file, args, command, escapedCommand, options};81 };82 83-const handleOutputSync = (options, value, error) => {84- if (Buffer.isBuffer(value)) {85- value = bufferToUint8Array(value);86- }87-88- return handleOutput(options, value, error);89-};90-91-const handleOutput = (options, value, error) => {83+const handleOutput = (options, value) => {84 if (typeof value !== 'string' && !ArrayBuffer.isView(value)) {93- // When `execaSync()` errors, we normalize it to '' to mimic `execa()`94- return error === undefined ? undefined : '';85+ return;86 }87 97- if (options.stripFinalNewline) {98- return stripFinalNewline(value);88+ if (Buffer.isBuffer(value)) {89+ value = bufferToUint8Array(value);90 }91 101- return value;92+ return options.stripFinalNewline ? stripFinalNewline(value) : value;93 };94 95 export function execa(rawFile, rawArgs, rawOptions) {96 const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, rawOptions);97 validateTimeout(options);98 108- const stdioStreams = handleInputAsync(options);99+ const {stdioStreams, stdioLength} = handleInputAsync(options);100 101 let spawned;102 try {103 spawned = childProcess.spawn(file, args, options);1 unmodified line105 // Ensure the returned error is always both a promise and a child process106 const dummySpawned = new childProcess.ChildProcess();107 const errorPromise = Promise.reject(makeError({108 error,118- stdout: '',119- stderr: '',120- all: '',109+ stdio: Array.from({length: stdioLength}),110+ all: options.all ? '' : undefined,111 command,112 escapedCommand,113 options,114 timedOut: false,21 unmodified lines136 137 const handlePromise = async ({spawned, options, context, stdioStreams, command, escapedCommand}) => {138 const [139 [exitCode, signal, error],150- stdoutResult,151- stderrResult,140+ stdioResults,141 allResult,142 ] = await getSpawnedResult(spawned, options, context, stdioStreams);154- const stdout = handleOutput(options, stdoutResult);155- const stderr = handleOutput(options, stderrResult);143+ const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));144 const all = handleOutput(options, allResult);145 146 if (error || exitCode !== 0 || signal !== null) {147 const isCanceled = context.isCanceled || Boolean(options.signal?.aborted);148 const returnedError = makeError({149 error,150 exitCode,151 signal,164- stdout,165- stderr,152+ stdio,153 all,154 command,155 escapedCommand,156 options,11 unmodified lines168 return {169 command,170 escapedCommand,171 exitCode: 0,185- stdout,186- stderr,172+ stdio,173+ stdout: stdio[1],174+ stderr: stdio[2],175 all,176 failed: false,177 timedOut: false,178 isCanceled: false,3 unmodified lines182 183 export function execaSync(rawFile, rawArgs, rawOptions) {184 const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, rawOptions);185 198- const stdioStreams = handleInputSync(options);186+ const {stdioStreams, stdioLength} = handleInputSync(options);187 188 let result;189 try {190 result = childProcess.spawnSync(file, args, options);191 } catch (error) {192 throw makeError({193 error,206- stdout: '',207- stderr: '',208- all: '',194+ stdio: Array.from({length: stdioLength}),195 command,196 escapedCommand,197 options,198 timedOut: false,1 unmodified line200 });201 }202 203 pipeOutputSync(stdioStreams, result);218- const stdout = handleOutputSync(options, result.stdout, result.error);219- const stderr = handleOutputSync(options, result.stderr, result.error);204 205+ const output = result.output || [undefined, undefined, undefined];206+ const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));207+208 if (result.error || result.status !== 0 || result.signal !== null) {209 const error = makeError({223- stdout,224- stderr,210+ stdio,211 error: result.error,212 signal: result.signal,213 exitCode: result.status,214 command,13 unmodified lines228 return {229 command,230 escapedCommand,231 exitCode: 0,246- stdout,247- stderr,232+ stdio,233+ stdout: stdio[1],234+ stderr: stdio[2],235 failed: false,236 timedOut: false,237 isCanceled: false,238 isTerminated: false,80 unmodified linesmodified:index.test-d.ts+16 added
61 unmodified lines62 const unicornsResult = await execaPromise;63 expectType<string>(unicornsResult.command);64 expectType<string>(unicornsResult.escapedCommand);65 expectType<number | undefined>(unicornsResult.exitCode);66+ expectType<undefined>(unicornsResult.stdio[0]);67 expectType<string>(unicornsResult.stdout);68+ expectType<string>(unicornsResult.stdio[1]);69 expectType<string>(unicornsResult.stderr);70+ expectType<string>(unicornsResult.stdio[2]);71+ expectType<string | undefined>(unicornsResult.stdio[3]);72 expectType<string | undefined>(unicornsResult.all);73 expectType<boolean>(unicornsResult.failed);74 expectType<boolean>(unicornsResult.timedOut);75 expectType<boolean>(unicornsResult.isCanceled);5 unmodified lines81 const execaError = error as ExecaError<false>;82 83 expectType<string>(execaError.message);84 expectType<number | undefined>(execaError.exitCode);85+ expectType<undefined>(execaError.stdio[0]);86 expectType<string>(execaError.stdout);87+ expectType<string>(execaError.stdio[1]);88 expectType<string>(execaError.stderr);89+ expectType<string>(execaError.stdio[2]);90+ expectType<string | undefined>(execaError.stdio[3]);91 expectType<string | undefined>(execaError.all);92 expectType<boolean>(execaError.failed);93 expectType<boolean>(execaError.timedOut);94 expectType<boolean>(execaError.isCanceled);10 unmodified lines105 expectType<ExecaSyncReturnValue>(unicornsResult);106 expectType<string>(unicornsResult.command);107 expectType<string>(unicornsResult.escapedCommand);108 expectType<number | undefined>(unicornsResult.exitCode);109+ expectType<undefined>(unicornsResult.stdio[0]);110 expectType<string>(unicornsResult.stdout);111+ expectType<string>(unicornsResult.stdio[1]);112 expectType<string>(unicornsResult.stderr);113+ expectType<string>(unicornsResult.stdio[2]);114+ expectType<string | undefined>(unicornsResult.stdio[3]);115 expectError(unicornsResult.all);116 expectError(unicornsResult.pipeStdout);117 expectError(unicornsResult.pipeStderr);118 expectError(unicornsResult.pipeAll);9 unmodified lines128 129 expectType<ExecaSyncError>(execaError);130 expectType<string>(execaError.message);131 expectType<number | undefined>(execaError.exitCode);132+ expectType<undefined>(execaError.stdio[0]);133 expectType<string>(execaError.stdout);134+ expectType<string>(execaError.stdio[1]);135 expectType<string>(execaError.stderr);136+ expectType<string>(execaError.stdio[2]);137+ expectType<string | undefined>(execaError.stdio[3]);138 expectError(execaError.all);139 expectType<boolean>(execaError.failed);140 expectType<boolean>(execaError.timedOut);141 expectType<boolean>(execaError.isCanceled);572 unmodified linesmodified:readme.md+19 added-11 removed
253 unmodified lines254 255 Like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options):256 - the current Node version and options are used. This can be overridden using the [`nodePath`](#nodepath-for-node-only) and [`nodeOptions`](#nodeoptions-for-node-only) options.257 - the [`shell`](#shell) option cannot be used258-- an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)258+- an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio-1)259 260 #### $\`command\`261 262 Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a [`childProcess`](#childprocess).25 unmodified lines288 ### execaSync(file, arguments?, options?)289 290 Same as [`execa()`](#execacommandcommand-options) but synchronous.291 292-Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`serialization`](#serialization) and [`signal`](#signal). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio) and [`input`](#input) options cannot be a stream nor an iterable.292+Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`serialization`](#serialization) and [`signal`](#signal). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be a stream nor an iterable.293 294 Returns or throws a [`childProcessResult`](#childProcessResult).295 296 ### $.sync\`command\`297 ### $.s\`command\`298 299 Same as [$\`command\`](#command) but synchronous.300 301-Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`serialization`](#serialization) and [`signal`](#signal). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio) and [`input`](#input) options cannot be a stream nor an iterable.301+Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`serialization`](#serialization) and [`signal`](#signal). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be a stream nor an iterable.302 303 Returns or throws a [`childProcessResult`](#childProcessResult).304 305 ### execaCommandSync(command, options?)306 307 Same as [`execaCommand()`](#execacommand-command-options) but synchronous.308 309-Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`serialization`](#serialization) and [`signal`](#signal). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio) and [`input`](#input) options cannot be a stream nor an iterable.309+Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`serialization`](#serialization) and [`signal`](#signal). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be a stream nor an iterable.310 311 Returns or throws a [`childProcessResult`](#childProcessResult).312 313 ### Shell syntax117 unmodified lines431 This is `undefined` if either:432 - the [`all` option](#all-2) is `false` (the default value)433 - both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)434 435+#### stdio436+437+Type: `Array<string | Uint8Array | undefined>`438+439+The output of the process on [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1) and [other file descriptors](#stdio-1).440+441+Items are `undefined` when their corresponding [`stdio`](#stdio-1) option is set to [`'inherit'`, `'ipc'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio).442+443 #### failed444 445 Type: `boolean`446 50 unmodified lines497 Type: `string`498 499 Error message when the child process failed to run. In addition to the [underlying error message](#originalMessage), it also contains some information related to why the child process errored.500 493-The child process [`stderr`](#stderr) then [`stdout`](#stdout) are appended to the end, separated with newlines and not interleaved.501+The child process [`stderr`](#stderr), [`stdout`](#stdout) and other [file descriptors' output](#stdio) are appended to the end, separated with newlines and not interleaved.502 503 #### shortMessage504 505 Type: `string`506 499-This is the same as the [`message` property](#message) except it does not include the child process `stdout`/`stderr`.507+This is the same as the [`message` property](#message) except it does not include the child process [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio).508 509 #### originalMessage510 511 Type: `string | undefined`512 505-Original error message. This is the same as the `message` property excluding the child process `stdout`/`stderr` and some additional information added by Execa.513+Original error message. This is the same as the `message` property excluding the child process [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio) and some additional information added by Execa.514 515 This is `undefined` unless the child process exited due to an `error` event or a timeout.516 517 ### options43 unmodified lines561 Default: `true`562 563 Buffer the output from the spawned process. When set to `false`, you must read the output of [`stdout`](#stdout-1) and [`stderr`](#stderr-1) (or [`all`](#all) if the [`all`](#all-2) option is `true`). Otherwise the returned promise will not be resolved/rejected.564 557-If the spawned process fails, [`error.stdout`](#stdout), [`error.stderr`](#stderr), and [`error.all`](#all) will contain the buffered data.565+If the spawned process fails, [`error.stdout`](#stdout), [`error.stderr`](#stderr), [`error.all`](#all) and [`error.stdio`](#stdio) will contain the buffered data.566 567 #### input568 569 Type: `string | Uint8Array | stream.Readable`136 unmodified lines706 707 Type: `string`\708 Default: `'json'`709 702-Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execaNode()`](#execanodescriptpath-arguments-options):710+Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio-1) option or [`execaNode()`](#execanodescriptpath-arguments-options):711 - `json`: Uses `JSON.stringify()` and `JSON.parse()`.712 - `advanced`: Uses [`v8.serialize()`](https://nodejs.org/api/v8.html#v8_v8_serialize_value)713 714 [More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)32 unmodified lines747 748 Type: `string`\749 Default: `utf8`750 743-Specify the character encoding used to decode the `stdout` and `stderr` output. If set to `'buffer'`, then `stdout` and `stderr` will be a `Uint8Array` instead of a string.751+Specify the character encoding used to decode the [`stdout`](#stdout), [`stderr`](#stderr) and [`stdio`](#stdio) output. If set to `'buffer'`, then `stdout`, `stderr` and `stdio` will be `Uint8Array`s instead of strings.752 753 #### timeout754 755 Type: `number`\5 unmodified lines761 762 Type: `number`\763 Default: `100_000_000` (100 MB)764 757-Largest amount of data in bytes allowed on `stdout` or `stderr`.765+Largest amount of data in bytes allowed on [`stdout`](#stdout), [`stderr`](#stderr) and [`stdio`](#stdio).766 767 #### killSignal768 769 Type: `string | number`\168 unmodified lines