Skip to content
Myr

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

38 files+1013 added−823 removed

modified:lib/stdio/handle.js+1 added-1 removed
modified:lib/stdio/sync.js+2 added-2 removed
modified:lib/error.js+7 added-5 removed
24 unmodified lines
25 return 'failed';26};2728export const makeError = ({29 stdout,30 stderr,29 stdio,30 all,31 error,32 signal,33 exitCode,
2 unmodified lines
36 timedOut,37 isCanceled,38 options: {timeout, cwd = process.cwd()},39}) => {40 stdio = stdio.map(stdioOutput => stdioOutput ?? '');4142 // `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 lines
50 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');5556 if (isError) {57 error.originalMessage = error.message;58 error.message = message;
6 unmodified lines
65 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;7374 if (all !== undefined) {75 error.all = all;
13 unmodified lines
modified:lib/stream.js+8 added-6 removed
33 unmodified lines
34 return error.bufferedData === undefined ? undefined : applyEncoding(error.bufferedData, encoding);35 }36};3738const 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};4243const getStreamPromise = async (stream, {encoding, buffer, maxBuffer}) => {44 if (!stream || !buffer) {45 return;46 }
69 unmodified lines
116 const finalizers = [];117 cleanupOnExit(spawned, cleanup, detached, finalizers);118 const customStreams = getCustomStreams(stdioStreams);119115 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});122123 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 lines
135 } 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 lines
modified:test/fixtures/echo-fail.js+2 added
modified:test/fixtures/max-buffer.js+10 added-4 removed
modified:test/fixtures/nested-multiple-stderr.js+1 added-1 removed
1 unmodified line
2import process from 'node:process';3import {execa} from '../../index.js';45const [options] = process.argv.slice(2);6const result = await execa('noop-err.js', ['foobar'], {stderr: JSON.parse(options)});6const result = await execa('noop-fd.js', ['2', 'foobar'], {stderr: JSON.parse(options)});7process.stdout.write(`nested ${result.stderr}`);
modified:test/fixtures/nested-stdio.js+1 added-1 removed
8 unmodified lines
9 ? [process[optionValue[0]], ...optionValue.slice(1)]10 : optionValue;11const stdio = ['ignore', 'inherit', 'inherit'];12stdio[index] = optionValue;13const childProcess = execa(file, args, {stdio});13const childProcess = execa(file, [`${index}`, ...args], {stdio});1415const shouldPipe = Array.isArray(optionValue) && optionValue.includes('pipe');16const hasPipe = childProcess.stdio[index] !== null;17
9 unmodified lines
modified:test/fixtures/noop-delay.js+3 added-2 removed
1#!/usr/bin/env node2import process from 'node:process';3import {writeSync} from 'node:fs';4import {setTimeout} from 'node:timers/promises';55console.log(process.argv[2]);6await setTimeout((Number(process.argv[3]) || 1) * 1e3);6writeSync(Number(process.argv[2]), 'foobar');7await setTimeout(100);
deleted:test/fixtures/noop-err.js-4 removed
1#!/usr/bin/env node2import process from 'node:process';34console.error(process.argv[2]);
modified:test/fixtures/noop-fail.js+2 added-1 removed
1#!/usr/bin/env node2import process from 'node:process';3import {writeSync} from 'node:fs';44console.log(process.argv[2]);5writeSync(Number(process.argv[2]), 'foobar');6process.exit(2);
added:test/fixtures/noop-fd.js+5 added
1#!/usr/bin/env node2import process from 'node:process';3import {writeSync} from 'node:fs';45writeSync(Number(process.argv[2]), process.argv[3] || 'foobar');
deleted:test/fixtures/noop-fd3.js-6 removed
1#!/usr/bin/env node2import process from 'node:process';3import {writeSync} from 'node:fs';45const fileDescriptorIndex = Number(process.argv[3] || 3);6writeSync(fileDescriptorIndex, `${process.argv[2]}\n`);
deleted:test/fixtures/noop-no-newline.js-4 removed
1#!/usr/bin/env node2import process from 'node:process';34process.stdout.write(process.argv[2]);
deleted:test/fixtures/noop-throw.js-5 removed
1#!/usr/bin/env node2import process from 'node:process';34console.error(process.argv[2]);5process.exit(2);
added:test/fixtures/stdin-fd.js+10 added
1#!/usr/bin/env node2import process from 'node:process';3import {readFileSync} from 'node:fs';45const fileDescriptorIndex = Number(process.argv[2]);6if (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 node2import process from 'node:process';3import {readFileSync} from 'node:fs';45const fileDescriptorIndex = Number(process.argv[2] || 3);6console.log(readFileSync(fileDescriptorIndex, {encoding: 'utf8'}));
added:test/helpers/run.js+6 added
1import {execa, execaSync, $} from '../../index.js';23export const runExeca = (file, options) => execa(file, options);4export const runExecaSync = (file, options) => execaSync(file, options);5export const runScript = (file, options) => $(options)`${file}`;6export const runScriptSync = (file, options) => $(options).sync`${file}`;
modified:test/helpers/stdio.js+15 added-8 removed
1export const getStdinOption = stdioOption => ({stdin: stdioOption});2export const getStdoutOption = stdioOption => ({stdout: stdioOption});3export const getStderrOption = stdioOption => ({stderr: stdioOption});4export const getStdioOption = stdioOption => ({stdio: ['pipe', 'pipe', 'pipe', stdioOption]});5export const getInputOption = input => ({input});6export const getInputFileOption = inputFile => ({inputFile});1import process from 'node:process';28export const getScriptSync = $ => $.sync;93export const identity = value => value;45export const getStdio = (indexOrName, stdioOption) => {6 if (typeof indexOrName === 'string') {7 return {[indexOrName]: stdioOption};8 }910 const stdio = ['pipe', 'pipe', 'pipe'];11 stdio[indexOrName] = stdioOption;12 return {stdio};13};1415export const fullStdio = getStdio(3, 'pipe');1617export const STANDARD_STREAMS = [process.stdin, process.stdout, process.stderr];
modified:test/stdio/array.js+149 added-159 removed
1 unmodified line
2import process from 'node:process';3import test from 'ava';4import tempfile from 'tempfile';5import {execa, execaSync} from '../../index.js';6import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption} from '../helpers/stdio.js';6import {fullStdio, getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';7import {stringGenerator} from '../helpers/generator.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';910setFixtureDir();1112const testEmptyArray = (t, getOptions, optionName, execaMethod) => {12const 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};1718test('Cannot pass an empty array to stdin', testEmptyArray, getStdinOption, 'stdin', execa);19test('Cannot pass an empty array to stdout', testEmptyArray, getStdoutOption, 'stdout', execa);20test('Cannot pass an empty array to stderr', testEmptyArray, getStderrOption, 'stderr', execa);21test('Cannot pass an empty array to stdio[*]', testEmptyArray, getStdioOption, 'stdio[3]', execa);22test('Cannot pass an empty array to stdin - sync', testEmptyArray, getStdinOption, 'stdin', execaSync);23test('Cannot pass an empty array to stdout - sync', testEmptyArray, getStdoutOption, 'stdout', execaSync);24test('Cannot pass an empty array to stderr - sync', testEmptyArray, getStderrOption, 'stderr', execaSync);25test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, getStdioOption, 'stdio[3]', execaSync);18test('Cannot pass an empty array to stdin', testEmptyArray, 0, 'stdin', execa);19test('Cannot pass an empty array to stdout', testEmptyArray, 1, 'stdout', execa);20test('Cannot pass an empty array to stderr', testEmptyArray, 2, 'stderr', execa);21test('Cannot pass an empty array to stdio[*]', testEmptyArray, 3, 'stdio[3]', execa);22test('Cannot pass an empty array to stdin - sync', testEmptyArray, 0, 'stdin', execaSync);23test('Cannot pass an empty array to stdout - sync', testEmptyArray, 1, 'stdout', execaSync);24test('Cannot pass an empty array to stderr - sync', testEmptyArray, 2, 'stderr', execaSync);25test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, 3, 'stdio[3]', execaSync);2627const testNoPipeOption = async (t, stdioOption, streamName) => {28 const childProcess = execa('empty.js', {[streamName]: stdioOption});29 t.is(childProcess[streamName], null);27const 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};3233test('stdin can be "ignore"', testNoPipeOption, 'ignore', 'stdin');34test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 'stdin');35test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 'stdin');36test('stdin can be "ipc"', testNoPipeOption, 'ipc', 'stdin');37test('stdin can be ["ipc"]', testNoPipeOption, ['ipc'], 'stdin');38test('stdin can be "inherit"', testNoPipeOption, 'inherit', 'stdin');39test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 'stdin');40test('stdin can be 0', testNoPipeOption, 0, 'stdin');41test('stdin can be [0]', testNoPipeOption, [0], 'stdin');42test('stdout can be "ignore"', testNoPipeOption, 'ignore', 'stdout');43test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 'stdout');44test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 'stdout');45test('stdout can be "ipc"', testNoPipeOption, 'ipc', 'stdout');46test('stdout can be ["ipc"]', testNoPipeOption, ['ipc'], 'stdout');47test('stdout can be "inherit"', testNoPipeOption, 'inherit', 'stdout');48test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 'stdout');49test('stdout can be 1', testNoPipeOption, 1, 'stdout');50test('stdout can be [1]', testNoPipeOption, [1], 'stdout');51test('stderr can be "ignore"', testNoPipeOption, 'ignore', 'stderr');52test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 'stderr');53test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 'stderr');54test('stderr can be "ipc"', testNoPipeOption, 'ipc', 'stderr');55test('stderr can be ["ipc"]', testNoPipeOption, ['ipc'], 'stderr');56test('stderr can be "inherit"', testNoPipeOption, 'inherit', 'stderr');57test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 'stderr');58test('stderr can be 2', testNoPipeOption, 2, 'stderr');59test('stderr can be [2]', testNoPipeOption, [2], 'stderr');33test('stdin can be "ignore"', testNoPipeOption, 'ignore', 0);34test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 0);35test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 0);36test('stdin can be "ipc"', testNoPipeOption, 'ipc', 0);37test('stdin can be ["ipc"]', testNoPipeOption, ['ipc'], 0);38test('stdin can be "inherit"', testNoPipeOption, 'inherit', 0);39test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 0);40test('stdin can be 0', testNoPipeOption, 0, 0);41test('stdin can be [0]', testNoPipeOption, [0], 0);42test('stdout can be "ignore"', testNoPipeOption, 'ignore', 1);43test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 1);44test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 1);45test('stdout can be "ipc"', testNoPipeOption, 'ipc', 1);46test('stdout can be ["ipc"]', testNoPipeOption, ['ipc'], 1);47test('stdout can be "inherit"', testNoPipeOption, 'inherit', 1);48test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 1);49test('stdout can be 1', testNoPipeOption, 1, 1);50test('stdout can be [1]', testNoPipeOption, [1], 1);51test('stderr can be "ignore"', testNoPipeOption, 'ignore', 2);52test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 2);53test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 2);54test('stderr can be "ipc"', testNoPipeOption, 'ipc', 2);55test('stderr can be ["ipc"]', testNoPipeOption, ['ipc'], 2);56test('stderr can be "inherit"', testNoPipeOption, 'inherit', 2);57test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 2);58test('stderr can be 2', testNoPipeOption, 2, 2);59test('stderr can be [2]', testNoPipeOption, [2], 2);60test('stdio[*] can be "ignore"', testNoPipeOption, 'ignore', 3);61test('stdio[*] can be ["ignore"]', testNoPipeOption, ['ignore'], 3);62test('stdio[*] can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 3);63test('stdio[*] can be "ipc"', testNoPipeOption, 'ipc', 3);64test('stdio[*] can be ["ipc"]', testNoPipeOption, ['ipc'], 3);65test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);66test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);67test('stdio[*] can be 3', testNoPipeOption, 3, 3);68test('stdio[*] can be [3]', testNoPipeOption, [3], 3);6961const 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};6667test('stdio[*] can be "ignore"', testNoPipeStdioOption, 'ignore');68test('stdio[*] can be ["ignore"]', testNoPipeStdioOption, ['ignore']);69test('stdio[*] can be ["ignore", "ignore"]', testNoPipeStdioOption, ['ignore', 'ignore']);70test('stdio[*] can be "ipc"', testNoPipeStdioOption, 'ipc');71test('stdio[*] can be ["ipc"]', testNoPipeStdioOption, ['ipc']);72test('stdio[*] can be "inherit"', testNoPipeStdioOption, 'inherit');73test('stdio[*] can be ["inherit"]', testNoPipeStdioOption, ['inherit']);74test('stdio[*] can be 3', testNoPipeStdioOption, 3);75test('stdio[*] can be [3]', testNoPipeStdioOption, [3]);7677const testInvalidArrayValue = (t, invalidStdio, getOptions, execaMethod) => {70const 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};7583test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', getStdinOption, execa);84test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', getStdoutOption, execa);85test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', getStderrOption, execa);86test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', getStdioOption, execa);87test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', getStdinOption, execaSync);88test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', getStdoutOption, execaSync);89test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', getStderrOption, execaSync);90test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', getStdioOption, execaSync);91test('Cannot pass "ipc" and another value to stdin', testInvalidArrayValue, 'ipc', getStdinOption, execa);92test('Cannot pass "ipc" and another value to stdout', testInvalidArrayValue, 'ipc', getStdoutOption, execa);93test('Cannot pass "ipc" and another value to stderr', testInvalidArrayValue, 'ipc', getStderrOption, execa);94test('Cannot pass "ipc" and another value to stdio[*]', testInvalidArrayValue, 'ipc', getStdioOption, execa);95test('Cannot pass "ipc" and another value to stdin - sync', testInvalidArrayValue, 'ipc', getStdinOption, execaSync);96test('Cannot pass "ipc" and another value to stdout - sync', testInvalidArrayValue, 'ipc', getStdoutOption, execaSync);97test('Cannot pass "ipc" and another value to stderr - sync', testInvalidArrayValue, 'ipc', getStderrOption, execaSync);98test('Cannot pass "ipc" and another value to stdio[*] - sync', testInvalidArrayValue, 'ipc', getStdioOption, execaSync);76test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', 0, execa);77test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', 1, execa);78test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', 2, execa);79test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', 3, execa);80test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', 0, execaSync);81test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', 1, execaSync);82test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', 2, execaSync);83test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', 3, execaSync);84test('Cannot pass "ipc" and another value to stdin', testInvalidArrayValue, 'ipc', 0, execa);85test('Cannot pass "ipc" and another value to stdout', testInvalidArrayValue, 'ipc', 1, execa);86test('Cannot pass "ipc" and another value to stderr', testInvalidArrayValue, 'ipc', 2, execa);87test('Cannot pass "ipc" and another value to stdio[*]', testInvalidArrayValue, 'ipc', 3, execa);88test('Cannot pass "ipc" and another value to stdin - sync', testInvalidArrayValue, 'ipc', 0, execaSync);89test('Cannot pass "ipc" and another value to stdout - sync', testInvalidArrayValue, 'ipc', 1, execaSync);90test('Cannot pass "ipc" and another value to stderr - sync', testInvalidArrayValue, 'ipc', 2, execaSync);91test('Cannot pass "ipc" and another value to stdio[*] - sync', testInvalidArrayValue, 'ipc', 3, execaSync);9293const 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};9899test('Cannot pass both readable and writable values to stdio[*] - WritableStream', testInputOutput, new WritableStream(), execa);
8 unmodified lines
108test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', testInputOutput, process.stderr, execaSync);109110const 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};119120test('stdio[*] default direction is output', testAmbiguousDirection, execa);121test('stdio[*] default direction is output - sync', testAmbiguousDirection, execaSync);122127const testAmbiguousMultiple = async (t, fixtureName, getOptions) => {123const 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};130135test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 'stdin.js', getStdinOption);136test('stdio[*] ambiguous direction is influenced by other values', testAmbiguousMultiple, 'stdin-fd3.js', getStdioOption);131test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 0);132test('stdio[*] ambiguous direction is influenced by other values', testAmbiguousMultiple, 3);133138const 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');134const 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};142143test.serial('stdio[*] can be 0', testRedirectInput, 0, 3, 'stdin-fd3.js');144test.serial('stdio[*] can be [0]', testRedirectInput, [0], 3, 'stdin-fd3.js');145test.serial('stdio[*] can be [0, "pipe"]', testRedirectInput, [0, 'pipe'], 3, 'stdin-fd3.js');146test.serial('stdio[*] can be process.stdin', testRedirectInput, 'stdin', 3, 'stdin-fd3.js');147test.serial('stdio[*] can be [process.stdin]', testRedirectInput, ['stdin'], 3, 'stdin-fd3.js');148test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirectInput, ['stdin', 'pipe'], 3, 'stdin-fd3.js');143const isStderrDescriptor = stdioOption => stdioOption === 2144 || stdioOption === 'stderr'145 || (Array.isArray(stdioOption) && isStderrDescriptor(stdioOption[0]));146150const OUTPUT_DESCRIPTOR_FIXTURES = ['noop.js', 'noop-err.js', 'noop-fd3.js'];147test.serial('stdio[*] can be 0', testRedirect, 0, 3, true);148test.serial('stdio[*] can be [0]', testRedirect, [0], 3, true);149test.serial('stdio[*] can be [0, "pipe"]', testRedirect, [0, 'pipe'], 3, true);150test.serial('stdio[*] can be process.stdin', testRedirect, 'stdin', 3, true);151test.serial('stdio[*] can be [process.stdin]', testRedirect, ['stdin'], 3, true);152test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirect, ['stdin', 'pipe'], 3, true);153test('stdout can be 2', testRedirect, 2, 1, false);154test('stdout can be [2]', testRedirect, [2], 1, false);155test('stdout can be [2, "pipe"]', testRedirect, [2, 'pipe'], 1, false);156test('stdout can be process.stderr', testRedirect, 'stderr', 1, false);157test('stdout can be [process.stderr]', testRedirect, ['stderr'], 1, false);158test('stdout can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 1, false);159test('stderr can be 1', testRedirect, 1, 2, false);160test('stderr can be [1]', testRedirect, [1], 2, false);161test('stderr can be [1, "pipe"]', testRedirect, [1, 'pipe'], 2, false);162test('stderr can be process.stdout', testRedirect, 'stdout', 2, false);163test('stderr can be [process.stdout]', testRedirect, ['stdout'], 2, false);164test('stderr can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 2, false);165test('stdio[*] can be 1', testRedirect, 1, 3, false);166test('stdio[*] can be [1]', testRedirect, [1], 3, false);167test('stdio[*] can be [1, "pipe"]', testRedirect, [1, 'pipe'], 3, false);168test('stdio[*] can be 2', testRedirect, 2, 3, false);169test('stdio[*] can be [2]', testRedirect, [2], 3, false);170test('stdio[*] can be [2, "pipe"]', testRedirect, [2, 'pipe'], 3, false);171test('stdio[*] can be process.stdout', testRedirect, 'stdout', 3, false);172test('stdio[*] can be [process.stdout]', testRedirect, ['stdout'], 3, false);173test('stdio[*] can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 3, false);174test('stdio[*] can be process.stderr', testRedirect, 'stderr', 3, false);175test('stdio[*] can be [process.stderr]', testRedirect, ['stderr'], 3, false);176test('stdio[*] can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 3, false);177152const isStdoutDescriptor = stdioOption => stdioOption === 1153 || stdioOption === 'stdout'154 || (Array.isArray(stdioOption) && isStdoutDescriptor(stdioOption[0]));155156const 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};162163test('stdout can be 2', testRedirectOutput, 2, 1);164test('stdout can be [2]', testRedirectOutput, [2], 1);165test('stdout can be [2, "pipe"]', testRedirectOutput, [2, 'pipe'], 1);166test('stdout can be process.stderr', testRedirectOutput, 'stderr', 1);167test('stdout can be [process.stderr]', testRedirectOutput, ['stderr'], 1);168test('stdout can be [process.stderr, "pipe"]', testRedirectOutput, ['stderr', 'pipe'], 1);169test('stderr can be 1', testRedirectOutput, 1, 2);170test('stderr can be [1]', testRedirectOutput, [1], 2);171test('stderr can be [1, "pipe"]', testRedirectOutput, [1, 'pipe'], 2);172test('stderr can be process.stdout', testRedirectOutput, 'stdout', 2);173test('stderr can be [process.stdout]', testRedirectOutput, ['stdout'], 2);174test('stderr can be [process.stdout, "pipe"]', testRedirectOutput, ['stdout', 'pipe'], 2);175test('stdio[*] can be 1', testRedirectOutput, 1, 3);176test('stdio[*] can be [1]', testRedirectOutput, [1], 3);177test('stdio[*] can be [1, "pipe"]', testRedirectOutput, [1, 'pipe'], 3);178test('stdio[*] can be 2', testRedirectOutput, 2, 3);179test('stdio[*] can be [2]', testRedirectOutput, [2], 3);180test('stdio[*] can be [2, "pipe"]', testRedirectOutput, [2, 'pipe'], 3);181test('stdio[*] can be process.stdout', testRedirectOutput, 'stdout', 3);182test('stdio[*] can be [process.stdout]', testRedirectOutput, ['stdout'], 3);183test('stdio[*] can be [process.stdout, "pipe"]', testRedirectOutput, ['stdout', 'pipe'], 3);184test('stdio[*] can be process.stderr', testRedirectOutput, 'stderr', 3);185test('stdio[*] can be [process.stderr]', testRedirectOutput, ['stderr'], 3);186test('stdio[*] can be [process.stderr, "pipe"]', testRedirectOutput, ['stderr', 'pipe'], 3);187178const 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 lines
200201test('stderr can be ["inherit", "pipe"]', testInheritStderr, ['inherit', 'pipe']);202test('stderr can be [2, "pipe"]', testInheritStderr, [2, 'pipe']);203214const testOverflowStream = async (t, stdio) => {215 const {stdout} = await execa('nested.js', [JSON.stringify({stdio}), 'empty.js'], {stdio: ['pipe', 'pipe', 'pipe', 'pipe']});204const 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};208209if (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}219230test('stdio[*] can use "inherit"', testOverflowStream, ['pipe', 'pipe', 'pipe', 'inherit']);231test('stdio[*] can use ["inherit"]', testOverflowStream, ['pipe', 'pipe', 'pipe', ['inherit']]);220test('stdio[*] can use "inherit"', testOverflowStream, 3, 'inherit');221test('stdio[*] can use ["inherit"]', testOverflowStream, 3, ['inherit']);222233const testOverflowStreamArray = (t, stdio) => {223const 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};228239test('stdin cannot use 4+ and another value', testOverflowStreamArray, [[4, 'pipe'], 'pipe', 'pipe', 'pipe']);240test('stdout cannot use 4+ and another value', testOverflowStreamArray, ['pipe', [4, 'pipe'], 'pipe', 'pipe']);241test('stderr cannot use 4+ and another value', testOverflowStreamArray, ['pipe', 'pipe', [4, 'pipe'], 'pipe']);242test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, ['pipe', 'pipe', 'pipe', [4, 'pipe']]);243test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, ['pipe', 'pipe', 'pipe', ['inherit', 'pipe']]);229test('stdin cannot use 4+ and another value', testOverflowStreamArray, 0, [4, 'pipe']);230test('stdout cannot use 4+ and another value', testOverflowStreamArray, 1, [4, 'pipe']);231test('stderr cannot use 4+ and another value', testOverflowStreamArray, 2, [4, 'pipe']);232test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, 3, [4, 'pipe']);233test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, 3, ['inherit', 'pipe']);234245const testOverlapped = async (t, getOptions) => {246 const {stdout} = await execa('noop.js', ['foobar'], getOptions(['overlapped', 'pipe']));235const testOverlapped = async (t, index) => {236 const {stdout} = await execa('noop.js', ['foobar'], getStdio(index, ['overlapped', 'pipe']));237 t.is(stdout, 'foobar');238};239250test('stdin can be ["overlapped", "pipe"]', testOverlapped, getStdinOption);251test('stdout can be ["overlapped", "pipe"]', testOverlapped, getStdoutOption);252test('stderr can be ["overlapped", "pipe"]', testOverlapped, getStderrOption);253test('stdio[*] can be ["overlapped", "pipe"]', testOverlapped, getStdioOption);240test('stdin can be ["overlapped", "pipe"]', testOverlapped, 0);241test('stdout can be ["overlapped", "pipe"]', testOverlapped, 1);242test('stderr can be ["overlapped", "pipe"]', testOverlapped, 2);243test('stdio[*] can be ["overlapped", "pipe"]', testOverlapped, 3);244255const testDestroyStandard = async (t, optionName) => {245const 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};252263test('Does not destroy process.stdin on errors', testDestroyStandard, 'stdin');264test('Does not destroy process.stdout on errors', testDestroyStandard, 'stdout');265test('Does not destroy process.stderr on errors', testDestroyStandard, 'stderr');253test('Does not destroy process.stdin on errors', testDestroyStandard, 0);254test('Does not destroy process.stdout on errors', testDestroyStandard, 1);255test('Does not destroy process.stderr on errors', testDestroyStandard, 2);
modified:test/stdio/file-descriptor.js+16 added-18 removed
1 unmodified line
2import test from 'ava';3import tempfile from 'tempfile';4import {execa, execaSync} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption} from '../helpers/stdio.js';6import {getStdio} from '../helpers/stdio.js';78setFixtureDir();910const getStdinProp = ({stdin}) => stdin;11const getStdioProp = ({stdio}) => stdio[3];1213const testFileDescriptorOption = async (t, fixtureName, getOptions, execaMethod) => {10const 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};1821test('pass `stdout` to a file descriptor', testFileDescriptorOption, 'noop.js', getStdoutOption, execa);22test('pass `stderr` to a file descriptor', testFileDescriptorOption, 'noop-err.js', getStderrOption, execa);23test('pass `stdio[*]` to a file descriptor', testFileDescriptorOption, 'noop-fd3.js', getStdioOption, execa);24test('pass `stdout` to a file descriptor - sync', testFileDescriptorOption, 'noop.js', getStdoutOption, execaSync);25test('pass `stderr` to a file descriptor - sync', testFileDescriptorOption, 'noop-err.js', getStderrOption, execaSync);26test('pass `stdio[*]` to a file descriptor - sync', testFileDescriptorOption, 'noop-fd3.js', getStdioOption, execaSync);19test('pass `stdout` to a file descriptor', testFileDescriptorOption, 1, execa);20test('pass `stderr` to a file descriptor', testFileDescriptorOption, 2, execa);21test('pass `stdio[*]` to a file descriptor', testFileDescriptorOption, 3, execa);22test('pass `stdout` to a file descriptor - sync', testFileDescriptorOption, 1, execaSync);23test('pass `stderr` to a file descriptor - sync', testFileDescriptorOption, 2, execaSync);24test('pass `stdio[*]` to a file descriptor - sync', testFileDescriptorOption, 3, execaSync);2528const testStdinWrite = async (t, getStreamProp, fixtureName, getOptions) => {29 const subprocess = execa(fixtureName, getOptions('pipe'));30 getStreamProp(subprocess).end('unicorns');26const 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};3235test('you can write to child.stdin', testStdinWrite, getStdinProp, 'stdin.js', getStdinOption);36test('you can write to child.stdio[*]', testStdinWrite, getStdioProp, 'stdin-fd3.js', getStdioOption);33test('you can write to child.stdin', testStdinWrite, 0);34test('you can write to child.stdio[*]', testStdinWrite, 3);
modified:test/stdio/file-path.js+126 added-134 removed
2 unmodified lines
3import process from 'node:process';4import {pathToFileURL} from 'node:url';5import test from 'ava';6import tempfile from 'tempfile';7import {execa, execaSync, $} from '../../index.js';7import {execa, execaSync} from '../../index.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';9import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption, getInputFileOption, getScriptSync, identity} from '../helpers/stdio.js';9import {identity, getStdio} from '../helpers/stdio.js';10import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';1112setFixtureDir();1314const textEncoder = new TextEncoder();
1 unmodified line
16const nonFileUrl = new URL('https://example.com');1718const getAbsolutePath = file => ({file});19const getRelativePath = filePath => ({file: relative('.', filePath)});19const getStdinFilePath = file => ({stdin: {file}});2021const getStdioFile = (index, file) => getStdio(index, index === 0 ? {file} : file);2223const getStdioInput = (index, file) => {24 if (index === 'string') {25 return {input: 'foobar'};26 }2728 if (index === 'binary') {29 return {input: binaryFoobar};30 }3132 return getStdioFile(index, file);33};3421const testStdinFile = async (t, mapFilePath, getOptions, execaMethod) => {35const 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};4229test('inputFile can be a file URL', testStdinFile, pathToFileURL, getInputFileOption, execa);30test('stdin can be a file URL', testStdinFile, pathToFileURL, getStdinOption, execa);31test('inputFile can be an absolute file path', testStdinFile, identity, getInputFileOption, execa);32test('stdin can be an absolute file path', testStdinFile, getAbsolutePath, getStdinOption, execa);33test('inputFile can be a relative file path', testStdinFile, identity, getInputFileOption, execa);34test('stdin can be a relative file path', testStdinFile, getRelativePath, getStdinOption, execa);35test('inputFile can be a file URL - sync', testStdinFile, pathToFileURL, getInputFileOption, execaSync);36test('stdin can be a file URL - sync', testStdinFile, pathToFileURL, getStdinOption, execaSync);37test('inputFile can be an absolute file path - sync', testStdinFile, identity, getInputFileOption, execaSync);38test('stdin can be an absolute file path - sync', testStdinFile, getAbsolutePath, getStdinOption, execaSync);39test('inputFile can be a relative file path - sync', testStdinFile, identity, getInputFileOption, execaSync);40test('stdin can be a relative file path - sync', testStdinFile, getRelativePath, getStdinOption, execaSync);43test('inputFile can be a file URL', testStdinFile, pathToFileURL, 'inputFile', execa);44test('stdin can be a file URL', testStdinFile, pathToFileURL, 0, execa);45test('inputFile can be an absolute file path', testStdinFile, identity, 'inputFile', execa);46test('stdin can be an absolute file path', testStdinFile, getAbsolutePath, 0, execa);47test('inputFile can be a relative file path', testStdinFile, identity, 'inputFile', execa);48test('stdin can be a relative file path', testStdinFile, getRelativePath, 0, execa);49test('inputFile can be a file URL - sync', testStdinFile, pathToFileURL, 'inputFile', execaSync);50test('stdin can be a file URL - sync', testStdinFile, pathToFileURL, 0, execaSync);51test('inputFile can be an absolute file path - sync', testStdinFile, identity, 'inputFile', execaSync);52test('stdin can be an absolute file path - sync', testStdinFile, getAbsolutePath, 0, execaSync);53test('inputFile can be a relative file path - sync', testStdinFile, identity, 'inputFile', execaSync);54test('stdin can be a relative file path - sync', testStdinFile, getRelativePath, 0, execaSync);5542// eslint-disable-next-line max-params43const testOutputFile = async (t, mapFile, fixtureName, getOptions, execaMethod) => {56const 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};6250test('stdout can be a file URL', testOutputFile, pathToFileURL, 'noop.js', getStdoutOption, execa);51test('stderr can be a file URL', testOutputFile, pathToFileURL, 'noop-err.js', getStderrOption, execa);52test('stdio[*] can be a file URL', testOutputFile, pathToFileURL, 'noop-fd3.js', getStdioOption, execa);53test('stdout can be an absolute file path', testOutputFile, getAbsolutePath, 'noop.js', getStdoutOption, execa);54test('stderr can be an absolute file path', testOutputFile, getAbsolutePath, 'noop-err.js', getStderrOption, execa);55test('stdio[*] can be an absolute file path', testOutputFile, getAbsolutePath, 'noop-fd3.js', getStdioOption, execa);56test('stdout can be a relative file path', testOutputFile, getRelativePath, 'noop.js', getStdoutOption, execa);57test('stderr can be a relative file path', testOutputFile, getRelativePath, 'noop-err.js', getStderrOption, execa);58test('stdio[*] can be a relative file path', testOutputFile, getRelativePath, 'noop-fd3.js', getStdioOption, execa);59test('stdout can be a file URL - sync', testOutputFile, pathToFileURL, 'noop.js', getStdoutOption, execaSync);60test('stderr can be a file URL - sync', testOutputFile, pathToFileURL, 'noop-err.js', getStderrOption, execaSync);61test('stdio[*] can be a file URL - sync', testOutputFile, pathToFileURL, 'noop-fd3.js', getStdioOption, execaSync);62test('stdout can be an absolute file path - sync', testOutputFile, getAbsolutePath, 'noop.js', getStdoutOption, execaSync);63test('stderr can be an absolute file path - sync', testOutputFile, getAbsolutePath, 'noop-err.js', getStderrOption, execaSync);64test('stdio[*] can be an absolute file path - sync', testOutputFile, getAbsolutePath, 'noop-fd3.js', getStdioOption, execaSync);65test('stdout can be a relative file path - sync', testOutputFile, getRelativePath, 'noop.js', getStdoutOption, execaSync);66test('stderr can be a relative file path - sync', testOutputFile, getRelativePath, 'noop-err.js', getStderrOption, execaSync);67test('stdio[*] can be a relative file path - sync', testOutputFile, getRelativePath, 'noop-fd3.js', getStdioOption, execaSync);63test('stdout can be a file URL', testOutputFile, pathToFileURL, 1, execa);64test('stderr can be a file URL', testOutputFile, pathToFileURL, 2, execa);65test('stdio[*] can be a file URL', testOutputFile, pathToFileURL, 3, execa);66test('stdout can be an absolute file path', testOutputFile, getAbsolutePath, 1, execa);67test('stderr can be an absolute file path', testOutputFile, getAbsolutePath, 2, execa);68test('stdio[*] can be an absolute file path', testOutputFile, getAbsolutePath, 3, execa);69test('stdout can be a relative file path', testOutputFile, getRelativePath, 1, execa);70test('stderr can be a relative file path', testOutputFile, getRelativePath, 2, execa);71test('stdio[*] can be a relative file path', testOutputFile, getRelativePath, 3, execa);72test('stdout can be a file URL - sync', testOutputFile, pathToFileURL, 1, execaSync);73test('stderr can be a file URL - sync', testOutputFile, pathToFileURL, 2, execaSync);74test('stdio[*] can be a file URL - sync', testOutputFile, pathToFileURL, 3, execaSync);75test('stdout can be an absolute file path - sync', testOutputFile, getAbsolutePath, 1, execaSync);76test('stderr can be an absolute file path - sync', testOutputFile, getAbsolutePath, 2, execaSync);77test('stdio[*] can be an absolute file path - sync', testOutputFile, getAbsolutePath, 3, execaSync);78test('stdout can be a relative file path - sync', testOutputFile, getRelativePath, 1, execaSync);79test('stderr can be a relative file path - sync', testOutputFile, getRelativePath, 2, execaSync);80test('stdio[*] can be a relative file path - sync', testOutputFile, getRelativePath, 3, execaSync);8169const testStdioNonFileUrl = (t, getOptions, execaMethod) => {82const testStdioNonFileUrl = (t, index, execaMethod) => {83 t.throws(() => {71 execaMethod('noop.js', getOptions(nonFileUrl));84 execaMethod('empty.js', getStdio(index, nonFileUrl));85 }, {message: /pathToFileURL/});86};8775test('inputFile cannot be a non-file URL', testStdioNonFileUrl, getInputFileOption, execa);76test('stdin cannot be a non-file URL', testStdioNonFileUrl, getStdinOption, execa);77test('stdout cannot be a non-file URL', testStdioNonFileUrl, getStdoutOption, execa);78test('stderr cannot be a non-file URL', testStdioNonFileUrl, getStderrOption, execa);79test('stdio[*] cannot be a non-file URL', testStdioNonFileUrl, getStdioOption, execa);80test('inputFile cannot be a non-file URL - sync', testStdioNonFileUrl, getInputFileOption, execaSync);81test('stdin cannot be a non-file URL - sync', testStdioNonFileUrl, getStdinOption, execaSync);82test('stdout cannot be a non-file URL - sync', testStdioNonFileUrl, getStdoutOption, execaSync);83test('stderr cannot be a non-file URL - sync', testStdioNonFileUrl, getStderrOption, execaSync);84test('stdio[*] cannot be a non-file URL - sync', testStdioNonFileUrl, getStdioOption, execaSync);88test('inputFile cannot be a non-file URL', testStdioNonFileUrl, 'inputFile', execa);89test('stdin cannot be a non-file URL', testStdioNonFileUrl, 0, execa);90test('stdout cannot be a non-file URL', testStdioNonFileUrl, 1, execa);91test('stderr cannot be a non-file URL', testStdioNonFileUrl, 2, execa);92test('stdio[*] cannot be a non-file URL', testStdioNonFileUrl, 3, execa);93test('inputFile cannot be a non-file URL - sync', testStdioNonFileUrl, 'inputFile', execaSync);94test('stdin cannot be a non-file URL - sync', testStdioNonFileUrl, 0, execaSync);95test('stdout cannot be a non-file URL - sync', testStdioNonFileUrl, 1, execaSync);96test('stderr cannot be a non-file URL - sync', testStdioNonFileUrl, 2, execaSync);97test('stdio[*] cannot be a non-file URL - sync', testStdioNonFileUrl, 3, execaSync);9899const 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};104105test('inputFile must be a file URL or string', testInvalidInputFile, execa);106test('inputFile must be a file URL or string - sync', testInvalidInputFile, execaSync);10795const testInputFileValidUrl = async (t, getOptions, execaMethod) => {108const testInputFileValidUrl = async (t, index, execaMethod) => {109 const filePath = tempfile();110 await writeFile(filePath, 'foobar');111 const currentCwd = process.cwd();112 process.chdir(dirname(filePath));113114 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};122110test.serial('inputFile does not need to start with . when being a relative file path', testInputFileValidUrl, getInputFileOption, execa);111test.serial('stdin does not need to start with . when being a relative file path', testInputFileValidUrl, getStdinFilePath, execa);112test.serial('inputFile does not need to start with . when being a relative file path - sync', testInputFileValidUrl, getInputFileOption, execaSync);113test.serial('stdin does not need to start with . when being a relative file path - sync', testInputFileValidUrl, getStdinFilePath, execaSync);123test.serial('inputFile does not need to start with . when being a relative file path', testInputFileValidUrl, 'inputFile', execa);124test.serial('stdin does not need to start with . when being a relative file path', testInputFileValidUrl, 0, execa);125test.serial('inputFile does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 'inputFile', execaSync);126test.serial('stdin does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 0, execaSync);127115const testFilePathObject = (t, getOptions, execaMethod) => {128const 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};133121test('stdin must be an object when it is a file path string', testFilePathObject, getStdinOption, execa);122test('stdout must be an object when it is a file path string', testFilePathObject, getStdoutOption, execa);123test('stderr must be an object when it is a file path string', testFilePathObject, getStderrOption, execa);124test('stdio[*] must be an object when it is a file path string', testFilePathObject, getStdioOption, execa);125test('stdin be an object when it is a file path string - sync', testFilePathObject, getStdinOption, execaSync);126test('stdout be an object when it is a file path string - sync', testFilePathObject, getStdoutOption, execaSync);127test('stderr be an object when it is a file path string - sync', testFilePathObject, getStderrOption, execaSync);128test('stdio[*] must be an object when it is a file path string - sync', testFilePathObject, getStdioOption, execaSync);134test('stdin must be an object when it is a file path string', testFilePathObject, 0, execa);135test('stdout must be an object when it is a file path string', testFilePathObject, 1, execa);136test('stderr must be an object when it is a file path string', testFilePathObject, 2, execa);137test('stdio[*] must be an object when it is a file path string', testFilePathObject, 3, execa);138test('stdin be an object when it is a file path string - sync', testFilePathObject, 0, execaSync);139test('stdout be an object when it is a file path string - sync', testFilePathObject, 1, execaSync);140test('stderr be an object when it is a file path string - sync', testFilePathObject, 2, execaSync);141test('stdio[*] must be an object when it is a file path string - sync', testFilePathObject, 3, execaSync);142130const testFileError = async (t, mapFile, getOptions) => {143const 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};149137test('inputFile file URL errors should be handled', testFileError, pathToFileURL, getInputFileOption);138test('stdin file URL errors should be handled', testFileError, pathToFileURL, getStdinOption);139test('stdout file URL errors should be handled', testFileError, pathToFileURL, getStdoutOption);140test('stderr file URL errors should be handled', testFileError, pathToFileURL, getStderrOption);141test('stdio[*] file URL errors should be handled', testFileError, pathToFileURL, getStdioOption);142test('inputFile file path errors should be handled', testFileError, identity, getInputFileOption);143test('stdin file path errors should be handled', testFileError, getAbsolutePath, getStdinOption);144test('stdout file path errors should be handled', testFileError, getAbsolutePath, getStdoutOption);145test('stderr file path errors should be handled', testFileError, getAbsolutePath, getStderrOption);146test('stdio[*] file path errors should be handled', testFileError, getAbsolutePath, getStdioOption);150test('inputFile file URL errors should be handled', testFileError, pathToFileURL, 'inputFile');151test('stdin file URL errors should be handled', testFileError, pathToFileURL, 0);152test('stdout file URL errors should be handled', testFileError, pathToFileURL, 1);153test('stderr file URL errors should be handled', testFileError, pathToFileURL, 2);154test('stdio[*] file URL errors should be handled', testFileError, pathToFileURL, 3);155test('inputFile file path errors should be handled', testFileError, identity, 'inputFile');156test('stdin file path errors should be handled', testFileError, getAbsolutePath, 0);157test('stdout file path errors should be handled', testFileError, getAbsolutePath, 1);158test('stderr file path errors should be handled', testFileError, getAbsolutePath, 2);159test('stdio[*] file path errors should be handled', testFileError, getAbsolutePath, 3);160148const testFileErrorSync = (t, mapFile, getOptions) => {161const 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};166154test('inputFile file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, getInputFileOption);155test('stdin file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, getStdinOption);156test('stdout file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, getStdoutOption);157test('stderr file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, getStderrOption);158test('stdio[*] file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, getStdioOption);159test('inputFile file path errors should be handled - sync', testFileErrorSync, identity, getInputFileOption);160test('stdin file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, getStdinOption);161test('stdout file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, getStdoutOption);162test('stderr file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, getStderrOption);163test('stdio[*] file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, getStdioOption);167test('inputFile file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 'inputFile');168test('stdin file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 0);169test('stdout file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 1);170test('stderr file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 2);171test('stdio[*] file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 3);172test('inputFile file path errors should be handled - sync', testFileErrorSync, identity, 'inputFile');173test('stdin file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 0);174test('stdout file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 1);175test('stderr file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 2);176test('stdio[*] file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 3);177165const 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};172173test('inputFile can be set', testInputFile, execa);174test('inputFile can be set - sync', testInputFile, execa);175176const 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};183184test('inputFile can be set with $', testInputFileScript, identity);185test('inputFile can be set with $.sync', testInputFileScript, getScriptSync);186187const testMultipleInputs = async (t, allGetOptions, execaMethod) => {178const 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};186196const getStringInput = () => ({input: 'foobar'});197const getBinaryInput = () => ({input: binaryFoobar});198199test('input String and inputFile can be both set', testMultipleInputs, [getInputFileOption, getStringInput], execa);200test('input String and stdin can be both set', testMultipleInputs, [getStdinFilePath, getStringInput], execa);201test('input Uint8Array and inputFile can be both set', testMultipleInputs, [getInputFileOption, getBinaryInput], execa);202test('input Uint8Array and stdin can be both set', testMultipleInputs, [getStdinFilePath, getBinaryInput], execa);203test('stdin and inputFile can be both set', testMultipleInputs, [getStdinFilePath, getInputFileOption], execa);204test('input String, stdin and inputFile can be all set', testMultipleInputs, [getInputFileOption, getStdinFilePath, getStringInput], execa);205test('input Uint8Array, stdin and inputFile can be all set', testMultipleInputs, [getInputFileOption, getStdinFilePath, getBinaryInput], execa);206test('input String and inputFile can be both set - sync', testMultipleInputs, [getInputFileOption, getStringInput], execaSync);207test('input String and stdin can be both set - sync', testMultipleInputs, [getStdinFilePath, getStringInput], execaSync);208test('input Uint8Array and inputFile can be both set - sync', testMultipleInputs, [getInputFileOption, getBinaryInput], execaSync);209test('input Uint8Array and stdin can be both set - sync', testMultipleInputs, [getStdinFilePath, getBinaryInput], execaSync);210test('stdin and inputFile can be both set - sync', testMultipleInputs, [getStdinFilePath, getInputFileOption], execaSync);211test('input String, stdin and inputFile can be all set - sync', testMultipleInputs, [getInputFileOption, getStdinFilePath, getStringInput], execaSync);212test('input Uint8Array, stdin and inputFile can be all set - sync', testMultipleInputs, [getInputFileOption, getStdinFilePath, getBinaryInput], execaSync);187test('inputFile can be set', testMultipleInputs, ['inputFile'], runExeca);188test('inputFile can be set - sync', testMultipleInputs, ['inputFile'], runExecaSync);189test('inputFile can be set with $', testMultipleInputs, ['inputFile'], runScript);190test('inputFile can be set with $.sync', testMultipleInputs, ['inputFile'], runScriptSync);191test('input String and inputFile can be both set', testMultipleInputs, ['inputFile', 'string'], execa);192test('input String and stdin can be both set', testMultipleInputs, [0, 'string'], execa);193test('input Uint8Array and inputFile can be both set', testMultipleInputs, ['inputFile', 'binary'], execa);194test('input Uint8Array and stdin can be both set', testMultipleInputs, [0, 'binary'], execa);195test('stdin and inputFile can be both set', testMultipleInputs, [0, 'inputFile'], execa);196test('input String, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'string'], execa);197test('input Uint8Array, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'binary'], execa);198test('input String and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'string'], execaSync);199test('input String and stdin can be both set - sync', testMultipleInputs, [0, 'string'], execaSync);200test('input Uint8Array and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'binary'], execaSync);201test('input Uint8Array and stdin can be both set - sync', testMultipleInputs, [0, 'binary'], execaSync);202test('stdin and inputFile can be both set - sync', testMultipleInputs, [0, 'inputFile'], execaSync);203test('input String, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'string'], execaSync);204test('input Uint8Array, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'binary'], execaSync);
modified:test/stdio/input.js+9 added-15 removed
1import {Buffer} from 'node:buffer';2import {Writable} from 'node:stream';3import test from 'ava';4import {execa, execaSync, $} from '../../index.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {getScriptSync, identity} from '../helpers/stdio.js';6import {runExeca, runExecaSync, runScript, runScriptSync} from '../helpers/run.js';78setFixtureDir();910const textEncoder = new TextEncoder();
7 unmodified lines
18 const {stdout} = await execaMethod('stdin.js', {input});19 t.is(stdout, 'foobar');20};2122test('input option can be a String', testInput, 'foobar', execa);23test('input option can be a String - sync', testInput, 'foobar', execaSync);24test('input option can be a Uint8Array', testInput, binaryFoobar, execa);25test('input option can be a Uint8Array - sync', testInput, binaryFoobar, execaSync);22test('input option can be a String', testInput, 'foobar', runExeca);23test('input option can be a Uint8Array', testInput, binaryFoobar, runExeca);24test('input option can be a String - sync', testInput, 'foobar', runExecaSync);25test('input option can be a Uint8Array - sync', testInput, binaryFoobar, runExecaSync);26test('input option can be used with $', testInput, 'foobar', runScript);27test('input option can be used with $.sync', testInput, 'foobar', runScriptSync);2827const testInputScript = async (t, getExecaMethod) => {28 const {stdout} = await getExecaMethod($({input: 'foobar'}))`stdin.js`;29 t.is(stdout, 'foobar');30};3132test('input option can be used with $', testInputScript, identity);33test('input option can be used with $.sync', testInputScript, getScriptSync);3429const 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};3435test('input option cannot be a Buffer', testInvalidInput, bufferFoobar, execa);
15 unmodified lines
modified:test/stdio/iterable.js+30 added-30 removed
1import {once} from 'node:events';2import test from 'ava';3import {execa, execaSync} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption} from '../helpers/stdio.js';5import {getStdio} from '../helpers/stdio.js';6import {stringGenerator, binaryGenerator, asyncGenerator, throwingGenerator, infiniteGenerator} from '../helpers/generator.js';78setFixtureDir();910const testIterable = async (t, stdioOption, fixtureName, getOptions) => {11 const {stdout} = await execa(fixtureName, getOptions(stdioOption));10const testIterable = async (t, stdioOption, index) => {11 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, stdioOption));12 t.is(stdout, 'foobar');13};1415test('stdin option can be an iterable of strings', testIterable, stringGenerator(), 'stdin.js', getStdinOption);16test('stdio[*] option can be an iterable of strings', testIterable, stringGenerator(), 'stdin-fd3.js', getStdioOption);17test('stdin option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 'stdin.js', getStdinOption);18test('stdio[*] option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 'stdin-fd3.js', getStdioOption);19test('stdin option can be an async iterable', testIterable, asyncGenerator(), 'stdin.js', getStdinOption);20test('stdio[*] option can be an async iterable', testIterable, asyncGenerator(), 'stdin-fd3.js', getStdioOption);15test('stdin option can be an iterable of strings', testIterable, stringGenerator(), 0);16test('stdio[*] option can be an iterable of strings', testIterable, stringGenerator(), 3);17test('stdin option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 0);18test('stdio[*] option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 3);19test('stdin option can be an async iterable', testIterable, asyncGenerator(), 0);20test('stdio[*] option can be an async iterable', testIterable, asyncGenerator(), 3);2122const testIterableSync = (t, stdioOption, fixtureName, getOptions) => {22const 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};2728test('stdin option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 'stdin.js', getStdinOption);29test('stdio[*] option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 'stdin-fd3.js', getStdioOption);30test('stdin option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 'stdin.js', getStdinOption);31test('stdio[*] option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 'stdin-fd3.js', getStdioOption);28test('stdin option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 0);29test('stdio[*] option cannot be a sync iterable - sync', testIterableSync, stringGenerator(), 3);30test('stdin option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 0);31test('stdio[*] option cannot be an async iterable - sync', testIterableSync, asyncGenerator(), 3);3233const testIterableError = async (t, fixtureName, getOptions) => {34 const {originalMessage} = await t.throwsAsync(execa(fixtureName, getOptions(throwingGenerator())));33const 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};3738test('stdin option handles errors in iterables', testIterableError, 'stdin.js', getStdinOption);39test('stdio[*] option handles errors in iterables', testIterableError, 'stdin-fd3.js', getStdioOption);38test('stdin option handles errors in iterables', testIterableError, 0);39test('stdio[*] option handles errors in iterables', testIterableError, 3);4041const testNoIterableOutput = (t, getOptions, execaMethod) => {41const 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};4647test('stdout option cannot be an iterable', testNoIterableOutput, getStdoutOption, execa);48test('stderr option cannot be an iterable', testNoIterableOutput, getStderrOption, execa);49test('stdout option cannot be an iterable - sync', testNoIterableOutput, getStdoutOption, execaSync);50test('stderr option cannot be an iterable - sync', testNoIterableOutput, getStderrOption, execaSync);47test('stdout option cannot be an iterable', testNoIterableOutput, 1, execa);48test('stderr option cannot be an iterable', testNoIterableOutput, 2, execa);49test('stdout option cannot be an iterable - sync', testNoIterableOutput, 1, execaSync);50test('stderr option cannot be an iterable - sync', testNoIterableOutput, 2, execaSync);5152test('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 line
61 abort();62 }63});6465const testMultipleIterable = async (t, fixtureName, getOptions) => {66 const {stdout} = await execa(fixtureName, getOptions([stringGenerator(), asyncGenerator()]));65const testMultipleIterable = async (t, index) => {66 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, [stringGenerator(), asyncGenerator()]));67 t.is(stdout, 'foobarfoobar');68};6970test('stdin option can be multiple iterables', testMultipleIterable, 'stdin.js', getStdinOption);71test('stdio[*] option can be multiple iterables', testMultipleIterable, 'stdin-fd3.js', getStdioOption);70test('stdin option can be multiple iterables', testMultipleIterable, 0);71test('stdio[*] option can be multiple iterables', testMultipleIterable, 3);
modified:test/stdio/node-stream.js+38 added-37 removed
4 unmodified lines
5import test from 'ava';6import tempfile from 'tempfile';7import {execa, execaSync} from '../../index.js';8import {setFixtureDir} from '../helpers/fixtures-dir.js';9import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption, getInputOption} from '../helpers/stdio.js';9import {getStdio} from '../helpers/stdio.js';1011setFixtureDir();1213const createNoFileReadable = value => {
2 unmodified lines
16 stream.end();17 return stream;18};1920const testNodeStreamSync = (t, StreamClass, getOptions, optionName) => {20const 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};2526test('input cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, getInputOption, 'input');27test('stdin cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, getStdinOption, 'stdin');28test('stdio[*] cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, getStdioOption, 'stdio[3]');29test('stdout cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, getStdoutOption, 'stdout');30test('stderr cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, getStderrOption, 'stderr');31test('stdio[*] cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, getStdioOption, 'stdio[3]');26test('input cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, 'input', 'input');27test('stdin cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, 0, 'stdin');28test('stdio[*] cannot be a Node.js Readable - sync', testNodeStreamSync, Readable, 3, 'stdio[3]');29test('stdout cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, 1, 'stdout');30test('stderr cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, 2, 'stderr');31test('stdio[*] cannot be a Node.js Writable - sync', testNodeStreamSync, Writable, 3, 'stdio[3]');3233test('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});3738const testNoFileStream = async (t, getOptions, StreamClass) => {39 await t.throwsAsync(execa('noop.js', getOptions(new StreamClass())), {code: 'ERR_INVALID_ARG_VALUE'});38const testNoFileStream = async (t, index, StreamClass) => {39 await t.throwsAsync(execa('empty.js', getStdio(index, new StreamClass())), {code: 'ERR_INVALID_ARG_VALUE'});40};4142test('stdin cannot be a Node.js Readable without a file descriptor', testNoFileStream, getStdinOption, Readable);43test('stdout cannot be a Node.js Writable without a file descriptor', testNoFileStream, getStdoutOption, Writable);44test('stderr cannot be a Node.js Writable without a file descriptor', testNoFileStream, getStderrOption, Writable);45test('stdio[*] cannot be a Node.js Readable without a file descriptor', testNoFileStream, getStdioOption, Readable);46test('stdio[*] cannot be a Node.js Writable without a file descriptor', testNoFileStream, getStdioOption, Writable);42test('stdin cannot be a Node.js Readable without a file descriptor', testNoFileStream, 0, Readable);43test('stdout cannot be a Node.js Writable without a file descriptor', testNoFileStream, 1, Writable);44test('stderr cannot be a Node.js Writable without a file descriptor', testNoFileStream, 2, Writable);45test('stdio[*] cannot be a Node.js Readable without a file descriptor', testNoFileStream, 3, Readable);46test('stdio[*] cannot be a Node.js Writable without a file descriptor', testNoFileStream, 3, Writable);4748const testFileReadable = async (t, fixtureName, getOptions) => {48const testFileReadable = async (t, index) => {49 const filePath = tempfile();50 await writeFile(filePath, 'foobar');51 const stream = createReadStream(filePath);52 await once(stream, 'open');5354 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');5758 await rm(filePath);59};6060test('input can be a Node.js Readable with a file descriptor', testFileReadable, 'stdin.js', getInputOption);61test('stdin can be a Node.js Readable with a file descriptor', testFileReadable, 'stdin.js', getStdinOption);62test('stdio[*] can be a Node.js Readable with a file descriptor', testFileReadable, 'stdin-fd3.js', getStdioOption);61test('input can be a Node.js Readable with a file descriptor', testFileReadable, 'input');62test('stdin can be a Node.js Readable with a file descriptor', testFileReadable, 0);63test('stdio[*] can be a Node.js Readable with a file descriptor', testFileReadable, 3);6464const testFileWritable = async (t, getOptions, fixtureName) => {65const testFileWritable = async (t, index) => {66 const filePath = tempfile();67 const stream = createWriteStream(filePath);68 await once(stream, 'open');6969 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');7273 await rm(filePath);74};7575test('stdout can be a Node.js Writable with a file descriptor', testFileWritable, getStdoutOption, 'noop.js');76test('stderr can be a Node.js Writable with a file descriptor', testFileWritable, getStderrOption, 'noop-err.js');77test('stdio[*] can be a Node.js Writable with a file descriptor', testFileWritable, getStdioOption, 'noop-fd3.js');76test('stdout can be a Node.js Writable with a file descriptor', testFileWritable, 1);77test('stderr can be a Node.js Writable with a file descriptor', testFileWritable, 2);78test('stdio[*] can be a Node.js Writable with a file descriptor', testFileWritable, 3);7979const testLazyFileReadable = async (t, fixtureName, getOptions) => {80const testLazyFileReadable = async (t, index) => {81 const filePath = tempfile();82 await writeFile(filePath, 'foobar');83 const stream = createReadStream(filePath);8484 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');8788 await rm(filePath);89};9090test('stdin can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 'stdin.js', getStdinOption);91test('stdio[*] can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 'stdin-fd3.js', getStdioOption);91test('stdin can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 0);92test('stdio[*] can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 3);9393const testLazyFileWritable = async (t, getOptions, fixtureName) => {94const testLazyFileWritable = async (t, index) => {95 const filePath = tempfile();96 const stream = createWriteStream(filePath);9797 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');100101 await rm(filePath);102};103103test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, getStdoutOption, 'noop.js');104test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, getStderrOption, 'noop-err.js');105test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, getStdioOption, 'noop-fd3.js');104test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 1);105test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 2);106test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 3);
modified:test/stdio/typed-array.js+13 added-13 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption} from '../helpers/stdio.js';4import {getStdio} from '../helpers/stdio.js';56setFixtureDir();78const uint8ArrayFoobar = new TextEncoder().encode('foobar');910const testUint8Array = async (t, fixtureName, getOptions) => {11 const {stdout} = await execa(fixtureName, getOptions(uint8ArrayFoobar));10const testUint8Array = async (t, index) => {11 const {stdout} = await execa('stdin-fd.js', [`${index}`], getStdio(index, uint8ArrayFoobar));12 t.is(stdout, 'foobar');13};1415test('stdin option can be a Uint8Array', testUint8Array, 'stdin.js', getStdinOption);16test('stdio[*] option can be a Uint8Array', testUint8Array, 'stdin-fd3.js', getStdioOption);17test('stdin option can be a Uint8Array - sync', testUint8Array, 'stdin.js', getStdinOption);18test('stdio[*] option can be a Uint8Array - sync', testUint8Array, 'stdin-fd3.js', getStdioOption);15test('stdin option can be a Uint8Array', testUint8Array, 0);16test('stdio[*] option can be a Uint8Array', testUint8Array, 3);17test('stdin option can be a Uint8Array - sync', testUint8Array, 0);18test('stdio[*] option can be a Uint8Array - sync', testUint8Array, 3);1920const testNoUint8ArrayOutput = (t, getOptions, execaMethod) => {20const 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};2526test('stdout option cannot be a Uint8Array', testNoUint8ArrayOutput, getStdoutOption, execa);27test('stderr option cannot be a Uint8Array', testNoUint8ArrayOutput, getStderrOption, execa);28test('stdout option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, getStdoutOption, execaSync);29test('stderr option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, getStderrOption, execaSync);26test('stdout option cannot be a Uint8Array', testNoUint8ArrayOutput, 1, execa);27test('stderr option cannot be a Uint8Array', testNoUint8ArrayOutput, 2, execa);28test('stdout option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, 1, execaSync);29test('stderr option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, 2, execaSync);
modified:test/stdio/web-stream.js+28 added-28 removed
1 unmodified line
2import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import {execa, execaSync} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption} from '../helpers/stdio.js';6import {getStdio} from '../helpers/stdio.js';78setFixtureDir();910const testReadableStream = async (t, fixtureName, getOptions) => {10const 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};1516test('stdin can be a ReadableStream', testReadableStream, 'stdin.js', getStdinOption);17test('stdio[*] can be a ReadableStream', testReadableStream, 'stdin-fd3.js', getStdioOption);16test('stdin can be a ReadableStream', testReadableStream, 0);17test('stdio[*] can be a ReadableStream', testReadableStream, 3);1819const testWritableStream = async (t, fixtureName, getOptions) => {19const 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};2930test('stdout can be a WritableStream', testWritableStream, 'noop.js', getStdoutOption);31test('stderr can be a WritableStream', testWritableStream, 'noop-err.js', getStderrOption);32test('stdio[*] can be a WritableStream', testWritableStream, 'noop-fd3.js', getStdioOption);30test('stdout can be a WritableStream', testWritableStream, 1);31test('stderr can be a WritableStream', testWritableStream, 2);32test('stdio[*] can be a WritableStream', testWritableStream, 3);3334const testWebStreamSync = (t, StreamClass, getOptions, optionName) => {34const 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};3940test('stdin cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, getStdinOption, 'stdin');41test('stdio[*] cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, getStdioOption, 'stdio[3]');42test('stdout cannot be a WritableStream - sync', testWebStreamSync, WritableStream, getStdoutOption, 'stdout');43test('stderr cannot be a WritableStream - sync', testWebStreamSync, WritableStream, getStderrOption, 'stderr');44test('stdio[*] cannot be a WritableStream - sync', testWebStreamSync, WritableStream, getStdioOption, 'stdio[3]');40test('stdin cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, 0, 'stdin');41test('stdio[*] cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, 3, 'stdio[3]');42test('stdout cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 1, 'stdout');43test('stderr cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 2, 'stderr');44test('stdio[*] cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 3, 'stdio[3]');4546const testLongWritableStream = async (t, getOptions) => {46const 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};5758test('stdout waits for WritableStream completion', testLongWritableStream, getStdoutOption);59test('stderr waits for WritableStream completion', testLongWritableStream, getStderrOption);60test('stdio[*] waits for WritableStream completion', testLongWritableStream, getStdioOption);58test('stdout waits for WritableStream completion', testLongWritableStream, 1);59test('stderr waits for WritableStream completion', testLongWritableStream, 2);60test('stdio[*] waits for WritableStream completion', testLongWritableStream, 3);6162const testWritableStreamError = async (t, getOptions) => {62const 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};7172test('stdout option handles errors in WritableStream', testWritableStreamError, getStdoutOption);73test('stderr option handles errors in WritableStream', testWritableStreamError, getStderrOption);74test('stdio[*] option handles errors in WritableStream', testWritableStreamError, getStdioOption);72test('stdout option handles errors in WritableStream', testWritableStreamError, 1);73test('stderr option handles errors in WritableStream', testWritableStreamError, 2);74test('stdio[*] option handles errors in WritableStream', testWritableStreamError, 3);
added:test/encoding.js+121 added
1import {Buffer} from 'node:buffer';2import {exec} from 'node:child_process';3import {promisify} from 'node:util';4import test from 'ava';5import {execa, execaSync} from '../index.js';6import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';7import {fullStdio} from './helpers/stdio.js';89const pExec = promisify(exec);1011setFixtureDir();1213const 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);1617 if (index === 3) {18 return;19 }2021 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};2425const 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};3334// This string gives different outputs with each encoding type35const STRING_TO_ENCODE = '\u1000.';36const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);3738/* eslint-disable unicorn/text-encoding-identifier-case */39test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);40test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);41test('can pass encoding "utf-8" to stdout', checkEncoding, 'utf-8', 1, execa);42test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);43test('can pass encoding "utf-16le" to stdout', checkEncoding, 'utf-16le', 1, execa);44test('can pass encoding "ucs2" to stdout', checkEncoding, 'ucs2', 1, execa);45test('can pass encoding "ucs-2" to stdout', checkEncoding, 'ucs-2', 1, execa);46test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);47test('can pass encoding "binary" to stdout', checkEncoding, 'binary', 1, execa);48test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);49test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);50test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);51test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);52test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);53test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);54test('can pass encoding "utf-8" to stderr', checkEncoding, 'utf-8', 2, execa);55test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);56test('can pass encoding "utf-16le" to stderr', checkEncoding, 'utf-16le', 2, execa);57test('can pass encoding "ucs2" to stderr', checkEncoding, 'ucs2', 2, execa);58test('can pass encoding "ucs-2" to stderr', checkEncoding, 'ucs-2', 2, execa);59test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);60test('can pass encoding "binary" to stderr', checkEncoding, 'binary', 2, execa);61test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);62test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);63test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);64test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);65test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);66test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);67test('can pass encoding "utf-8" to stdio[*]', checkEncoding, 'utf-8', 3, execa);68test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);69test('can pass encoding "utf-16le" to stdio[*]', checkEncoding, 'utf-16le', 3, execa);70test('can pass encoding "ucs2" to stdio[*]', checkEncoding, 'ucs2', 3, execa);71test('can pass encoding "ucs-2" to stdio[*]', checkEncoding, 'ucs-2', 3, execa);72test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);73test('can pass encoding "binary" to stdio[*]', checkEncoding, 'binary', 3, execa);74test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);75test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);76test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);77test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);78test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);79test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);80test('can pass encoding "utf-8" to stdout - sync', checkEncoding, 'utf-8', 1, execaSync);81test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);82test('can pass encoding "utf-16le" to stdout - sync', checkEncoding, 'utf-16le', 1, execaSync);83test('can pass encoding "ucs2" to stdout - sync', checkEncoding, 'ucs2', 1, execaSync);84test('can pass encoding "ucs-2" to stdout - sync', checkEncoding, 'ucs-2', 1, execaSync);85test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);86test('can pass encoding "binary" to stdout - sync', checkEncoding, 'binary', 1, execaSync);87test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);88test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);89test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);90test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);91test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);92test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);93test('can pass encoding "utf-8" to stderr - sync', checkEncoding, 'utf-8', 2, execaSync);94test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);95test('can pass encoding "utf-16le" to stderr - sync', checkEncoding, 'utf-16le', 2, execaSync);96test('can pass encoding "ucs2" to stderr - sync', checkEncoding, 'ucs2', 2, execaSync);97test('can pass encoding "ucs-2" to stderr - sync', checkEncoding, 'ucs-2', 2, execaSync);98test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);99test('can pass encoding "binary" to stderr - sync', checkEncoding, 'binary', 2, execaSync);100test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);101test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);102test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);103test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);104test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);105test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);106test('can pass encoding "utf-8" to stdio[*] - sync', checkEncoding, 'utf-8', 3, execaSync);107test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);108test('can pass encoding "utf-16le" to stdio[*] - sync', checkEncoding, 'utf-16le', 3, execaSync);109test('can pass encoding "ucs2" to stdio[*] - sync', checkEncoding, 'ucs2', 3, execaSync);110test('can pass encoding "ucs-2" to stdio[*] - sync', checkEncoding, 'ucs-2', 3, execaSync);111test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);112test('can pass encoding "binary" to stdio[*] - sync', checkEncoding, 'binary', 3, execaSync);113test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);114test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);115test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);116test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);117/* eslint-enable unicorn/text-encoding-identifier-case */118119test('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
1import process from 'node:process';2import test from 'ava';3import {execa, execaSync} from '../index.js';4import {FIXTURES_DIR, setFixtureDir} from './helpers/fixtures-dir.js';5import {fullStdio} from './helpers/stdio.js';67const isWindows = process.platform === 'win32';89setFixtureDir();1011const TIMEOUT_REGEXP = /timed out after/;1212const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);13test('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});1914test('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');20test('empty error.all', async t => {21 const {all} = await t.throwsAsync(execa('fail.js', {all: true}));22 t.is(all, '');23});2425test('undefined error.all', async t => {26 const {all} = await t.throwsAsync(execa('fail.js'));27 t.is(all, undefined);28});2930test('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});3435const WRONG_COMMAND = isWindows36 ? '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.'37 : '';3825test('stdout/stderr/all on process errors', async t => {26 const {stdout, stderr, all} = await t.throwsAsync(execa('wrong command', {all: true}));39test('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});4632test('stdout/stderr/all on process errors, in sync mode', t => {33 const {stdout, stderr, all} = t.throws(() => {47test('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});5657test('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});6364test('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});7273test('exitCode is 0 on success', async t => {74 const {exitCode} = await execa('noop.js', ['foo']);75 t.is(exitCode, 0);76});7778const 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};8283test('exitCode is 2', testExitCode, 2);
3 unmodified lines
87test('error.message contains the command', async t => {88 await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});89});9059test('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'));91test('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});9565test('error.message does not contain stdout/stderr if not available', async t => {96test('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});100101test('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});105106test('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});11271test('error.shortMessage does not contain stdout/stderr', async t => {72 const {shortMessage} = await t.throwsAsync(execa('echo-fail.js'));113test('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});119120test('Original error.message is kept', async t => {121 const {originalMessage} = await t.throwsAsync(execa('noop.js', {cwd: 1}));
5 unmodified lines
127 t.false(failed);128});129130test('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});134135test('error.isTerminated is true if process was killed directly', async t => {
94 unmodified lines
230 t.is(signal, undefined);231});232233test('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});237238test('result.signalDescription is undefined for successful execution', async t => {
11 unmodified lines
250 t.is(code, 'ERR_INVALID_ARG_TYPE');251});252253test('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});257258test('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 lines
63 test('`forceKillAfterTimeout` should not be NaN', testInvalidForceKill, Number.NaN);64 test('`forceKillAfterTimeout` should not be negative', testInvalidForceKill, -1);65}6667test('execa() returns a promise with kill()', t => {68 const {kill} = execa('noop.js', ['foo']);69 t.is(typeof kill, 'function');67test('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});7273test('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 lines
modified:test/node.js+5 added
35 unmodified lines
3637 t.is(stdout, 'foo');38});3940test('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});4445test('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 lines
modified:test/pipe.js+28 added-28 removed
7 unmodified lines
8import {setFixtureDir} from './helpers/fixtures-dir.js';910setFixtureDir();1112const pipeToProcess = async (t, fixtureName, funcName) => {13 const {stdout} = await execa(fixtureName, ['test'], {all: true})[funcName](execa('stdin.js'));12const 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};1617test('pipeStdout() can pipe to Execa child processes', pipeToProcess, 'noop.js', 'pipeStdout');18test('pipeStderr() can pipe to Execa child processes', pipeToProcess, 'noop-err.js', 'pipeStderr');19test('pipeAll() can pipe stdout to Execa child processes', pipeToProcess, 'noop.js', 'pipeAll');20test('pipeAll() can pipe stderr to Execa child processes', pipeToProcess, 'noop-err.js', 'pipeAll');17test('pipeStdout() can pipe to Execa child processes', pipeToProcess, 1, 'pipeStdout');18test('pipeStderr() can pipe to Execa child processes', pipeToProcess, 2, 'pipeStderr');19test('pipeAll() can pipe stdout to Execa child processes', pipeToProcess, 1, 'pipeAll');20test('pipeAll() can pipe stderr to Execa child processes', pipeToProcess, 2, 'pipeAll');2122const pipeToStream = async (t, fixtureName, funcName, streamName) => {22const 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};2829test('pipeStdout() can pipe to streams', pipeToStream, 'noop.js', 'pipeStdout', 'stdout');30test('pipeStderr() can pipe to streams', pipeToStream, 'noop-err.js', 'pipeStderr', 'stderr');31test('pipeAll() can pipe stdout to streams', pipeToStream, 'noop.js', 'pipeAll', 'stdout');32test('pipeAll() can pipe stderr to streams', pipeToStream, 'noop-err.js', 'pipeAll', 'stderr');29test('pipeStdout() can pipe to streams', pipeToStream, 1, 'pipeStdout');30test('pipeStderr() can pipe to streams', pipeToStream, 2, 'pipeStderr');31test('pipeAll() can pipe stdout to streams', pipeToStream, 1, 'pipeAll');32test('pipeAll() can pipe stderr to streams', pipeToStream, 2, 'pipeAll');3334const pipeToFile = async (t, fixtureName, funcName, streamName) => {34const 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};4142// `test.serial()` is due to a race condition: `execa(...).pipe*(file)` might resolve before the file stream has resolved43test.serial('pipeStdout() can pipe to files', pipeToFile, 'noop.js', 'pipeStdout', 'stdout');44test.serial('pipeStderr() can pipe to files', pipeToFile, 'noop-err.js', 'pipeStderr', 'stderr');45test.serial('pipeAll() can pipe stdout to files', pipeToFile, 'noop.js', 'pipeAll', 'stdout');46test.serial('pipeAll() can pipe stderr to files', pipeToFile, 'noop-err.js', 'pipeAll', 'stderr');43test.serial('pipeStdout() can pipe to files', pipeToFile, 1, 'pipeStdout');44test.serial('pipeStderr() can pipe to files', pipeToFile, 2, 'pipeStderr');45test.serial('pipeAll() can pipe stdout to files', pipeToFile, 1, 'pipeAll');46test.serial('pipeAll() can pipe stderr to files', pipeToFile, 2, 'pipeAll');4748const 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 lines
68test('Must set "stdout" option to "pipe" to use pipeStdout()', invalidSource, 'pipeStdout');69test('Must set "stderr" option to "pipe" to use pipeStderr()', invalidSource, 'pipeStderr');70test('Must set "stdout" or "stderr" option to "pipe" to use pipeAll()', invalidSource, 'pipeAll');7172const invalidPipeToProcess = async (t, fixtureName, funcName) => {73 t.throws(() => execa(fixtureName, ['test'], {all: true})[funcName](execa('stdin.js', {stdin: 'ignore'})), {72const 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};7778test('Must set target "stdin" option to "pipe" to use pipeStdout()', invalidPipeToProcess, 'noop.js', 'pipeStdout');79test('Must set target "stdin" option to "pipe" to use pipeStderr()', invalidPipeToProcess, 'noop-err.js', 'pipeStderr');80test('Must set target "stdin" option to "pipe" to use pipeAll()', invalidPipeToProcess, 'noop.js', 'pipeAll');78test('Must set target "stdin" option to "pipe" to use pipeStdout()', invalidPipeToProcess, 1, 'pipeStdout');79test('Must set target "stdin" option to "pipe" to use pipeStderr()', invalidPipeToProcess, 2, 'pipeStderr');80test('Must set target "stdin" option to "pipe" to use pipeAll()', invalidPipeToProcess, 1, 'pipeAll');
modified:test/stream.js+186 added-168 removed
1import {Buffer} from 'node:buffer';2import {exec} from 'node:child_process';2import {once} from 'node:events';3import process from 'node:process';4import {setTimeout} from 'node:timers/promises';6import {promisify} from 'node:util';5import test from 'ava';6import getStream from 'get-stream';9import {pEvent} from 'p-event';7import {execa, execaSync} from '../index.js';11import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';8import {setFixtureDir} from './helpers/fixtures-dir.js';9import {fullStdio, getStdio} from './helpers/stdio.js';1013const pExec = promisify(exec);1411setFixtureDir();1217const 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));2021 const {stdout: nativeStdout} = await pExec(`node noop-no-newline.js ${STRING_TO_ENCODE}`, {encoding, cwd: FIXTURES_DIR});22 t.is(stdout, nativeStdout);23};2425// This string gives different outputs with each encoding type26const STRING_TO_ENCODE = '\u1000.';27const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);2829test('can pass encoding "utf8"', checkEncoding, 'utf8');30test('can pass encoding "utf-8"', checkEncoding, 'utf8');31test('can pass encoding "utf16le"', checkEncoding, 'utf16le');32test('can pass encoding "utf-16le"', checkEncoding, 'utf16le');33test('can pass encoding "ucs2"', checkEncoding, 'utf16le');34test('can pass encoding "ucs-2"', checkEncoding, 'utf16le');35test('can pass encoding "latin1"', checkEncoding, 'latin1');36test('can pass encoding "binary"', checkEncoding, 'latin1');37test('can pass encoding "ascii"', checkEncoding, 'ascii');38test('can pass encoding "hex"', checkEncoding, 'hex');39test('can pass encoding "base64"', checkEncoding, 'base64');40test('can pass encoding "base64url"', checkEncoding, 'base64url');4142const 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));4647 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};5152test('can pass encoding "buffer"', checkBufferEncoding, execa);53test('can pass encoding "buffer" - sync', checkBufferEncoding, execaSync);5455test('validate unknown encodings', async t => {56 await t.throwsAsync(execa('noop.js', {encoding: 'unknownEncoding'}), {code: 'ERR_UNKNOWN_ENCODING'});57});5813test.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 lines
3334test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');35test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');3683const testIgnore = async (t, streamName, execaMethod) => {84 const result = await execaMethod('noop.js', {[streamName]: 'ignore'});85 t.is(result[streamName], undefined);37const testIgnore = async (t, index, execaMethod) => {38 const result = await execaMethod('noop.js', getStdio(index, 'ignore'));39 t.is(result.stdio[index], undefined);40};4188test('stdout is undefined if ignored', testIgnore, 'stdout', execa);89test('stderr is undefined if ignored', testIgnore, 'stderr', execa);90test('stdout is undefined if ignored - sync', testIgnore, 'stdout', execaSync);91test('stderr is undefined if ignored - sync', testIgnore, 'stderr', execaSync);42test('stdout is undefined if ignored', testIgnore, 1, execa);43test('stderr is undefined if ignored', testIgnore, 2, execa);44test('stdio[*] is undefined if ignored', testIgnore, 3, execa);45test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);46test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);47test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);4893const 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}`)},49const maxBuffer = 10;5051const testMaxBufferSuccess = async (t, index, all) => {52 await t.notThrowsAsync(execa('max-buffer.js', [`${index}`, `${maxBuffer}`], {...fullStdio, maxBuffer, all}));53};5455test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, 1, false);56test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, 2, false);57test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, 3, false);58test('maxBuffer does not affect all if too high', testMaxBufferSuccess, 1, true);5960const 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};68103test('maxBuffer affects stdout', testMaxBuffer, 'stdout');104test('maxBuffer affects stderr', testMaxBuffer, 'stderr');69test('maxBuffer affects stdout', testMaxBufferLimit, 1, false);70test('maxBuffer affects stderr', testMaxBufferLimit, 2, false);71test('maxBuffer affects stdio[*]', testMaxBufferLimit, 3, false);72test('maxBuffer affects all', testMaxBufferLimit, 1, true);73106test('maxBuffer works with encoding buffer', async t => {107 const {stdout} = await t.throwsAsync(108 execa('max-buffer.js', ['stdout', '11'], {maxBuffer: 10, encoding: 'buffer'}),74const 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};82114test('maxBuffer works with other encodings', async t => {115 const {stdout} = await t.throwsAsync(116 execa('max-buffer.js', ['stdout', '11'], {maxBuffer: 10, encoding: 'hex'}),83test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, 1);84test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, 2);85test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, 3);8687const 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};93121const testNoMaxBuffer = async (t, streamName) => {122 const promise = execa('max-buffer.js', [streamName, '10'], {buffer: false});94test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);95test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);96test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);9798const 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 ]);127128 t.is(result[streamName], undefined);129 t.is(output, '.........\n');104 t.is(result.stdio[index], undefined);105 t.is(output, '.'.repeat(maxBuffer));106};107132test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 'stdout');133test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 'stderr');108test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1);109test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2);110test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3);111135test('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});112const 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};122141test('buffers when streaming and `buffer` is `true`', async t => {142 const childProcess = execa('max-buffer.js', ['stdout', '21'], {maxBuffer: 10});123test('do not hit maxBuffer when `buffer` is `false` with stdout', testNoMaxBufferOption, 1);124test('do not hit maxBuffer when `buffer` is `false` with stderr', testNoMaxBufferOption, 2);125test('do not hit maxBuffer when `buffer` is `false` with stdio[*]', testNoMaxBufferOption, 3);126127const 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};134135test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);136test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);137test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);138139test('buffer: false > promise resolves', async t => {140 await t.notThrowsAsync(execa('noop.js', {buffer: false}));141});142153test('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'}));143test('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});147157test('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});148const 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};155164test('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});156test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);157test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);158test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);159test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);160test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);161test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);162170test('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});163const testBufferIgnore = async (t, index, all) => {164 await t.notThrowsAsync(execa('max-buffer.js', [`${index}`], {...getStdio(index, 'ignore'), buffer: false, all}));165};166176test('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});167test('Process buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);168test('Process buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);169test('Process buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);170171// This specific behavior does not happen on Windows.172// Also, on macOS, it randomly happens, which would make those tests randomly fail.173if (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 };178189 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);183193 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 };190200 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}196205test('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});197const 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};203211test.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});204test('Destroying stdin should make the process exit', testStreamDestroy, 0);205test('Destroying stdout should make the process exit', testStreamDestroy, 1);206test('Destroying stderr should make the process exit', testStreamDestroy, 2);207test('Destroying stdio[*] should make the process exit', testStreamDestroy, 3);208219test.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});209const 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};216226test.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});217test('Errors on stdin should make the process exit', testStreamError, 0);218test('Errors on stdout should make the process exit', testStreamError, 1);219test('Errors on stderr should make the process exit', testStreamError, 2);220test('Errors on stdio[*] should make the process exit', testStreamError, 3);221233test.serial('Process buffers stdout right away, on failure', async t => {234 const childProcess = execa('noop-fail.js', ['foobar'], {reject: false});235 await setTimeout(1e3);222const 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};229240test('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');230test.serial('Process waits on stdin before exiting', testWaitOnStreamEnd, 0);231test.serial('Process waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);232233const 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};239240test.serial('Process buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);241test.serial('Process buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);242test.serial('Process buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);243test.serial('Process buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);244test.serial('Process buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);245test.serial('Process buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);246test.serial('Process buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);247test.serial('Process buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);248test.serial('Process buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);249250const 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};257258test('Process buffers stdout right away, even if directly read', testBufferDirect, 1);259test('Process buffers stderr right away, even if directly read', testBufferDirect, 2);260test('Process buffers stdio[*] right away, even if directly read', testBufferDirect, 3);261248test('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});262const 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};268269test('childProcess.stdout must be read right away', testBufferDestroyOnEnd, 1);270test('childProcess.stderr must be read right away', testBufferDestroyOnEnd, 2);271test('childProcess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);
modified:test/test.js+52 added-60 removed
1import path from 'node:path';2import process from 'node:process';3import {setTimeout} from 'node:timers/promises';3import {fileURLToPath, pathToFileURL} from 'node:url';4import test from 'ava';5import isRunning from 'is-running';6import getNode from 'get-node';7import which from 'which';8import {execa, execaSync, execaNode, $} from '../index.js';9import {setFixtureDir, PATH_KEY, FIXTURES_DIR_URL} from './helpers/fixtures-dir.js';10import {identity, fullStdio} from './helpers/stdio.js';11import {stringGenerator} from './helpers/generator.js';1213setFixtureDir();14process.env.FOO = 'foo';1516const ENOENT_REGEXP = process.platform === 'win32' ? /failed with exit code 1/ : /spawn.* ENOENT/;1717const identity = value => value;18const testOutput = async (t, index, execaCommand) => {19 const {stdout, stderr, stdio} = await execaCommand('noop-fd.js', [`${index}`, 'foobar'], fullStdio);20 t.is(stdio[index], 'foobar');2119test('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};2829test('can return stdout', testOutput, 1, execa);30test('can return stderr', testOutput, 2, execa);31test('can return output stdio[*]', testOutput, 3, execa);32test('can return stdout - sync', testOutput, 1, execaSync);33test('can return stderr - sync', testOutput, 2, execaSync);34test('can return output stdio[*] - sync', testOutput, 3, execaSync);3536const testNoStdin = async (t, execaCommand) => {37 const {stdio} = await execaCommand('noop.js', ['foobar']);38 t.is(stdio[0], undefined);39};4041test('cannot return stdin', testNoStdin, execa);42test('cannot return stdin - sync', testNoStdin, execaSync);4344test('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});4849if (process.platform === 'win32') {50 test('execa() - cmd file', async t => {
6 unmodified lines
57 t.is(stdout, 'Hello World');58 });59}6036test('execaSync()', t => {37 const {stdout} = execaSync('noop.js', ['foo']);38 t.is(stdout, 'foo');39});4041test('execaSync() throws error if written to stderr', t => {61test('execaSync() throws error if ENOENT', t => {62 t.throws(() => {63 execaSync('foo');64 }, {message: ENOENT_REGEXP});65});
7 unmodified lines
73 const {exitCode} = execaSync('fail.js', {reject: false});74 t.is(exitCode, 2);75});7657test('stripFinalNewline: true', async t => {58 const {stdout} = await execa('noop.js', ['foo']);59 t.is(stdout, 'foo');60});77const 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};8162test('stripFinalNewline: false', async t => {63 const {stdout} = await execa('noop.js', ['foo'], {stripFinalNewline: false});64 t.is(stdout, 'foo\n');65});82test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, undefined, execa);83test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, execa);84test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, undefined, execa);85test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, execa);86test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, undefined, execa);87test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, execa);88test('stripFinalNewline: true with stdout - sync', testStripFinalNewline, 1, undefined, execaSync);89test('stripFinalNewline: false with stdout - sync', testStripFinalNewline, 1, false, execaSync);90test('stripFinalNewline: true with stderr - sync', testStripFinalNewline, 2, undefined, execaSync);91test('stripFinalNewline: false with stderr - sync', testStripFinalNewline, 2, false, execaSync);92test('stripFinalNewline: true with stdio[*] - sync', testStripFinalNewline, 3, undefined, execaSync);93test('stripFinalNewline: false with stdio[*] - sync', testStripFinalNewline, 3, false, execaSync);9467test('stripFinalNewline on failure', async t => {68 const {stderr} = await t.throwsAsync(execa('noop-throw.js', ['foo'], {stripFinalNewline: true}));69 t.is(stderr, 'foo');70});7172test('stripFinalNewline in sync mode', t => {73 const {stdout} = execaSync('noop.js', ['foo'], {stripFinalNewline: true});74 t.is(stdout, 'foo');75});7677test('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});8395const 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 lines
135136test.serial('execPath option', testExecPath, identity);137test.serial('execPath option can be a file URL', testExecPath, pathToFileURL);138128const emitStdinError = async subprocess => {129 await setTimeout(0);130 subprocess.stdin.emit('error', new Error('test'));131};132133test('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});140139test('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});144147test('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/});145test('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});150153test('execa() returns a promise with pid', t => {154 const {pid} = execa('noop.js', ['foo']);155 t.is(typeof pid, 'number');156});157151test('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 lines
184});185186if (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 });190191 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 lines
modified:index.d.ts+12 added-5 removed
239 unmodified lines
240 */241 readonly shell?: boolean | string | URL;242243 /**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.245246 @default 'utf8'247 */248 readonly encoding?: EncodingType;
5 unmodified lines
254 */255 readonly timeout?: number;256257 /**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.259260 @default 100_000_000261 */262 readonly maxBuffer?: number;
165 unmodified lines
428 */429 stderr: StdoutStderrType;430431 /**432 The output of the process on `stdin`, `stdout`, `stderr` and other file descriptors.433434 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>];437438 /**439 Whether the process failed to run.440 */441 failed: boolean;442
52 unmodified lines
495export 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.498492 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;502503 /**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;507508 /**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.510511 This is `undefined` unless the child process exited due to an `error` event or a timeout.512 */513 originalMessage?: string;
547 unmodified lines
modified:index.js+23 added-36 removed
78 unmodified lines
7980 return {file, args, command, escapedCommand, options};81};8283const handleOutputSync = (options, value, error) => {84 if (Buffer.isBuffer(value)) {85 value = bufferToUint8Array(value);86 }8788 return handleOutput(options, value, error);89};9091const handleOutput = (options, value, error) => {83const 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 }8797 if (options.stripFinalNewline) {98 return stripFinalNewline(value);88 if (Buffer.isBuffer(value)) {89 value = bufferToUint8Array(value);90 }91101 return value;92 return options.stripFinalNewline ? stripFinalNewline(value) : value;93};9495export function execa(rawFile, rawArgs, rawOptions) {96 const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, rawOptions);97 validateTimeout(options);98108 const stdioStreams = handleInputAsync(options);99 const {stdioStreams, stdioLength} = handleInputAsync(options);100101 let spawned;102 try {103 spawned = childProcess.spawn(file, args, options);
1 unmodified line
105 // 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 lines
136137const 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);145146 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 lines
168 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 lines
182183export function execaSync(rawFile, rawArgs, rawOptions) {184 const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, rawOptions);185198 const stdioStreams = handleInputSync(options);186 const {stdioStreams, stdioLength} = handleInputSync(options);187188 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 line
200 });201 }202203 pipeOutputSync(stdioStreams, result);218 const stdout = handleOutputSync(options, result.stdout, result.error);219 const stderr = handleOutputSync(options, result.stderr, result.error);204205 const output = result.output || [undefined, undefined, undefined];206 const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));207208 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 lines
228 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 lines
modified:index.test-d.ts+16 added
61 unmodified lines
62 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 lines
81 const execaError = error as ExecaError<false>;8283 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 lines
105 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 lines
128129 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 lines
modified:readme.md+19 added-11 removed
253 unmodified lines
254255Like [`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)259260#### $\`command\`261262Executes a command. The `command` string includes both the `file` and its `arguments`. Returns a [`childProcess`](#childprocess).
25 unmodified lines
288### execaSync(file, arguments?, options?)289290Same as [`execa()`](#execacommandcommand-options) but synchronous.291292Cannot 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.292Cannot 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.293294Returns or throws a [`childProcessResult`](#childProcessResult).295296### $.sync\`command\`297### $.s\`command\`298299Same as [$\`command\`](#command) but synchronous.300301Cannot 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.301Cannot 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.302303Returns or throws a [`childProcessResult`](#childProcessResult).304305### execaCommandSync(command, options?)306307Same as [`execaCommand()`](#execacommand-command-options) but synchronous.308309Cannot 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.309Cannot 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.310311Returns or throws a [`childProcessResult`](#childProcessResult).312313### Shell syntax
117 unmodified lines
431This 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)434435#### stdio436437Type: `Array<string | Uint8Array | undefined>`438439The output of the process on [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1) and [other file descriptors](#stdio-1).440441Items 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).442443#### failed444445Type: `boolean`446
50 unmodified lines
497Type: `string`498499Error 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.500493The child process [`stderr`](#stderr) then [`stdout`](#stdout) are appended to the end, separated with newlines and not interleaved.501The child process [`stderr`](#stderr), [`stdout`](#stdout) and other [file descriptors' output](#stdio) are appended to the end, separated with newlines and not interleaved.502503#### shortMessage504505Type: `string`506499This is the same as the [`message` property](#message) except it does not include the child process `stdout`/`stderr`.507This is the same as the [`message` property](#message) except it does not include the child process [`stdout`](#stdout)/[`stderr`](#stderr)/[`stdio`](#stdio).508509#### originalMessage510511Type: `string | undefined`512505Original error message. This is the same as the `message` property excluding the child process `stdout`/`stderr` and some additional information added by Execa.513Original 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.514515This is `undefined` unless the child process exited due to an `error` event or a timeout.516517### options
43 unmodified lines
561Default: `true`562563Buffer 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.564557If the spawned process fails, [`error.stdout`](#stdout), [`error.stderr`](#stderr), and [`error.all`](#all) will contain the buffered data.565If the spawned process fails, [`error.stdout`](#stdout), [`error.stderr`](#stderr), [`error.all`](#all) and [`error.stdio`](#stdio) will contain the buffered data.566567#### input568569Type: `string | Uint8Array | stream.Readable`
136 unmodified lines
706707Type: `string`\708Default: `'json'`709702Specify the kind of serialization used for sending messages between processes when using the [`stdio: 'ipc'`](#stdio) option or [`execaNode()`](#execanodescriptpath-arguments-options):710Specify 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)713714[More info.](https://nodejs.org/api/child_process.html#child_process_advanced_serialization)
32 unmodified lines
747748Type: `string`\749Default: `utf8`750743Specify 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.751Specify 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.752753#### timeout754755Type: `number`\
5 unmodified lines
761762Type: `number`\763Default: `100_000_000` (100 MB)764757Largest amount of data in bytes allowed on `stdout` or `stderr`.765Largest amount of data in bytes allowed on [`stdout`](#stdout), [`stderr`](#stderr) and [`stdio`](#stdio).766767#### killSignal768769Type: `string | number`\
168 unmodified lines