Skip to content
Myr

Improve piping processes (#834)

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

authored by ehmicky · committed by GitHub · parent 30a662d · Browse files · 23 files+1511 added−256 removed
This commit

State

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

Diff stats

23 files+1511 added−256 removed

  • tests:+1114 added−110 removed
  • other:+397 added−146 removed

23 files+1511 added−256 removed

modified:docs/scripts.md+6 added-4 removed
586 unmodified lines
587### Piping stdout to another command588589```sh590# Bash591echo example | cat591echo npm run build | sort | head -n2592```593594```js595// zx596await $`echo example | cat`;596await $`npm run build | sort | head -n2`;597```598599```js600// Execa601await $`echo example`.pipe($({stdin: 'pipe'})`cat`);601await $`npm run build`602 .pipe($({stdin: 'pipe'})`sort`)603 .pipe($({stdin: 'pipe'})`head -n2`);604```605606### Piping stdout and stderr to another command607
12 unmodified lines
620```621622```js623// Execa622await $({all: true})`echo example`.pipe($({stdin: 'pipe'})`cat`, 'all');624await $({all: true})`echo example`.pipe($({from: 'all', stdin: 'pipe'})`cat`);625```626627### Piping stdout to a file628
50 unmodified lines
added:lib/pipe/abort.js+13 added
added:lib/pipe/sequence.js+24 added
added:lib/pipe/setup.js+25 added
added:lib/pipe/streaming.js+69 added
added:lib/pipe/validate.js+145 added
1import {ChildProcess} from 'node:child_process';2import {STANDARD_STREAMS_ALIASES} from '../stdio/utils.js';3import {makeEarlyError} from '../error.js';4import {abortSourceStream, endDestinationStream} from './streaming.js';56export const normalizePipeArguments = (destination, from, {spawned: source, stdioStreamsGroups, options}) => {7 const {destinationStream, destinationError} = getDestinationStream(destination);8 const {sourceStream, sourceError} = getSourceStream(source, stdioStreamsGroups, from, options);9 handlePipeArgumentsError({sourceStream, sourceError, destinationStream, destinationError, stdioStreamsGroups, options});10 return {source, sourceStream, destinationStream};11};1213const getDestinationStream = destination => {14 try {15 if (!isExecaChildProcess(destination)) {16 throw new TypeError('The first argument must be an Execa child process.');17 }1819 const destinationStream = destination.stdin;20 if (destinationStream === null) {21 throw new TypeError('The destination child process\'s stdin must be available. Please set its "stdin" option to "pipe".');22 }2324 return {destinationStream};25 } catch (error) {26 return {destinationError: error};27 }28};2930const isExecaChildProcess = destination => destination instanceof ChildProcess31 && typeof destination.then === 'function'32 && typeof destination.pipe === 'function';3334const getSourceStream = (source, stdioStreamsGroups, from, options) => {35 try {36 const streamIndex = getStreamIndex(stdioStreamsGroups, from);37 const sourceStream = streamIndex === 'all' ? source.all : source.stdio[streamIndex];3839 if (sourceStream === null || sourceStream === undefined) {40 throw new TypeError(getInvalidStdioOptionMessage(streamIndex, from, options));41 }4243 return {sourceStream};44 } catch (error) {45 return {sourceError: error};46 }47};4849const getStreamIndex = (stdioStreamsGroups, from = 'stdout') => {50 const streamIndex = STANDARD_STREAMS_ALIASES.includes(from)51 ? STANDARD_STREAMS_ALIASES.indexOf(from)52 : from;5354 if (streamIndex === 'all') {55 return streamIndex;56 }5758 if (streamIndex === 0) {59 throw new TypeError('The "from" option must not be "stdin".');60 }6162 if (!Number.isInteger(streamIndex) || streamIndex < 0) {63 throw new TypeError(`The "from" option must not be "${streamIndex}".64It must be "stdout", "stderr", "all" or a file descriptor integer.65It is optional and defaults to "stdout".`);66 }6768 const stdioStreams = stdioStreamsGroups[streamIndex];69 if (stdioStreams === undefined) {70 throw new TypeError(`The "from" option must not be ${streamIndex}. That file descriptor does not exist.71Please set the "stdio" option to ensure that file descriptor exists.`);72 }7374 if (stdioStreams[0].direction === 'input') {75 throw new TypeError(`The "from" option must not be ${streamIndex}. It must be a readable stream, not writable.`);76 }7778 return streamIndex;79};8081const getInvalidStdioOptionMessage = (streamIndex, from, options) => {82 if (streamIndex === 'all' && !options.all) {83 return 'The "all" option must be true to use `childProcess.pipe(destinationProcess, {from: "all"})`.';84 }8586 const {optionName, optionValue} = getInvalidStdioOption(streamIndex, options);87 const pipeOptions = from === undefined ? '' : `, {from: ${serializeOptionValue(from)}}`;88 return `The \`${optionName}: ${serializeOptionValue(optionValue)}\` option is incompatible with using \`childProcess.pipe(destinationProcess${pipeOptions})\`.89Please set this option with "pipe" instead.`;90};9192const getInvalidStdioOption = (streamIndex, {stdout, stderr, stdio}) => {93 const usedIndex = streamIndex === 'all' ? 1 : streamIndex;9495 if (usedIndex === 1 && stdout !== undefined) {96 return {optionName: 'stdout', optionValue: stdout};97 }9899 if (usedIndex === 2 && stderr !== undefined) {100 return {optionName: 'stderr', optionValue: stderr};101 }102103 return {optionName: `stdio[${usedIndex}]`, optionValue: stdio[usedIndex]};104};105106const serializeOptionValue = optionValue => {107 if (typeof optionValue === 'string') {108 return `"${optionValue}"`;109 }110111 return typeof optionValue === 'number' ? `${optionValue}` : 'Stream';112};113114const handlePipeArgumentsError = ({sourceStream, sourceError, destinationStream, destinationError, stdioStreamsGroups, options}) => {115 const error = getPipeArgumentsError({sourceStream, sourceError, destinationStream, destinationError});116 if (error !== undefined) {117 throw createNonCommandError({error, stdioStreamsGroups, options});118 }119};120121const getPipeArgumentsError = ({sourceStream, sourceError, destinationStream, destinationError}) => {122 if (sourceError !== undefined && destinationError !== undefined) {123 return destinationError;124 }125126 if (destinationError !== undefined) {127 abortSourceStream(sourceStream);128 return destinationError;129 }130131 if (sourceError !== undefined) {132 endDestinationStream(destinationStream);133 return sourceError;134 }135};136137export const createNonCommandError = ({error, stdioStreamsGroups, options}) => makeEarlyError({138 error,139 command: PIPE_COMMAND_MESSAGE,140 escapedCommand: PIPE_COMMAND_MESSAGE,141 stdioStreamsGroups,142 options,143});144145const PIPE_COMMAND_MESSAGE = 'source.pipe(destination)';
modified:lib/error.js+3 added
145 unmodified lines
146 if ('bufferedData' in error) {147 delete error.bufferedData;148 }149150 error.pipedFrom = [];151152 return error;153};154155export const makeEarlyError = ({
30 unmodified lines
186 stdout: stdio[1],187 stderr: stdio[2],188 all,189 stdio,190 pipedFrom: [],191});
deleted:lib/pipe.js-95 removed
1import {ChildProcess} from 'node:child_process';2import {isWritableStream} from 'is-stream';3import {STANDARD_STREAMS_ALIASES} from './stdio/utils.js';45export const pipeToProcess = ({spawned, stdioStreamsGroups, options}, targetProcess, streamName) => {6 validateTargetProcess(targetProcess);78 const streamIndex = getStreamIndex(streamName);9 const inputStream = getInputStream(spawned, streamIndex, stdioStreamsGroups);10 validateStdioOption(inputStream, streamIndex, streamName, options);1112 inputStream.pipe(targetProcess.stdin);13 return targetProcess;14};1516const validateTargetProcess = targetProcess => {17 if (!isExecaChildProcess(targetProcess)) {18 throw new TypeError('The first argument must be an Execa child process.');19 }2021 if (!isWritableStream(targetProcess.stdin)) {22 throw new TypeError('The target child process\'s stdin must be available.');23 }24};2526const isExecaChildProcess = target => target instanceof ChildProcess && typeof target.then === 'function';2728const getStreamIndex = (streamName = 'stdout') => STANDARD_STREAMS_ALIASES.includes(streamName)29 ? STANDARD_STREAMS_ALIASES.indexOf(streamName)30 : streamName;3132const getInputStream = (spawned, streamIndex, stdioStreamsGroups) => {33 if (streamIndex === 'all') {34 return spawned.all;35 }3637 if (streamIndex === 0) {38 throw new TypeError('The second argument must not be "stdin".');39 }4041 if (!Number.isInteger(streamIndex) || streamIndex < 0) {42 throw new TypeError(`The second argument must not be "${streamIndex}".43It must be "stdout", "stderr", "all" or a file descriptor integer.44It is optional and defaults to "stdout".`);45 }4647 const stdioStreams = stdioStreamsGroups[streamIndex];48 if (stdioStreams === undefined) {49 throw new TypeError(`The second argument must not be ${streamIndex}: that file descriptor does not exist.50Please set the "stdio" option to ensure that file descriptor exists.`);51 }5253 if (stdioStreams[0].direction === 'input') {54 throw new TypeError(`The second argument must not be ${streamIndex}: it must be a readable stream, not writable.`);55 }5657 return spawned.stdio[streamIndex];58};5960const validateStdioOption = (inputStream, streamIndex, streamName, options) => {61 if (inputStream !== null && inputStream !== undefined) {62 return;63 }6465 if (streamIndex === 'all' && !options.all) {66 throw new TypeError('The "all" option must be true to use `childProcess.pipe(targetProcess, "all")`.');67 }6869 const {optionName, optionValue} = getInvalidStdioOption(streamIndex, options);70 const pipeArgument = streamName === undefined ? '' : `, ${streamName}`;71 throw new TypeError(`The \`${optionName}: ${serializeOptionValue(optionValue)}\` option is incompatible with using \`childProcess.pipe(targetProcess${pipeArgument})\`.72Please set this option with "pipe" instead.`);73};7475const getInvalidStdioOption = (streamIndex, {stdout, stderr, stdio}) => {76 const usedIndex = streamIndex === 'all' ? 1 : streamIndex;7778 if (usedIndex === 1 && stdout !== undefined) {79 return {optionName: 'stdout', optionValue: stdout};80 }8182 if (usedIndex === 2 && stderr !== undefined) {83 return {optionName: 'stderr', optionValue: stderr};84 }8586 return {optionName: `stdio[${usedIndex}]`, optionValue: stdio[usedIndex]};87};8889const serializeOptionValue = optionValue => {90 if (typeof optionValue === 'string') {91 return `"${optionValue}"`;92 }9394 return typeof optionValue === 'number' ? `${optionValue}` : 'Stream';95};
added:test/fixtures/noop-stdin-double.js+6 added
added:test/fixtures/stdin-both.js+5 added
added:test/fixtures/stdin-fail.js+5 added
1#!/usr/bin/env node2import process from 'node:process';34process.stdin.pipe(process.stdout);5process.exitCode = 2;
added:test/pipe/abort.js+167 added
1import {once} from 'node:events';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {foobarString} from '../helpers/input.js';67setFixtureDir();89const assertUnPipeError = async (t, pipePromise) => {10 const error = await t.throwsAsync(pipePromise);1112 t.is(error.command, 'source.pipe(destination)');13 t.is(error.escapedCommand, error.command);1415 t.is(typeof error.cwd, 'string');16 t.true(error.failed);17 t.false(error.timedOut);18 t.false(error.isCanceled);19 t.false(error.isTerminated);20 t.is(error.exitCode, undefined);21 t.is(error.signal, undefined);22 t.is(error.signalDescription, undefined);23 t.is(error.stdout, undefined);24 t.is(error.stderr, undefined);25 t.is(error.all, undefined);26 t.deepEqual(error.stdio, Array.from({length: error.stdio.length}));27 t.deepEqual(error.pipedFrom, []);2829 t.true(error.originalMessage.includes('Pipe cancelled'));30 t.true(error.shortMessage.includes(`Command failed: ${error.command}`));31 t.true(error.shortMessage.includes(error.originalMessage));32 t.true(error.message.includes(error.shortMessage));33};3435test('Can unpipe a single process', async t => {36 const abortController = new AbortController();37 const source = execa('stdin.js');38 const destination = execa('stdin.js');39 const pipePromise = source.pipe(destination, {signal: abortController.signal});4041 abortController.abort();42 await assertUnPipeError(t, pipePromise);4344 source.stdin.end(foobarString);45 destination.stdin.end('.');4647 t.like(await destination, {stdout: '.'});48 t.like(await source, {stdout: foobarString});49});5051test('Can use an already aborted signal', async t => {52 const abortController = new AbortController();53 abortController.abort();54 const source = execa('empty.js');55 const destination = execa('empty.js');56 const pipePromise = source.pipe(destination, {signal: abortController.signal});5758 await assertUnPipeError(t, pipePromise);59});6061test('Can unpipe a process among other sources', async t => {62 const abortController = new AbortController();63 const source = execa('stdin.js');64 const secondSource = execa('noop.js', [foobarString]);65 const destination = execa('stdin.js');66 const pipePromise = source.pipe(destination, {signal: abortController.signal});67 const secondPipePromise = secondSource.pipe(destination);6869 abortController.abort();70 await assertUnPipeError(t, pipePromise);7172 source.stdin.end('.');7374 t.is(await secondPipePromise, await destination);75 t.like(await destination, {stdout: foobarString});76 t.like(await source, {stdout: '.'});77 t.like(await secondSource, {stdout: foobarString});78});7980test('Can unpipe a process among other sources on the same process', async t => {81 const abortController = new AbortController();82 const source = execa('stdin-both.js');83 const destination = execa('stdin.js');84 const pipePromise = source.pipe(destination, {signal: abortController.signal});85 const secondPipePromise = source.pipe(destination, {from: 'stderr'});8687 abortController.abort();88 await assertUnPipeError(t, pipePromise);8990 source.stdin.end(foobarString);9192 t.is(await secondPipePromise, await destination);93 t.like(await destination, {stdout: foobarString});94 t.like(await source, {stdout: foobarString, stderr: foobarString});95});9697test('Can unpipe a process among other destinations', async t => {98 const abortController = new AbortController();99 const source = execa('stdin.js');100 const destination = execa('stdin.js');101 const secondDestination = execa('stdin.js');102 const pipePromise = source.pipe(destination, {signal: abortController.signal});103 const secondPipePromise = source.pipe(secondDestination);104105 abortController.abort();106 await assertUnPipeError(t, pipePromise);107108 source.stdin.end(foobarString);109 destination.stdin.end('.');110111 t.is(await secondPipePromise, await secondDestination);112 t.like(await destination, {stdout: '.'});113 t.like(await source, {stdout: foobarString});114 t.like(await secondDestination, {stdout: foobarString});115});116117test('Can unpipe then re-pipe a process', async t => {118 const abortController = new AbortController();119 const source = execa('stdin.js');120 const destination = execa('stdin.js');121 const pipePromise = source.pipe(destination, {signal: abortController.signal});122123 source.stdin.write('.');124 const [firstWrite] = await once(source.stdout, 'data');125 t.is(firstWrite.toString(), '.');126127 abortController.abort();128 await assertUnPipeError(t, pipePromise);129130 source.pipe(destination);131 source.stdin.end('.');132133 t.like(await destination, {stdout: '..'});134 t.like(await source, {stdout: '..'});135});136137test('Can unpipe to prevent termination to propagate to source', async t => {138 const abortController = new AbortController();139 const source = execa('stdin.js');140 const destination = execa('stdin.js');141 const pipePromise = source.pipe(destination, {signal: abortController.signal});142143 abortController.abort();144 await assertUnPipeError(t, pipePromise);145146 destination.kill();147 t.like(await t.throwsAsync(destination), {signal: 'SIGTERM'});148149 source.stdin.end(foobarString);150 t.like(await source, {stdout: foobarString});151});152153test('Can unpipe to prevent termination to propagate to destination', async t => {154 const abortController = new AbortController();155 const source = execa('noop-forever.js', [foobarString]);156 const destination = execa('stdin.js');157 const pipePromise = source.pipe(destination, {signal: abortController.signal});158159 abortController.abort();160 await assertUnPipeError(t, pipePromise);161162 source.kill();163 t.like(await t.throwsAsync(source), {signal: 'SIGTERM'});164165 destination.stdin.end(foobarString);166 t.like(await destination, {stdout: foobarString});167});
added:test/pipe/sequence.js+313 added
1import {once} from 'node:events';2import process from 'node:process';3import {PassThrough} from 'node:stream';4import test from 'ava';5import {execa} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';7import {foobarString} from '../helpers/input.js';8import {noopGenerator} from '../helpers/generator.js';9import {prematureClose} from '../helpers/stdio.js';1011setFixtureDir();1213const isLinux = process.platform === 'linux';1415test('Source stream abort -> destination success', async t => {16 const source = execa('noop-repeat.js');17 const destination = execa('stdin.js');18 const pipePromise = source.pipe(destination);19 source.stdout.destroy();2021 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));22 t.like(await t.throwsAsync(source), {exitCode: 1});23 await destination;24});2526test('Source stream error -> destination success', async t => {27 const source = execa('noop-repeat.js');28 const destination = execa('stdin.js');29 const pipePromise = source.pipe(destination);30 const error = new Error('test');31 source.stdout.destroy(error);3233 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));34 t.like(await t.throwsAsync(source), {originalMessage: error.originalMessage, exitCode: 1});35 await destination;36});3738test('Destination stream abort -> source failure', async t => {39 const source = execa('noop-repeat.js');40 const destination = execa('stdin.js');41 const pipePromise = source.pipe(destination);42 destination.stdin.destroy();4344 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));45 t.like(await t.throwsAsync(destination), prematureClose);46 t.like(await t.throwsAsync(source), {exitCode: 1});47});4849test('Destination stream error -> source failure', async t => {50 const source = execa('noop-repeat.js');51 const destination = execa('stdin.js');52 const pipePromise = source.pipe(destination);53 const error = new Error('test');54 destination.stdin.destroy(error);5556 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));57 t.like(await t.throwsAsync(destination), {originalMessage: error.originalMessage, exitCode: 0});58 t.like(await t.throwsAsync(source), {exitCode: 1});59});6061test('Source success -> destination success', async t => {62 const source = execa('noop.js', [foobarString]);63 const destination = execa('stdin.js');64 const pipePromise = source.pipe(destination);6566 t.like(await source, {stdout: foobarString});67 t.like(await destination, {stdout: foobarString});68 t.is(await pipePromise, await destination);69});7071test('Destination stream end -> source failure', async t => {72 const source = execa('noop-repeat.js');73 const destination = execa('stdin.js');74 const pipePromise = source.pipe(destination);75 destination.stdin.end();7677 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));78 await destination;79 t.like(await t.throwsAsync(source), {exitCode: 1});80});8182test('Source normal failure -> destination success', async t => {83 const source = execa('noop-fail.js', ['1', foobarString]);84 const destination = execa('stdin.js');85 const pipePromise = source.pipe(destination);8687 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));88 t.like(await t.throwsAsync(source), {stdout: foobarString, exitCode: 2});89 await destination;90});9192test('Source normal failure -> deep destination success', async t => {93 const source = execa('noop-fail.js', ['1', foobarString]);94 const destination = execa('stdin.js');95 const secondDestination = execa('stdin.js');96 const pipePromise = source.pipe(destination);97 const secondPipePromise = destination.pipe(secondDestination);9899 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));100 await secondPipePromise;101 t.like(await t.throwsAsync(source), {stdout: foobarString, exitCode: 2});102 await destination;103 await secondDestination;104});105106const testSourceTerminated = async (t, signal) => {107 const source = execa('noop-repeat.js');108 const destination = execa('stdin.js');109 const pipePromise = source.pipe(destination);110 source.kill(signal);111112 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));113 t.like(await t.throwsAsync(source), {signal});114 await destination;115};116117test('Source SIGTERM -> destination success', testSourceTerminated, 'SIGTERM');118test('Source SIGKILL -> destination success', testSourceTerminated, 'SIGKILL');119120test('Destination success before source -> source success', async t => {121 const passThroughStream = new PassThrough();122 const source = execa('stdin.js', {stdin: ['pipe', passThroughStream]});123 const destination = execa('empty.js');124 const pipePromise = source.pipe(destination);125126 await destination;127 passThroughStream.end();128 await source;129 t.is(await pipePromise, await destination);130});131132test('Destination normal failure -> source failure', async t => {133 const source = execa('noop-repeat.js');134 const destination = execa('fail.js');135 const pipePromise = source.pipe(destination);136137 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));138 t.like(await t.throwsAsync(destination), {exitCode: 2});139 t.like(await t.throwsAsync(source), {exitCode: 1});140});141142test('Destination normal failure -> deep source failure', async t => {143 const source = execa('noop-repeat.js');144 const destination = execa('stdin.js');145 const secondDestination = execa('fail.js');146 const pipePromise = source.pipe(destination);147 const secondPipePromise = destination.pipe(secondDestination);148149 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));150 t.is(await t.throwsAsync(secondPipePromise), await t.throwsAsync(secondDestination));151 t.like(await t.throwsAsync(secondDestination), {exitCode: 2});152 t.like(await t.throwsAsync(destination), {exitCode: 1});153 t.like(await t.throwsAsync(source), {exitCode: 1});154});155156const testDestinationTerminated = async (t, signal) => {157 const source = execa('noop-repeat.js');158 const destination = execa('stdin.js');159 const pipePromise = source.pipe(destination);160 destination.kill(signal);161162 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));163 t.like(await t.throwsAsync(destination), {signal});164 t.like(await t.throwsAsync(source), {exitCode: 1});165};166167test('Destination SIGTERM -> source abort', testDestinationTerminated, 'SIGTERM');168test('Destination SIGKILL -> source abort', testDestinationTerminated, 'SIGKILL');169170test('Source already ended -> ignore source', async t => {171 const source = execa('noop.js', [foobarString]);172 await source;173 const destination = execa('stdin.js');174 const pipePromise = source.pipe(destination);175176 t.is(await pipePromise, await destination);177 t.like(await source, {stdout: foobarString});178 t.like(await destination, {stdout: ''});179});180181test('Source already aborted -> ignore source', async t => {182 const source = execa('noop.js', [foobarString]);183 source.stdout.destroy();184 const destination = execa('stdin.js');185 const pipePromise = source.pipe(destination);186187 t.is(await pipePromise, await destination);188 t.like(await source, {stdout: ''});189 t.like(await destination, {stdout: ''});190});191192test('Source already errored -> failure', async t => {193 const source = execa('noop.js', [foobarString]);194 const error = new Error('test');195 source.stdout.destroy(error);196 const destination = execa('stdin.js');197 const pipePromise = source.pipe(destination);198199 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));200 t.is(await t.throwsAsync(source), error);201 t.like(await destination, {stdout: ''});202});203204test('Destination already ended -> ignore source', async t => {205 const destination = execa('stdin.js');206 destination.stdin.end('.');207 await destination;208 const source = execa('noop.js', [foobarString]);209 const pipePromise = source.pipe(destination);210211 t.is(await pipePromise, await destination);212 t.like(await destination, {stdout: '.'});213 t.like(await source, {stdout: ''});214});215216test('Destination already aborted -> failure', async t => {217 const destination = execa('stdin.js');218 destination.stdin.destroy();219 t.like(await t.throwsAsync(destination), prematureClose);220 const source = execa('noop.js', [foobarString]);221 const pipePromise = source.pipe(destination);222223 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));224 t.like(await source, {stdout: ''});225});226227test('Destination already errored -> failure', async t => {228 const destination = execa('stdin.js');229 const error = new Error('test');230 destination.stdin.destroy(error);231 t.is(await t.throwsAsync(destination), error);232 const source = execa('noop.js', [foobarString]);233 const pipePromise = source.pipe(destination);234235 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));236 t.like(await source, {stdout: ''});237});238239test('Source normal failure + destination normal failure', async t => {240 const source = execa('noop-fail.js', ['1', foobarString]);241 const destination = execa('stdin-fail.js');242 const pipePromise = source.pipe(destination);243244 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));245 t.like(await t.throwsAsync(source), {stdout: foobarString, exitCode: 2});246 t.like(await t.throwsAsync(destination), {stdout: foobarString, exitCode: 2});247});248249test('Simultaneous error on source and destination', async t => {250 const source = execa('noop.js', ['']);251 const destination = execa('stdin.js');252 const pipePromise = source.pipe(destination);253254 const sourceError = new Error(foobarString);255 source.emit('error', sourceError);256 const destinationError = new Error('other');257 destination.emit('error', destinationError);258259 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));260 t.like(await t.throwsAsync(source), {originalMessage: sourceError.originalMessage});261 t.like(await t.throwsAsync(destination), {originalMessage: destinationError.originalMessage});262});263264test('Does not need to await individual promises', async t => {265 const source = execa('fail.js');266 const destination = execa('fail.js');267 await t.throwsAsync(source.pipe(destination));268});269270test('Need to await .pipe() return value', async t => {271 const source = execa('fail.js');272 const destination = execa('fail.js');273 const pipePromise = source.pipe(destination);274 await Promise.all([275 once(process, 'unhandledRejection'),276 t.throwsAsync(source),277 t.throwsAsync(destination),278 ]);279 await t.throwsAsync(pipePromise);280});281282if (isLinux) {283 const testYesHead = async (t, useStdoutTransform, useStdinTransform, all) => {284 const source = execa('yes', {stdout: useStdoutTransform ? noopGenerator(false) : 'pipe', all});285 const destination = execa('head', ['-n', '1'], {stdin: useStdinTransform ? noopGenerator(false) : 'pipe'});286 const pipePromise = source.pipe(destination);287 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));288 t.like(await destination, {stdout: 'y'});289 t.like(await t.throwsAsync(source), {exitCode: 1, stderr: 'yes: standard output: Connection reset by peer'});290291 t.false(source.stdout.readableEnded);292 t.is(source.stdout.errored, null);293 t.true(source.stdout.destroyed);294 t.true(source.stderr.readableEnded);295 t.is(source.stderr.errored, null);296 t.true(source.stderr.destroyed);297298 if (all) {299 t.true(source.all.readableEnded);300 t.is(source.all.errored, null);301 t.true(source.all.destroyed);302 }303 };304305 test('Works with yes | head', testYesHead, false, false, false);306 test('Works with yes | head, input transform', testYesHead, false, true, false);307 test('Works with yes | head, output transform', testYesHead, true, false, false);308 test('Works with yes | head, input/output transform', testYesHead, true, true, false);309 test('Works with yes | head, "all" option', testYesHead, false, false, true);310 test('Works with yes | head, "all" option, input transform', testYesHead, false, true, true);311 test('Works with yes | head, "all" option, output transform', testYesHead, true, false, true);312 test('Works with yes | head, "all" option, input/output transform', testYesHead, true, true, true);313}
added:test/pipe/setup.js+23 added
1import test from 'ava';2import {execa} from '../../index.js';3import {setFixtureDir} from '../helpers/fixtures-dir.js';4import {fullStdio} from '../helpers/stdio.js';56setFixtureDir();78const pipeToProcess = async (t, index, from, options) => {9 const {stdout} = await execa('noop-fd.js', [`${index}`, 'test'], options)10 .pipe(execa('stdin.js'), {from});11 t.is(stdout, 'test');12};1314test('pipe(...) can pipe', pipeToProcess, 1, undefined, {});15test('pipe(..., {from: "stdout"}) can pipe', pipeToProcess, 1, 'stdout', {});16test('pipe(..., {from: 1}) can pipe', pipeToProcess, 1, 1, {});17test('pipe(..., {from: "stderr"}) stderr can pipe', pipeToProcess, 2, 'stderr', {});18test('pipe(..., {from: 2}) can pipe', pipeToProcess, 2, 2, {});19test('pipe(..., {from: 3}) can pipe', pipeToProcess, 3, 3, fullStdio);20test('pipe(..., {from: "all"}) can pipe stdout', pipeToProcess, 1, 'all', {all: true});21test('pipe(..., {from: "all"}) can pipe stderr', pipeToProcess, 2, 'all', {all: true});22test('pipe(..., {from: "all"}) can pipe stdout even with "stderr: ignore"', pipeToProcess, 1, 'all', {all: true, stderr: 'ignore'});23test('pipe(..., {from: "all"}) can pipe stderr even with "stdout: ignore"', pipeToProcess, 2, 'all', {all: true, stdout: 'ignore'});
added:test/pipe/streaming.js+428 added
1import {once} from 'node:events';2import {PassThrough} from 'node:stream';3import test from 'ava';4import {execa} from '../../index.js';5import {setFixtureDir} from '../helpers/fixtures-dir.js';6import {foobarString} from '../helpers/input.js';7import {assertMaxListeners} from '../helpers/listeners.js';89setFixtureDir();1011test('Can pipe two sources to same destination', async t => {12 const source = execa('noop.js', [foobarString]);13 const secondSource = execa('noop.js', [foobarString]);14 const destination = execa('stdin.js');15 const pipePromise = source.pipe(destination);16 const secondPipePromise = secondSource.pipe(destination);1718 t.like(await source, {stdout: foobarString});19 t.like(await secondSource, {stdout: foobarString});20 t.like(await destination, {stdout: `${foobarString}\n${foobarString}`});21 t.is(await pipePromise, await destination);22 t.is(await secondPipePromise, await destination);23});2425test('Can pipe three sources to same destination', async t => {26 const source = execa('noop.js', [foobarString]);27 const secondSource = execa('noop.js', [foobarString]);28 const thirdSource = execa('noop.js', [foobarString]);29 const destination = execa('stdin.js');30 const pipePromise = source.pipe(destination);31 const secondPipePromise = secondSource.pipe(destination);32 const thirdPromise = thirdSource.pipe(destination);3334 t.like(await source, {stdout: foobarString});35 t.like(await secondSource, {stdout: foobarString});36 t.like(await thirdSource, {stdout: foobarString});37 t.like(await destination, {stdout: `${foobarString}\n${foobarString}\n${foobarString}`});38 t.is(await pipePromise, await destination);39 t.is(await secondPipePromise, await destination);40 t.is(await thirdPromise, await destination);41});4243const processesCount = 100;4445test.serial('Can pipe many sources to same destination', async t => {46 const checkMaxListeners = assertMaxListeners(t);4748 const expectedResults = Array.from({length: processesCount}, (_, index) => `${index}`).sort();49 const sources = expectedResults.map(expectedResult => execa('noop.js', [expectedResult]));50 const destination = execa('stdin.js');51 const pipePromises = sources.map(source => source.pipe(destination));5253 const results = await Promise.all(sources);54 t.deepEqual(results.map(({stdout}) => stdout), expectedResults);55 const destinationResult = await destination;56 t.deepEqual(destinationResult.stdout.split('\n').sort(), expectedResults);57 t.deepEqual(await Promise.all(pipePromises), sources.map(() => destinationResult));5859 checkMaxListeners();60});6162test.serial('Can pipe same source to many destinations', async t => {63 const checkMaxListeners = assertMaxListeners(t);6465 const source = execa('noop-fd.js', ['1', foobarString]);66 const expectedResults = Array.from({length: processesCount}, (_, index) => `${index}`);67 const destinations = expectedResults.map(expectedResult => execa('noop-stdin-double.js', [expectedResult]));68 const pipePromises = destinations.map(destination => source.pipe(destination));6970 t.like(await source, {stdout: foobarString});71 const results = await Promise.all(destinations);72 t.deepEqual(results.map(({stdout}) => stdout), expectedResults.map(result => `${foobarString} ${result}`));73 t.deepEqual(await Promise.all(pipePromises), results);7475 checkMaxListeners();76});7778test('Can pipe two streams from same process to same destination', async t => {79 const source = execa('noop-both.js', [foobarString]);80 const destination = execa('stdin.js');81 const pipePromise = source.pipe(destination);82 const secondPipePromise = source.pipe(destination, {from: 'stderr'});8384 t.like(await source, {stdout: foobarString, stderr: foobarString});85 t.like(await destination, {stdout: `${foobarString}\n${foobarString}`});86 t.is(await pipePromise, await destination);87 t.is(await secondPipePromise, await destination);88});8990test('Can pipe a new source to same destination after some source has already written', async t => {91 const passThroughStream = new PassThrough();92 const source = execa('stdin.js', {stdin: ['pipe', passThroughStream]});93 const destination = execa('stdin.js');94 const pipePromise = source.pipe(destination);9596 passThroughStream.write('foo');97 const firstWrite = await once(destination.stdout, 'data');98 t.is(firstWrite.toString(), 'foo');99100 const secondSource = execa('noop.js', ['bar']);101 const secondPipePromise = secondSource.pipe(destination);102 passThroughStream.end();103104 t.like(await source, {stdout: 'foo'});105 t.like(await secondSource, {stdout: 'bar'});106 t.like(await destination, {stdout: 'foobar'});107 t.is(await pipePromise, await destination);108 t.is(await secondPipePromise, await destination);109});110111test('Can pipe a second source to same destination after destination has already ended', async t => {112 const source = execa('noop.js', [foobarString]);113 const destination = execa('stdin.js');114 const pipePromise = source.pipe(destination);115116 t.like(await source, {stdout: foobarString});117 t.like(await destination, {stdout: foobarString});118 t.is(await pipePromise, await destination);119120 const secondSource = execa('noop.js', [foobarString]);121 const secondPipePromise = secondSource.pipe(destination);122123 t.like(await secondSource, {stdout: ''});124 t.is(await secondPipePromise, await destination);125});126127test('Can pipe same source to a second destination after source has already ended', async t => {128 const source = execa('noop.js', [foobarString]);129 const destination = execa('stdin.js');130 const pipePromise = source.pipe(destination);131132 t.like(await source, {stdout: foobarString});133 t.like(await destination, {stdout: foobarString});134 t.is(await pipePromise, await destination);135136 const secondDestination = execa('stdin.js');137 const secondPipePromise = source.pipe(secondDestination);138139 t.like(await secondDestination, {stdout: ''});140 t.is(await secondPipePromise, await secondDestination);141});142143test('Can pipe a new source to same destination after some but not all sources have ended', async t => {144 const source = execa('noop.js', [foobarString]);145 const passThroughStream = new PassThrough();146 const secondSource = execa('stdin.js', {stdin: ['pipe', passThroughStream]});147 const destination = execa('stdin.js');148 const pipePromise = source.pipe(destination);149 const secondPipePromise = secondSource.pipe(destination);150151 t.like(await source, {stdout: foobarString});152153 const thirdSource = execa('noop.js', [foobarString]);154 const thirdPipePromise = thirdSource.pipe(destination);155 passThroughStream.end(`${foobarString}\n`);156157 t.like(await secondSource, {stdout: foobarString});158 t.like(await thirdSource, {stdout: foobarString});159 t.like(await destination, {stdout: `${foobarString}\n${foobarString}\n${foobarString}`});160 t.is(await pipePromise, await destination);161 t.is(await secondPipePromise, await destination);162 t.is(await thirdPipePromise, await destination);163});164165test('Can pipe two processes already ended', async t => {166 const source = execa('noop.js', [foobarString]);167 const destination = execa('stdin.js');168 destination.stdin.end('.');169 await Promise.all([source, destination]);170 const pipePromise = source.pipe(destination);171172 t.like(await source, {stdout: foobarString});173 t.like(await destination, {stdout: '.'});174 t.is(await pipePromise, await destination);175});176177test('Can pipe to same destination through multiple paths', async t => {178 const source = execa('noop.js', [foobarString]);179 const destination = execa('stdin.js');180 const secondDestination = execa('stdin.js');181 const pipePromise = source.pipe(destination);182 const secondPipePromise = destination.pipe(secondDestination);183 const thirdPipePromise = source.pipe(secondDestination);184185 t.like(await source, {stdout: foobarString});186 t.like(await destination, {stdout: foobarString});187 t.like(await secondDestination, {stdout: `${foobarString}\n${foobarString}`});188 t.is(await pipePromise, await destination);189 t.is(await secondPipePromise, await secondDestination);190 t.is(await thirdPipePromise, await secondDestination);191});192193test('Can pipe two sources to same destination in objectMode', async t => {194 const stdoutTransform = {195 * transform() {196 yield [foobarString];197 },198 objectMode: true,199 };200 const source = execa('noop.js', [''], {stdout: stdoutTransform});201 const secondSource = execa('noop.js', [''], {stdout: stdoutTransform});202 t.true(source.stdout.readableObjectMode);203 t.true(secondSource.stdout.readableObjectMode);204205 const stdinTransform = {206 * transform([chunk]) {207 yield chunk;208 },209 objectMode: true,210 };211 const destination = execa('stdin.js', {stdin: stdinTransform});212 const pipePromise = source.pipe(destination);213 const secondPipePromise = secondSource.pipe(destination);214215 t.like(await source, {stdout: [[foobarString]]});216 t.like(await secondSource, {stdout: [[foobarString]]});217 t.like(await destination, {stdout: `${foobarString}${foobarString}`});218 t.is(await pipePromise, await destination);219 t.is(await secondPipePromise, await destination);220});221222test('Can pipe one source to two destinations', async t => {223 const source = execa('noop.js', [foobarString]);224 const destination = execa('stdin.js');225 const secondDestination = execa('stdin.js');226 const pipePromise = source.pipe(destination);227 const secondPipePromise = source.pipe(secondDestination);228229 t.like(await source, {stdout: foobarString});230 t.like(await destination, {stdout: foobarString});231 t.like(await secondDestination, {stdout: foobarString});232 t.is(await pipePromise, await destination);233 t.is(await secondPipePromise, await secondDestination);234});235236test('Can pipe one source to three destinations', async t => {237 const source = execa('noop.js', [foobarString]);238 const destination = execa('stdin.js');239 const secondDestination = execa('stdin.js');240 const thirdDestination = execa('stdin.js');241 const pipePromise = source.pipe(destination);242 const secondPipePromise = source.pipe(secondDestination);243 const thirdPipePromise = source.pipe(thirdDestination);244245 t.like(await source, {stdout: foobarString});246 t.like(await destination, {stdout: foobarString});247 t.like(await secondDestination, {stdout: foobarString});248 t.like(await thirdDestination, {stdout: foobarString});249 t.is(await pipePromise, await destination);250 t.is(await secondPipePromise, await secondDestination);251 t.is(await thirdPipePromise, await thirdDestination);252});253254test('Can create a series of pipes', async t => {255 const source = execa('noop.js', [foobarString]);256 const destination = execa('stdin.js');257 const secondDestination = execa('stdin.js');258 const pipePromise = source.pipe(destination);259 const secondPipePromise = destination.pipe(secondDestination);260261 t.like(await source, {stdout: foobarString});262 t.like(await destination, {stdout: foobarString});263 t.like(await secondDestination, {stdout: foobarString});264 t.is(await pipePromise, await destination);265 t.is(await secondPipePromise, await secondDestination);266});267268test('Returns pipedFrom on success', async t => {269 const source = execa('noop.js', [foobarString]);270 const destination = execa('stdin.js');271 const pipePromise = source.pipe(destination);272273 const destinationResult = await destination;274 t.deepEqual(destinationResult.pipedFrom, []);275 const sourceResult = await source;276277 t.like(await pipePromise, {pipedFrom: [sourceResult]});278 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);279 t.deepEqual(sourceResult.pipedFrom, []);280});281282test('Returns pipedFrom on deep success', async t => {283 const source = execa('noop.js', [foobarString]);284 const destination = execa('stdin.js');285 const secondDestination = execa('stdin.js');286 const pipePromise = source.pipe(destination);287 const secondPipePromise = destination.pipe(secondDestination);288289 const destinationResult = await destination;290 t.deepEqual(destinationResult.pipedFrom, []);291 const secondDestinationResult = await secondDestination;292 t.deepEqual(secondDestinationResult.pipedFrom, []);293 const sourceResult = await source;294295 t.like(await secondPipePromise, {pipedFrom: [destinationResult]});296 t.deepEqual(secondDestinationResult.pipedFrom, [destinationResult]);297 t.like(await pipePromise, {pipedFrom: [sourceResult]});298 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);299 t.deepEqual(sourceResult.pipedFrom, []);300});301302test('Returns pipedFrom on source failure', async t => {303 const source = execa('noop-fail.js', ['1', foobarString]);304 const destination = execa('stdin.js');305 const pipePromise = source.pipe(destination);306307 const destinationResult = await destination;308 t.deepEqual(destinationResult.pipedFrom, []);309 const sourceResult = await t.throwsAsync(source);310311 t.like(await t.throwsAsync(pipePromise), {pipedFrom: []});312 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);313 t.deepEqual(sourceResult.pipedFrom, []);314});315316test('Returns pipedFrom on destination failure', async t => {317 const source = execa('noop.js', [foobarString]);318 const destination = execa('stdin-fail.js');319 const pipePromise = source.pipe(destination);320321 const destinationResult = await t.throwsAsync(destination);322 const sourceResult = await source;323324 t.like(await t.throwsAsync(pipePromise), {pipedFrom: [sourceResult]});325 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);326 t.deepEqual(sourceResult.pipedFrom, []);327});328329test('Returns pipedFrom on source + destination failure', async t => {330 const source = execa('noop-fail.js', ['1', foobarString]);331 const destination = execa('stdin-fail.js');332 const pipePromise = source.pipe(destination);333334 const destinationResult = await t.throwsAsync(destination);335 const sourceResult = await t.throwsAsync(source);336337 t.like(await t.throwsAsync(pipePromise), {pipedFrom: [sourceResult]});338 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);339 t.deepEqual(sourceResult.pipedFrom, []);340});341342test('Returns pipedFrom on deep failure', async t => {343 const source = execa('noop-fail.js', ['1', foobarString]);344 const destination = execa('stdin-fail.js');345 const secondDestination = execa('stdin.js');346 const pipePromise = source.pipe(destination);347 const secondPipePromise = destination.pipe(secondDestination);348349 const destinationResult = await t.throwsAsync(destination);350 const secondDestinationResult = await secondDestination;351 t.deepEqual(secondDestinationResult.pipedFrom, []);352 const sourceResult = await t.throwsAsync(source);353354 t.like(await t.throwsAsync(secondPipePromise), {pipedFrom: [sourceResult]});355 t.deepEqual(secondDestinationResult.pipedFrom, [destinationResult]);356 t.like(await t.throwsAsync(pipePromise), {pipedFrom: [sourceResult]});357 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);358 t.deepEqual(sourceResult.pipedFrom, []);359});360361test('Returns pipedFrom from multiple sources', async t => {362 const source = execa('noop.js', [foobarString]);363 const secondSource = execa('noop.js', [foobarString]);364 const destination = execa('stdin.js');365 const pipePromise = source.pipe(destination);366 const secondPipePromise = secondSource.pipe(destination);367368 const destinationResult = await destination;369 t.deepEqual(destinationResult.pipedFrom, []);370 const sourceResult = await source;371 const secondSourceResult = await secondSource;372373 t.like(await pipePromise, {pipedFrom: [sourceResult, secondSourceResult]});374 t.like(await secondPipePromise, {pipedFrom: [sourceResult, secondSourceResult]});375 t.deepEqual(destinationResult.pipedFrom, [sourceResult, secondSourceResult]);376 t.deepEqual(sourceResult.pipedFrom, []);377 t.deepEqual(secondSourceResult.pipedFrom, []);378});379380test('Returns pipedFrom from already ended processes', async t => {381 const source = execa('noop.js', [foobarString]);382 const destination = execa('stdin.js');383 destination.stdin.end('.');384 await Promise.all([source, destination]);385 const pipePromise = source.pipe(destination);386387 const destinationResult = await destination;388 t.deepEqual(destinationResult.pipedFrom, []);389 const sourceResult = await source;390 t.deepEqual(sourceResult.pipedFrom, []);391392 t.like(await pipePromise, {pipedFrom: [sourceResult]});393 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);394 t.deepEqual(sourceResult.pipedFrom, []);395});396397test('Does not return nor set pipedFrom on signal abort', async t => {398 const abortController = new AbortController();399 const source = execa('empty.js');400 const destination = execa('empty.js');401 const pipePromise = source.pipe(destination, {signal: abortController.signal});402403 abortController.abort();404 t.like(await t.throwsAsync(pipePromise), {pipedFrom: []});405 const destinationResult = await destination;406 t.deepEqual(destinationResult.pipedFrom, []);407 const sourceResult = await source;408 t.deepEqual(sourceResult.pipedFrom, []);409});410411test('Can pipe same source to same destination twice', async t => {412 const source = execa('noop.js', [foobarString]);413 const destination = execa('stdin.js');414 const pipePromise = source.pipe(destination);415 const secondPipePromise = source.pipe(destination);416417 const destinationResult = await destination;418 t.like(destinationResult, {pipedFrom: []});419 const sourceResult = await source;420 t.like(sourceResult, {pipedFrom: []});421422 t.like(await source, {stdout: foobarString});423 t.like(await destination, {stdout: foobarString});424 t.is(await pipePromise, destinationResult);425 t.is(await secondPipePromise, destinationResult);426 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);427 t.deepEqual(sourceResult.pipedFrom, []);428});
added:test/pipe/validate.js+165 added
1import {PassThrough} from 'node:stream';2import {spawn} from 'node:child_process';3import process from 'node:process';4import test from 'ava';5import {execa} from '../../index.js';6import {setFixtureDir} from '../helpers/fixtures-dir.js';7import {foobarString} from '../helpers/input.js';89setFixtureDir();1011const assertPipeError = async (t, pipePromise, message) => {12 const error = await t.throwsAsync(pipePromise);1314 t.is(error.command, 'source.pipe(destination)');15 t.is(error.escapedCommand, error.command);1617 t.is(typeof error.cwd, 'string');18 t.true(error.failed);19 t.false(error.timedOut);20 t.false(error.isCanceled);21 t.false(error.isTerminated);22 t.is(error.exitCode, undefined);23 t.is(error.signal, undefined);24 t.is(error.signalDescription, undefined);25 t.is(error.stdout, undefined);26 t.is(error.stderr, undefined);27 t.is(error.all, undefined);28 t.deepEqual(error.stdio, Array.from({length: error.stdio.length}));29 t.deepEqual(error.pipedFrom, []);3031 t.true(error.shortMessage.includes(`Command failed: ${error.command}`));32 t.true(error.shortMessage.includes(error.originalMessage));33 t.true(error.message.includes(error.shortMessage));3435 t.true(error.originalMessage.includes(message));36};3738test('Must set "all" option to "true" to use pipe(..., {from: "all"})', async t => {39 await assertPipeError(40 t,41 execa('empty.js')42 .pipe(execa('empty.js'), {from: 'all'}),43 '"all" option must be true',44 );45});4647const invalidDestination = async (t, getDestination) => {48 await assertPipeError(49 t,50 execa('empty.js')51 .pipe(getDestination()),52 'an Execa child process',53 );54};5556test('pipe() cannot pipe to non-processes', invalidDestination, () => ({stdin: new PassThrough()}));57test('pipe() cannot pipe to non-Execa processes', invalidDestination, () => spawn('node', ['--version']));5859test('pipe() "from" option cannot be "stdin"', async t => {60 await assertPipeError(61 t,62 execa('empty.js')63 .pipe(execa('empty.js'), {from: 'stdin'}),64 'not be "stdin"',65 );66});6768const invalidFromOption = async (t, from) => {69 await assertPipeError(70 t,71 execa('empty.js')72 .pipe(execa('empty.js'), {from}),73 '"from" option must not be',74 );75};7677test('pipe() "from" option cannot be any string', invalidFromOption, 'other');78test('pipe() "from" option cannot be a float', invalidFromOption, 1.5);79test('pipe() "from" option cannot be a negative number', invalidFromOption, -1);8081test('pipe() "from" option cannot be a non-existing file descriptor', async t => {82 await assertPipeError(83 t,84 execa('empty.js')85 .pipe(execa('empty.js'), {from: 3}),86 'file descriptor does not exist',87 );88});8990test('pipe() "from" option cannot be an input file descriptor', async t => {91 await assertPipeError(92 t,93 execa('stdin-fd.js', ['3'], {stdio: ['pipe', 'pipe', 'pipe', new Uint8Array()]})94 .pipe(execa('empty.js'), {from: 3}),95 'must be a readable stream',96 );97});9899test('Must set destination "stdin" option to "pipe" to use pipe()', async t => {100 await assertPipeError(101 t,102 execa('empty.js')103 .pipe(execa('stdin.js', {stdin: 'ignore'})),104 'stdin must be available',105 );106});107108// eslint-disable-next-line max-params109const invalidSource = async (t, optionName, optionValue, from, options) => {110 await assertPipeError(111 t,112 execa('empty.js', options)113 .pipe(execa('empty.js'), {from}),114 `\`${optionName}: ${optionValue}\` option is incompatible`,115 );116};117118test('Cannot set "stdout" option to "ignore" to use pipe(...)', invalidSource, 'stdout', '"ignore"', undefined, {stdout: 'ignore'});119test('Cannot set "stdout" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdout', '"ignore"', 1, {stdout: 'ignore'});120test('Cannot set "stdout" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdout', '"ignore"', 'stdout', {stdout: 'ignore'});121test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(...)', invalidSource, 'stdout', '"ignore"', undefined, {stdout: 'ignore', stderr: 'ignore'});122test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdout', '"ignore"', 1, {stdout: 'ignore', stderr: 'ignore'});123test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdout', '"ignore"', 'stdout', {stdout: 'ignore', stderr: 'ignore'});124test('Cannot set "stdio[1]" option to "ignore" to use pipe(...)', invalidSource, 'stdio[1]', '"ignore"', undefined, {stdio: ['pipe', 'ignore', 'pipe']});125test('Cannot set "stdio[1]" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdio[1]', '"ignore"', 1, {stdio: ['pipe', 'ignore', 'pipe']});126test('Cannot set "stdio[1]" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdio[1]', '"ignore"', 'stdout', {stdio: ['pipe', 'ignore', 'pipe']});127test('Cannot set "stderr" option to "ignore" to use pipe(..., 2)', invalidSource, 'stderr', '"ignore"', 2, {stderr: 'ignore'});128test('Cannot set "stderr" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stderr', '"ignore"', 'stderr', {stderr: 'ignore'});129test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., 2)', invalidSource, 'stderr', '"ignore"', 2, {stdout: 'ignore', stderr: 'ignore'});130test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stderr', '"ignore"', 'stderr', {stdout: 'ignore', stderr: 'ignore'});131test('Cannot set "stdio[2]" option to "ignore" to use pipe(..., 2)', invalidSource, 'stdio[2]', '"ignore"', 2, {stdio: ['pipe', 'pipe', 'ignore']});132test('Cannot set "stdio[2]" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stdio[2]', '"ignore"', 'stderr', {stdio: ['pipe', 'pipe', 'ignore']});133test('Cannot set "stdio[3]" option to "ignore" to use pipe(..., 3)', invalidSource, 'stdio[3]', '"ignore"', 3, {stdio: ['pipe', 'pipe', 'pipe', 'ignore']});134test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "all")', invalidSource, 'stdout', '"ignore"', 'all', {stdout: 'ignore', stderr: 'ignore', all: true});135test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use pipe(..., "all")', invalidSource, 'stdio[1]', '"ignore"', 'all', {stdio: ['pipe', 'ignore', 'ignore'], all: true});136test('Cannot set "stdout" option to "inherit" to use pipe()', invalidSource, 'stdout', '"inherit"', 1, {stdout: 'inherit'});137test('Cannot set "stdout" option to "ipc" to use pipe()', invalidSource, 'stdout', '"ipc"', 1, {stdout: 'ipc'});138test('Cannot set "stdout" option to file descriptors to use pipe()', invalidSource, 'stdout', '1', 1, {stdout: 1});139test('Cannot set "stdout" option to Node.js streams to use pipe()', invalidSource, 'stdout', 'Stream', 1, {stdout: process.stdout});140141test('Destination stream is ended when first argument is invalid', async t => {142 const source = execa('empty.js', {stdout: 'ignore'});143 const destination = execa('stdin.js');144 const pipePromise = source.pipe(destination);145146 await assertPipeError(t, pipePromise, 'option is incompatible');147 await source;148 t.like(await destination, {stdout: ''});149});150151test('Source stream is aborted when second argument is invalid', async t => {152 const source = execa('noop.js', [foobarString]);153 const pipePromise = source.pipe('');154155 await assertPipeError(t, pipePromise, 'an Execa child process');156 t.like(await source, {stdout: ''});157});158159test('Both arguments might be invalid', async t => {160 const source = execa('empty.js', {stdout: 'ignore'});161 const pipePromise = source.pipe('');162163 await assertPipeError(t, pipePromise, 'an Execa child process');164 t.like(await source, {stdout: undefined});165});
modified:test/error.js+2 added
24 unmodified lines
25 'stdout',26 'stderr',27 'all',28 'stdio',29 'pipedFrom',30 ]);31});3233test('Error properties are not missing and are ordered', async t => {
16 unmodified lines
50 'stdout',51 'stderr',52 'all',53 'stdio',54 'pipedFrom',55 ]);56});5758const testEmptyErrorStdio = async (t, execaMethod) => {
274 unmodified lines
deleted:test/pipe.js-110 removed
1import {PassThrough} from 'node:stream';2import {spawn} from 'node:child_process';3import process from 'node:process';4import test from 'ava';5import {execa} from '../index.js';6import {setFixtureDir} from './helpers/fixtures-dir.js';7import {fullStdio} from './helpers/stdio.js';89setFixtureDir();1011const pipeToProcess = async (t, index, streamName) => {12 const {stdout} = await execa('noop-fd.js', [`${index}`, 'test'], {...fullStdio, all: true}).pipe(execa('stdin.js'), streamName);13 t.is(stdout, 'test');14};1516test('pipe() can pipe to Execa child processes', pipeToProcess, 1, undefined);17test('pipe() stdout can pipe to Execa child processes', pipeToProcess, 1, 'stdout');18test('pipe() 1 can pipe to Execa child processes', pipeToProcess, 1, 1);19test('pipe() stderr can pipe to Execa child processes', pipeToProcess, 2, 'stderr');20test('pipe() 2 can pipe to Execa child processes', pipeToProcess, 2, 2);21test('pipe() 3 can pipe to Execa child processes', pipeToProcess, 3, 3);2223const pipeAllToProcess = async (t, index) => {24 const {stdout} = await execa('noop-fd.js', [`${index}`, 'test'], {...fullStdio, all: true}).pipe(execa('stdin.js'), 'all');25 t.is(stdout, 'test');26};2728test('pipe() all can pipe stdout to Execa child processes', pipeAllToProcess, 1, {all: true});29test('pipe() all can pipe stdout to Execa child processes even with "stderr: ignore"', pipeAllToProcess, 1, {all: true, stderr: 'ignore'});30test('pipe() all can pipe stderr to Execa child processes', pipeAllToProcess, 2, {all: true});31test('pipe() all can pipe stderr to Execa child processes even with "stdout: ignore"', pipeAllToProcess, 1, {all: true, stdout: 'ignore'});3233test('Must set "all" option to "true" to use pipe() with "all"', t => {34 t.throws(() => {35 execa('empty.js').pipe(execa('empty.js'), 'all');36 }, {message: /"all" option must be true/});37});3839const invalidTarget = (t, getTarget) => {40 t.throws(() => {41 execa('empty.js').pipe(getTarget());42 }, {message: /an Execa child process/});43};4445test('pipe() cannot pipe to non-processes', invalidTarget, () => ({stdin: new PassThrough()}));46test('pipe() cannot pipe to non-Execa processes', invalidTarget, () => spawn('node', ['--version']));4748test('pipe() second argument cannot be "stdin"', t => {49 t.throws(() => {50 execa('empty.js').pipe(execa('empty.js'), 'stdin');51 }, {message: /not be "stdin"/});52});5354const invalidStreamName = (t, streamName) => {55 t.throws(() => {56 execa('empty.js').pipe(execa('empty.js'), streamName);57 }, {message: /second argument must not be/});58};5960test('pipe() second argument cannot be any string', invalidStreamName, 'other');61test('pipe() second argument cannot be a float', invalidStreamName, 1.5);62test('pipe() second argument cannot be a negative number', invalidStreamName, -1);6364test('pipe() second argument cannot be a non-existing file descriptor', t => {65 t.throws(() => {66 execa('empty.js').pipe(execa('empty.js'), 3);67 }, {message: /file descriptor does not exist/});68});6970test('pipe() second argument cannot be an input file descriptor', t => {71 t.throws(() => {72 execa('stdin-fd.js', ['3'], {stdio: ['pipe', 'pipe', 'pipe', new Uint8Array()]}).pipe(execa('empty.js'), 3);73 }, {message: /must be a readable stream/});74});7576test('Must set target "stdin" option to "pipe" to use pipe()', t => {77 t.throws(() => {78 execa('empty.js').pipe(execa('stdin.js', {stdin: 'ignore'}));79 }, {message: /stdin must be available/});80});8182// eslint-disable-next-line max-params83const invalidSource = (t, optionName, optionValue, streamName, options) => {84 t.throws(() => {85 execa('empty.js', options).pipe(execa('empty.js'), streamName);86 }, {message: new RegExp(`\`${optionName}: ${optionValue}\` option is incompatible`)});87};8889test('Cannot set "stdout" option to "ignore" to use pipe(...)', invalidSource, 'stdout', '"ignore"', undefined, {stdout: 'ignore'});90test('Cannot set "stdout" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdout', '"ignore"', 1, {stdout: 'ignore'});91test('Cannot set "stdout" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdout', '"ignore"', 'stdout', {stdout: 'ignore'});92test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(...)', invalidSource, 'stdout', '"ignore"', undefined, {stdout: 'ignore', stderr: 'ignore'});93test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdout', '"ignore"', 1, {stdout: 'ignore', stderr: 'ignore'});94test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdout', '"ignore"', 'stdout', {stdout: 'ignore', stderr: 'ignore'});95test('Cannot set "stdio[1]" option to "ignore" to use pipe(...)', invalidSource, 'stdio\\[1\\]', '"ignore"', undefined, {stdio: ['pipe', 'ignore', 'pipe']});96test('Cannot set "stdio[1]" option to "ignore" to use pipe(..., 1)', invalidSource, 'stdio\\[1\\]', '"ignore"', 1, {stdio: ['pipe', 'ignore', 'pipe']});97test('Cannot set "stdio[1]" option to "ignore" to use pipe(..., "stdout")', invalidSource, 'stdio\\[1\\]', '"ignore"', 'stdout', {stdio: ['pipe', 'ignore', 'pipe']});98test('Cannot set "stderr" option to "ignore" to use pipe(..., 2)', invalidSource, 'stderr', '"ignore"', 2, {stderr: 'ignore'});99test('Cannot set "stderr" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stderr', '"ignore"', 'stderr', {stderr: 'ignore'});100test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., 2)', invalidSource, 'stderr', '"ignore"', 2, {stdout: 'ignore', stderr: 'ignore'});101test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stderr', '"ignore"', 'stderr', {stdout: 'ignore', stderr: 'ignore'});102test('Cannot set "stdio[2]" option to "ignore" to use pipe(..., 2)', invalidSource, 'stdio\\[2\\]', '"ignore"', 2, {stdio: ['pipe', 'pipe', 'ignore']});103test('Cannot set "stdio[2]" option to "ignore" to use pipe(..., "stderr")', invalidSource, 'stdio\\[2\\]', '"ignore"', 'stderr', {stdio: ['pipe', 'pipe', 'ignore']});104test('Cannot set "stdio[3]" option to "ignore" to use pipe(..., 3)', invalidSource, 'stdio\\[3\\]', '"ignore"', 3, {stdio: ['pipe', 'pipe', 'pipe', 'ignore']});105test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe(..., "all")', invalidSource, 'stdout', '"ignore"', 'all', {stdout: 'ignore', stderr: 'ignore', all: true});106test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use pipe(..., "all")', invalidSource, 'stdio\\[1\\]', '"ignore"', 'all', {stdio: ['pipe', 'ignore', 'ignore'], all: true});107test('Cannot set "stdout" option to "inherit" to use pipe()', invalidSource, 'stdout', '"inherit"', 1, {stdout: 'inherit'});108test('Cannot set "stdout" option to "ipc" to use pipe()', invalidSource, 'stdout', '"ipc"', 1, {stdout: 'ipc'});109test('Cannot set "stdout" option to file descriptors to use pipe()', invalidSource, 'stdout', '1', 1, {stdout: 1});110test('Cannot set "stdout" option to Node.js streams to use pipe()', invalidSource, 'stdout', 'Stream', 1, {stdout: process.stdout});
modified:index.d.ts+39 added-16 removed
1import {type ChildProcess} from 'node:child_process';2import {type Readable, type Writable} from 'node:stream';34type IfAsync<IsSync extends boolean, AsyncValue> = IsSync extends true ? never : AsyncValue;4type IfAsync<IsSync extends boolean, AsyncValue, SyncValue = never> = IsSync extends true ? SyncValue : AsyncValue;56// When the `stdin`/`stdout`/`stderr`/`stdio` option is set to one of those values, no stream is created7type NoStreamStdioOption =8 | 'ignore'
659 unmodified lines
668669 /**670 The output of the process on `stdout`.671672 This is `undefined` if the `stdout` option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `lines` option is `true, or if the `stdout` option is a transform in object mode.672 This is `undefined` if the `stdout` option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `lines` option is `true`, or if the `stdout` option is a transform in object mode.673 */674 stdout: StdioOutput<'1', OptionsType>;675676 /**677 The output of the process on `stderr`.678679 This is `undefined` if the `stderr` option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `lines` option is `true, or if the `stderr` option is a transform in object mode.679 This is `undefined` if the `stderr` option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the `lines` option is `true`, or if the `stderr` option is a transform in object mode.680 */681 stderr: StdioOutput<'2', OptionsType>;682683 /**
52 unmodified lines
736 This is `undefined` if either:737 - the `all` option is `false` (default value)738 - both `stdout` and `stderr` options are set to [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)739740 This is an array if the `lines` option is `true, or if either the `stdout` or `stderr` option is a transform in object mode.740 This is an array if the `lines` option is `true`, or if either the `stdout` or `stderr` option is a transform in object mode.741 */742 all: IfAsync<IsSync, AllOutput<OptionsType>>;743744 /**745 Results of the other processes that were piped into this child process. This is useful to inspect a series of child processes piped with each other.746747 This array is initially empty and is populated each time the `.pipe()` method resolves.748 */749 pipedFrom: IfAsync<IsSync, ExecaReturnValue[], []>;750 // Workaround for a TypeScript bug: https://github.com/microsoft/TypeScript/issues/57062751} & {};752753export type ExecaReturnValue<OptionsType extends Options = Options> = ExecaCommonReturnValue<false, OptionsType> & ErrorUnlessReject<OptionsType['reject']>;
63 unmodified lines
817type AllIfStderr<StderrResultIgnored extends boolean> = StderrResultIgnored extends true818 ? undefined819 : Readable;820821type PipeOptions = {822 /**823 Which stream to pipe. A file descriptor number can also be passed.824825 `"all"` pipes both `stdout` and `stderr`. This requires the `all` option to be `true`.826 */827 readonly from?: 'stdout' | 'stderr' | 'all' | number;828829 /**830 Unpipe the child process when the signal aborts.831832 The `.pipe()` method will be rejected with a cancellation error.833 */834 readonly signal?: AbortSignal;835};836837type PipableProcess = {838 /**839 [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to a second Execa child process' `stdin`. This resolves with that second process' result. If either process is rejected, this is rejected with that process' error instead.840841 This can be called multiple times to chain a series of processes.842843 Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.844 */845 pipe<Destination extends ExecaChildProcess>(destination: Destination, options?: PipeOptions): Promise<Awaited<Destination>> & PipableProcess;846};847848export type ExecaChildPromise<OptionsType extends Options = Options> = {849 stdin: StreamUnlessIgnored<'0', OptionsType>;850851 stdout: StreamUnlessIgnored<'1', OptionsType>;
13 unmodified lines
865 onRejected?: (reason: ExecaError<OptionsType>) => ResultType | PromiseLike<ResultType>866 ): Promise<ExecaReturnValue<OptionsType> | ResultType>;867868 /**835 [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to another Execa child process' `stdin`.836837 A `streamName` can be passed to pipe `"stderr"`, `"all"` (both `stdout` and `stderr`) or any another file descriptor instead of `stdout`.838839 `childProcess.stdout` (and/or `childProcess.stderr` depending on `streamName`) must not be `undefined`. When `streamName` is `"all"`, the `all` option must be set to `true`.840841 Returns `execaChildProcess`, which allows chaining `.pipe()` then `await`ing the final result.842 */843 pipe<Target extends ExecaChildProcess>(target: Target, streamName?: 'stdout' | 'stderr' | 'all' | number): Target;844845 /**869 Sends a [signal](https://nodejs.org/api/os.html#signal-constants) to the child process. The default signal is the `killSignal` option. `killSignal` defaults to `SIGTERM`, which terminates the child process.870871 This returns `false` when the signal could not be sent, for example when the child process has already exited.872
2 unmodified lines
875 [More info.](https://nodejs.org/api/child_process.html#subprocesskillsignal)876 */877 kill(signal: Parameters<ChildProcess['kill']>[0], error?: Error): ReturnType<ChildProcess['kill']>;878 kill(error?: Error): ReturnType<ChildProcess['kill']>;856};879} & PipableProcess;880881export type ExecaChildProcess<OptionsType extends Options = Options> = ChildProcess &882ExecaChildPromise<OptionsType> &883Promise<ExecaReturnValue<OptionsType>>;
463 unmodified lines
modified:index.js+1 added-1 removed
9 unmodified lines
10import {handleNodeOption} from './lib/node.js';11import {handleInputAsync, pipeOutputAsync, cleanupStdioStreams} from './lib/stdio/async.js';12import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';13import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay, cleanupOnExit, isFailedExit} from './lib/kill.js';14import {pipeToProcess} from './lib/pipe.js';14import {pipeToProcess} from './lib/pipe/setup.js';15import {getSpawnedResult, makeAllStream} from './lib/stream.js';16import {mergePromise} from './lib/promise.js';17import {joinCommand} from './lib/escape.js';18import {parseCommand} from './lib/command.js';
300 unmodified lines
modified:index.test-d.ts+23 added-12 removed
2 unmodified lines
3// to get treated as `any` by `@typescript-eslint/no-unsafe-assignment`.4import * as process from 'node:process';5import {Readable, Writable} from 'node:stream';6import {createWriteStream} from 'node:fs';7import {expectType, expectError, expectAssignable, expectNotAssignable} from 'tsd';7import {expectType, expectNotType, expectError, expectAssignable, expectNotAssignable} from 'tsd';8import {9 $,10 execa,11 execaSync,
66 unmodified lines
78};7980try {81 const execaPromise = execa('unicorns', {all: true});82 const unicornsResult = await execaPromise;8384 const execaBufferPromise = execa('unicorns', {encoding: 'buffer', all: true});84 const writeStream = createWriteStream('output.txt');85 const bufferResult = await execaBufferPromise;8686 expectType<typeof execaPromise>(execaBufferPromise.pipe(execaPromise));87 expectError(execaBufferPromise.pipe(writeStream));88 expectError(execaBufferPromise.pipe('output.txt'));89 await execaBufferPromise.pipe(execaPromise, 'stdout');90 await execaBufferPromise.pipe(execaPromise, 'stderr');91 await execaBufferPromise.pipe(execaPromise, 'all');92 await execaBufferPromise.pipe(execaPromise, 3);93 expectError(execaBufferPromise.pipe(execaPromise, 'other'));87 expectType<typeof bufferResult>(await execaPromise.pipe(execaBufferPromise));88 expectNotType<typeof bufferResult>(await execaPromise.pipe(execaPromise));89 expectType<typeof bufferResult>(await execaPromise.pipe(execaPromise).pipe(execaBufferPromise));90 await execaPromise.pipe(execaPromise).pipe(execaBufferPromise, {from: 'stdout'});91 expectError(execaPromise.pipe(execaBufferPromise).stdout);92 expectError(execaPromise.pipe(createWriteStream('output.txt')));93 expectError(execaPromise.pipe('output.txt'));94 await execaPromise.pipe(execaBufferPromise, {});95 expectError(execaPromise.pipe(execaBufferPromise, 'stdout'));96 await execaPromise.pipe(execaBufferPromise, {from: 'stdout'});97 await execaPromise.pipe(execaBufferPromise, {from: 'stderr'});98 await execaPromise.pipe(execaBufferPromise, {from: 'all'});99 await execaPromise.pipe(execaBufferPromise, {from: 3});100 expectError(execaPromise.pipe(execaBufferPromise, {from: 'other'}));101 await execaPromise.pipe(execaBufferPromise, {signal: new AbortController().signal});102 expectError(await execaPromise.pipe(execaBufferPromise, {signal: true}));103104 expectType<Readable>(execaPromise.all);105 const noAllPromise = execa('unicorns');106 expectType<undefined>(noAllPromise.all);107 const noAllResult = await noAllPromise;108 expectType<undefined>(noAllResult.all);109101 const unicornsResult = await execaPromise;110 expectType<string>(unicornsResult.command);111 expectType<string>(unicornsResult.escapedCommand);112 expectType<number | undefined>(unicornsResult.exitCode);113 expectType<boolean>(unicornsResult.failed);
2 unmodified lines
116 expectType<boolean>(unicornsResult.isTerminated);117 expectType<string | undefined>(unicornsResult.signal);118 expectType<string | undefined>(unicornsResult.signalDescription);119 expectType<string>(unicornsResult.cwd);120 expectType<ExecaReturnValue[]>(unicornsResult.pipedFrom);121122 expectType<undefined>(unicornsResult.stdio[0]);123 expectType<string>(unicornsResult.stdout);124 expectType<string>(unicornsResult.stdio[1]);
5 unmodified lines
130 expectType<Writable>(execaBufferPromise.stdin);131 expectType<Readable>(execaBufferPromise.stdout);132 expectType<Readable>(execaBufferPromise.stderr);133 expectType<Readable>(execaBufferPromise.all);125 const bufferResult = await execaBufferPromise;134 expectType<Uint8Array>(bufferResult.stdout);135 expectType<Uint8Array>(bufferResult.stdio[1]);136 expectType<Uint8Array>(bufferResult.stderr);137 expectType<Uint8Array>(bufferResult.stdio[2]);
292 unmodified lines
430 expectType<string | undefined>(execaError.signalDescription);431 expectType<string>(execaError.cwd);432 expectType<string>(execaError.shortMessage);433 expectType<string | undefined>(execaError.originalMessage);434 expectType<ExecaReturnValue[]>(execaError.pipedFrom);435436 expectType<undefined>(execaError.stdio[0]);437438 const noAllError = error as ExecaError<{}>;
137 unmodified lines
576 expectType<boolean>(unicornsResult.isTerminated);577 expectType<string | undefined>(unicornsResult.signal);578 expectType<string | undefined>(unicornsResult.signalDescription);579 expectType<string>(unicornsResult.cwd);580 expectType<[]>(unicornsResult.pipedFrom);581582 expectType<undefined>(unicornsResult.stdio[0]);583 expectType<string>(unicornsResult.stdout);584 expectType<string>(unicornsResult.stdio[1]);
63 unmodified lines
648 expectType<string | undefined>(execaError.signalDescription);649 expectType<string>(execaError.cwd);650 expectType<string>(execaError.shortMessage);651 expectType<string | undefined>(execaError.originalMessage);652 expectType<[]>(execaError.pipedFrom);653654 expectType<undefined>(execaError.stdio[0]);655656 const execaStringError = error as ExecaSyncError<{}>;
769 unmodified lines
modified:package.json+1 added-1 removed
43 unmodified lines
44 "local",45 "zx"46 ],47 "dependencies": {48 "@sindresorhus/merge-streams": "^2.0.1",48 "@sindresorhus/merge-streams": "^3.0.0",49 "cross-spawn": "^7.0.3",50 "get-stream": "^8.0.1",51 "human-signals": "^6.0.0",52 "is-stream": "^4.0.1",
40 unmodified lines
modified:readme.md+48 added-17 removed
180 unmodified lines
181182```js183import {execa} from 'execa';184185// Similar to `echo unicorns | cat` in Bash186const {stdout} = await execa('echo', ['unicorns']).pipe(execa('cat'));187console.log(stdout);188//=> 'unicorns'185// Similar to `npm run build | sort | head -n2` in Bash186const {stdout, pipedFrom} = await execa('npm', ['run', 'build'])187 .pipe(execa('sort'))188 .pipe(execa('head', ['-n2']));189console.log(stdout); // Result of `head -n2`190console.log(pipedFrom[0]); // Result of `sort`191console.log(pipedFrom[0].pipedFrom[0]); // Result of `npm run build`192```193194### Handling Errors195
79 unmodified lines
275Same as [`execa()`](#execacommandcommand-options) but synchronous.276277Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`ipc`](#ipc), [`serialization`](#serialization), [`signal`](#signal) and [`lines`](#lines). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be an array, an iterable or a web stream. Node.js streams [must have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr) unless the `input` option is used.278276Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipeexecachildprocess-streamname) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.279Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipesecondchildprocess-pipeoptions) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.280281#### $.sync\`command\`282#### $.s\`command\`283284Same as [$\`command\`](#command) but synchronous.285286Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`ipc`](#ipc), [`serialization`](#serialization), [`signal`](#signal) and [`lines`](#lines). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be an array, an iterable or a web stream. Node.js streams [must have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr) unless the `input` option is used.287285Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipeexecachildprocess-streamname) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.288Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipesecondchildprocess-pipeoptions) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.289290#### execaCommandSync(command, options?)291292Same as [`execaCommand()`](#execacommand-command-options) but synchronous.293294Cannot use the following options: [`all`](#all-2), [`cleanup`](#cleanup), [`buffer`](#buffer), [`detached`](#detached), [`ipc`](#ipc), [`serialization`](#serialization), [`signal`](#signal) and [`lines`](#lines). Also, the [`stdin`](#stdin), [`stdout`](#stdout-1), [`stderr`](#stderr-1), [`stdio`](#stdio-1) and [`input`](#input) options cannot be an array, an iterable or a web stream. Node.js streams [must have a file descriptor](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr) unless the `input` option is used.295293Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipeexecachildprocess-streamname) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.296Returns or throws a [`childProcessResult`](#childProcessResult). The [`childProcess`](#childprocess) is not returned: its methods and properties are not available. This includes [`.kill()`](https://nodejs.org/api/child_process.html#subprocesskillsignal), [`.pid`](https://nodejs.org/api/child_process.html#subprocesspid), [`.pipe()`](#pipesecondchildprocess-pipeoptions) and the [`.stdin`/`.stdout`/`.stderr`](https://nodejs.org/api/child_process.html#subprocessstdout) streams.297298### Shell syntax299300For all the [methods above](#methods), no shell interpreter (Bash, cmd.exe, etc.) is used unless the [`shell` option](#shell) is set. This means shell-specific characters and expressions (`$variable`, `&&`, `||`, `;`, `|`, etc.) have no special meaning and do not need to be escaped.
13 unmodified lines
314This is `undefined` if either:315- the [`all` option](#all-2) is `false` (the default value)316- both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)317315#### pipe(execaChildProcess, streamName?)318#### pipe(secondChildProcess, pipeOptions?)319317`execaChildProcess`: [`execa()` return value](#pipe-multiple-processes)\318`streamName`: `"stdout"` (default), `"stderr"`, `"all"` or file descriptor index320`secondChildProcess`: [`execa()` return value](#pipe-multiple-processes)\321`pipeOptions`: [`PipeOptions`](#pipeoptions)\322_Returns_: [`Promise<ChildProcessResult>`](#childprocessresult)323320[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to another Execa child process' `stdin`.324[Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to a second Execa child process' `stdin`. This resolves with that second process' [result](#childprocessresult). If either process is rejected, this is rejected with that process' [error](#childprocessresult) instead.325322A `streamName` can be passed to pipe `"stderr"`, `"all"` (both `stdout` and `stderr`) or any another file descriptor instead of `stdout`.326This can be called multiple times to chain a series of processes.327324[`childProcess.stdout`](#stdout) (and/or [`childProcess.stderr`](#stderr) depending on `streamName`) must not be `undefined`. When `streamName` is `"all"`, the [`all` option](#all-2) must be set to `true`.328Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.329326Returns `execaChildProcess`, which allows chaining `.pipe()` then `await`ing the [final result](#childprocessresult).330##### pipeOptions331332Type: `object`333334##### pipeOptions.from335336Type: `"stdout" | "stderr" | "all" | number`\337Default: `"stdout"`338339Which stream to pipe. A file descriptor number can also be passed.340341`"all"` pipes both `stdout` and `stderr`. This requires the [`all` option](#all-2) to be `true`.342343##### pipeOptions.signal344345Type: [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal)346347Unpipe the child process when the signal aborts.348349The [`.pipe()`](#pipesecondchildprocess-pipeoptions) method will be rejected with a cancellation error.350351#### kill(signal, error?)352#### kill(error?)353354`signal`: `string | number`\
49 unmodified lines
404Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`405406The output of the process on `stdout`.407385This is `undefined` if the [`stdout`](#stdout-1) option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the [`lines` option](#lines) is `true, or if the `stdout` option is a [transform in object mode](docs/transform.md#object-mode).408This is `undefined` if the [`stdout`](#stdout-1) option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the [`lines` option](#lines) is `true`, or if the `stdout` option is a [transform in object mode](docs/transform.md#object-mode).409410#### stderr411412Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`413414The output of the process on `stderr`.415393This is `undefined` if the [`stderr`](#stderr-1) option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the [`lines` option](#lines) is `true, or if the `stderr` option is a [transform in object mode](docs/transform.md#object-mode).416This is `undefined` if the [`stderr`](#stderr-1) option is set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio). This is an array if the [`lines` option](#lines) is `true`, or if the `stderr` option is a [transform in object mode](docs/transform.md#object-mode).417418#### all419420Type: `string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined`
3 unmodified lines
424This is `undefined` if either:425- the [`all` option](#all-2) is `false` (the default value)426- both [`stdout`](#stdout-1) and [`stderr`](#stderr-1) options are set to only [`'inherit'`, `'ignore'`, `Stream` or `integer`](https://nodejs.org/api/child_process.html#child_process_options_stdio)427405This is an array if the [`lines` option](#lines) is `true, or if either the `stdout` or `stderr` option is a [transform in object mode](docs/transform.md#object-mode).428This is an array if the [`lines` option](#lines) is `true`, or if either the `stdout` or `stderr` option is a [transform in object mode](docs/transform.md#object-mode).429430#### stdio431432Type: `Array<string | Uint8Array | string[] | Uint8Array[] | unknown[] | undefined>`
75 unmodified lines
508A human-friendly description of the signal that was used to terminate the process. For example, `Floating point arithmetic error`.509510If a signal terminated the process, this property is defined and included in the error message. Otherwise it is `undefined`. It is also `undefined` when the signal is very uncommon which should seldomly happen.511512#### pipedFrom513514Type: [`ChildProcessResult[]`](#childprocessresult)515516Results of the other processes that were [piped](#pipe-multiple-processes) into this child process. This is useful to inspect a series of child processes piped with each other.517518This array is initially empty and is populated each time the [`.pipe()`](#pipesecondchildprocess-pipeoptions) method resolves.519520### options521522Type: `object`523
467 unmodified lines