Improve process piping API (#757)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 192d818 · Browse files · 7 files·+167 added−109 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+167 added−109 removed
- tests:+75 added−28 removed
- other:+92 added−81 removed
Provenance
- Commit
9554a78- Tree
d54ecb0- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
192d818
7 files changed+167 added−109 removed
modified:docs/scripts.md+3 added-3 removed
4 unmodified lines5 ```js6 import {$} from 'execa';7 8 const {stdout: name} = await $`cat package.json`9- .pipeStdout($({stdin: 'pipe'})`grep name`);9+ .pipe($({stdin: 'pipe'})`grep name`);10 console.log(name);11 12 const branch = await $`git branch --show-current`;13 await $`dep deploy --branch=${branch}`;583 unmodified lines597 ```598 599 ```js600 // Execa601-await $`echo example`.pipeStdout($({stdin: 'pipe'})`cat`);601+await $`echo example`.pipe($({stdin: 'pipe'})`cat`);602 ```603 604 ### Piping stdout and stderr to another command605 12 unmodified lines618 ```619 620 ```js621 // Execa622-await $({all: true})`echo example`.pipeAll($({stdin: 'pipe'})`cat`);622+await $({all: true})`echo example`.pipe($({stdin: 'pipe'})`cat`, 'all');623 ```624 625 ### Piping stdout to a file626 50 unmodified linesmodified:lib/pipe.js+62 added-14 removed
12344567891011121367814151617181119202122231516242526272829303132333435363738394041424344454647484950515253192021545556575859602425616263642829656667686970717273747576777879import {ChildProcess} from 'node:child_process';import {isWritableStream} from 'is-stream';
const isExecaChildProcess = target => target instanceof ChildProcess && typeof target.then === 'function';export const pipeToProcess = ({spawned, stdioStreamsGroups, options}, targetProcess, streamName = 'stdout') => { validateTargetProcess(targetProcess);
const inputStream = getInputStream(spawned, streamName, stdioStreamsGroups); validateStdioOption(inputStream, spawned, streamName, options);
inputStream.pipe(targetProcess.stdin); return targetProcess;};
const pipeToTarget = (spawned, streamName, target) => { if (!isExecaChildProcess(target)) { throw new TypeError('The second argument must be an Execa child process.');const validateTargetProcess = targetProcess => { if (!isExecaChildProcess(targetProcess)) { throw new TypeError('The first argument must be an Execa child process.'); }
if (!isWritableStream(target.stdin)) { if (!isWritableStream(targetProcess.stdin)) { throw new TypeError('The target child process\'s stdin must be available.'); }};
spawned[streamName].pipe(target.stdin); return target;const isExecaChildProcess = target => target instanceof ChildProcess && typeof target.then === 'function';
const getInputStream = (spawned, streamName, stdioStreamsGroups) => { if (VALID_STREAM_NAMES.has(streamName)) { return spawned[streamName]; }
if (streamName === 'stdin') { throw new TypeError('The second argument must not be "stdin".'); }
if (!Number.isInteger(streamName) || streamName < 0) { throw new TypeError(`The second argument must not be "${streamName}".It must be "stdout", "stderr", "all" or a file descriptor integer.It is optional and defaults to "stdout".`); }
const stdioStreams = stdioStreamsGroups[streamName]; if (stdioStreams === undefined) { throw new TypeError(`The second argument must not be ${streamName}: that file descriptor does not exist.Please set the "stdio" option to ensure that file descriptor exists.`); }
if (stdioStreams[0].direction === 'input') { throw new TypeError(`The second argument must not be ${streamName}: it must be a readable stream, not writable.`); }
return spawned.stdio[streamName];};
export const addPipeMethods = spawned => { if (spawned.stdout !== null) { spawned.pipeStdout = pipeToTarget.bind(undefined, spawned, 'stdout');const VALID_STREAM_NAMES = new Set(['stdout', 'stderr', 'all']);
const validateStdioOption = (inputStream, spawned, streamName, options) => { if (inputStream !== null && inputStream !== undefined) { return; }
if (spawned.stderr !== null) { spawned.pipeStderr = pipeToTarget.bind(undefined, spawned, 'stderr'); if (streamName === 'all' && !options.all) { throw new TypeError('The "all" option must be true to use `childProcess.pipe(targetProcess, "all")`.'); }
if (spawned.all !== undefined) { spawned.pipeAll = pipeToTarget.bind(undefined, spawned, 'all'); throw new TypeError(`The "${getInvalidStdioOption(inputStream, spawned, options)}" option's value is incompatible with using \`childProcess.pipe(targetProcess)\`.Please set this option with "pipe" instead.`);};
const getInvalidStdioOption = (inputStream, spawned, options) => { if (inputStream === spawned.stdout && options.stdout !== undefined) { return 'stdout'; }
if (inputStream === spawned.stderr && options.stderr !== undefined) { return 'stderr'; }
return 'stdio';};modified:test/pipe.js+75 added-28 removed
12345678910910111213141514151617161718192021221920212223242526272526272829302829303132323333343536373839404142434436373845464740414243484950515253545556575859464748606162636465666768697071727374757677787980818283848586878889909192939495import {PassThrough} from 'node:stream';import {spawn} from 'node:child_process';import process from 'node:process';import test from 'ava';import {execa} from '../index.js';import {setFixtureDir} from './helpers/fixtures-dir.js';import {fullStdio} from './helpers/stdio.js';
setFixtureDir();
const pipeToProcess = async (t, index, funcName) => { const {stdout} = await execa('noop-fd.js', [`${index}`, 'test'], {all: true})[funcName](execa('stdin.js'));const pipeToProcess = async (t, index, streamName) => { const {stdout} = await execa('noop-fd.js', [`${index}`, 'test'], {...fullStdio, all: true}).pipe(execa('stdin.js'), streamName); t.is(stdout, 'test');};
test('pipeStdout() can pipe to Execa child processes', pipeToProcess, 1, 'pipeStdout');test('pipeStderr() can pipe to Execa child processes', pipeToProcess, 2, 'pipeStderr');test('pipeAll() can pipe stdout to Execa child processes', pipeToProcess, 1, 'pipeAll');test('pipeAll() can pipe stderr to Execa child processes', pipeToProcess, 2, 'pipeAll');test('pipe() can pipe to Execa child processes', pipeToProcess, 1, undefined);test('pipe() stdout can pipe to Execa child processes', pipeToProcess, 1, 'stdout');test('pipe() 1 can pipe to Execa child processes', pipeToProcess, 1, 1);test('pipe() stderr can pipe to Execa child processes', pipeToProcess, 2, 'stderr');test('pipe() 2 can pipe to Execa child processes', pipeToProcess, 2, 2);test('pipe() 3 can pipe to Execa child processes', pipeToProcess, 3, 3);
const invalidTarget = (t, funcName, getTarget) => { t.throws(() => execa('empty.js', {all: true})[funcName](getTarget()), { message: /an Execa child process/, });const pipeAllToProcess = async (t, index) => { const {stdout} = await execa('noop-fd.js', [`${index}`, 'test'], {...fullStdio, all: true}).pipe(execa('stdin.js'), 'all'); t.is(stdout, 'test');};
test('pipeStdout() cannot pipe to non-processes', invalidTarget, 'pipeStdout', () => ({stdin: new PassThrough()}));test('pipeStderr() cannot pipe to non-processes', invalidTarget, 'pipeStderr', () => ({stdin: new PassThrough()}));test('pipeAll() cannot pipe to non-processes', invalidTarget, 'pipeStderr', () => ({stdin: new PassThrough()}));test('pipeStdout() cannot pipe to non-Execa processes', invalidTarget, 'pipeStdout', () => spawn('node', ['--version']));test('pipeStderr() cannot pipe to non-Execa processes', invalidTarget, 'pipeStderr', () => spawn('node', ['--version']));test('pipeAll() cannot pipe to non-Execa processes', invalidTarget, 'pipeStderr', () => spawn('node', ['--version']));test('pipe() all can pipe stdout to Execa child processes', pipeAllToProcess, 1, {all: true});test('pipe() all can pipe stdout to Execa child processes even with "stderr: ignore"', pipeAllToProcess, 1, {all: true, stderr: 'ignore'});test('pipe() all can pipe stderr to Execa child processes', pipeAllToProcess, 2, {all: true});test('pipe() all can pipe stderr to Execa child processes even with "stdout: ignore"', pipeAllToProcess, 1, {all: true, stdout: 'ignore'});
const invalidSource = (t, funcName) => { t.false(funcName in execa('noop.js', {stdout: 'ignore', stderr: 'ignore'}));test('Must set "all" option to "true" to use pipe() with "all"', t => { t.throws(() => { execa('empty.js').pipe(execa('empty.js'), 'all'); }, {message: /"all" option must be true/});});
const invalidTarget = (t, getTarget) => { t.throws(() => { execa('empty.js').pipe(getTarget()); }, {message: /an Execa child process/});};
test('Must set "stdout" option to "pipe" to use pipeStdout()', invalidSource, 'pipeStdout');test('Must set "stderr" option to "pipe" to use pipeStderr()', invalidSource, 'pipeStderr');test('Must set "stdout" or "stderr" option to "pipe" to use pipeAll()', invalidSource, 'pipeAll');test('pipe() cannot pipe to non-processes', invalidTarget, () => ({stdin: new PassThrough()}));test('pipe() cannot pipe to non-Execa processes', invalidTarget, () => spawn('node', ['--version']));
const invalidPipeToProcess = async (t, index, funcName) => { t.throws(() => execa('noop-fd.js', [`${index}`, 'test'], {all: true})[funcName](execa('stdin.js', {stdin: 'ignore'})), { message: /stdin must be available/, });test('pipe() second argument cannot be "stdin"', t => { t.throws(() => { execa('empty.js').pipe(execa('empty.js'), 'stdin'); }, {message: /not be "stdin"/});});
const invalidStreamName = (t, streamName) => { t.throws(() => { execa('empty.js').pipe(execa('empty.js'), streamName); }, {message: /second argument must not be/});};
test('Must set target "stdin" option to "pipe" to use pipeStdout()', invalidPipeToProcess, 1, 'pipeStdout');test('Must set target "stdin" option to "pipe" to use pipeStderr()', invalidPipeToProcess, 2, 'pipeStderr');test('Must set target "stdin" option to "pipe" to use pipeAll()', invalidPipeToProcess, 1, 'pipeAll');test('pipe() second argument cannot be any string', invalidStreamName, 'other');test('pipe() second argument cannot be a float', invalidStreamName, 1.5);test('pipe() second argument cannot be a negative number', invalidStreamName, -1);
test('pipe() second argument cannot be a non-existing file descriptor', t => { t.throws(() => { execa('empty.js').pipe(execa('empty.js'), 3); }, {message: /file descriptor does not exist/});});
test('pipe() second argument cannot be an input file descriptor', t => { t.throws(() => { execa('stdin-fd.js', ['3'], {stdio: ['pipe', 'pipe', 'pipe', new Uint8Array()]}).pipe(execa('empty.js'), 3); }, {message: /must be a readable stream/});});
test('Must set target "stdin" option to "pipe" to use pipe()', t => { t.throws(() => { execa('empty.js').pipe(execa('stdin.js', {stdin: 'ignore'})); }, {message: /stdin must be available/});});
const invalidSource = (t, optionName, streamName, options) => { t.throws(() => { execa('empty.js', options).pipe(execa('empty.js'), streamName); }, {message: new RegExp(`"${optionName}" option's value is incompatible`)});};
test('Cannot set "stdout" option to "ignore" to use pipe()', invalidSource, 'stdout', 1, {stdout: 'ignore'});test('Cannot set "stderr" option to "ignore" to use pipe()', invalidSource, 'stderr', 2, {stderr: 'ignore'});test('Cannot set "stdio[*]" option to "ignore" to use pipe()', invalidSource, 'stdio', 3, {stdio: ['pipe', 'pipe', 'pipe', 'ignore']});test('Cannot set "stdout" + "stderr" option to "ignore" to use pipe() with "all"', invalidSource, 'stdout', 1, {stdout: 'ignore', stderr: 'ignore', all: true});test('Cannot set "stdout" option to "inherit" to use pipe()', invalidSource, 'stdout', 1, {stdout: 'inherit'});test('Cannot set "stdout" option to "ipc" to use pipe()', invalidSource, 'stdout', 1, {stdout: 'ipc'});test('Cannot set "stdout" option to file descriptors to use pipe()', invalidSource, 'stdout', 1, {stdout: 1});test('Cannot set "stdout" option to Node.js streams to use pipe()', invalidSource, 'stdout', 1, {stdout: process.stdout});modified:index.d.ts+9 added-21 removed
810 unmodified lines811 812 /**813 [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to another Execa child process' `stdin`.814 815- Returns `execaChildProcess`, which allows chaining `pipeStdout()` then `await`ing the final result.815+ A `streamName` can be passed to pipe `"stderr"`, `"all"` (both `stdout` and `stderr`) or any another file descriptor instead of `stdout`.816 817- `childProcess.stdout` must not be `undefined`.818- */819- pipeStdout?<Target extends ExecaChildProcess>(target: Target): Target;817+ `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`.818 821- /**822- Like `pipeStdout()` but piping the child process's `stderr` instead.823-824- `childProcess.stderr` must not be `undefined`.819+ Returns `execaChildProcess`, which allows chaining `.pipe()` then `await`ing the final result.820 */826- pipeStderr?<Target extends ExecaChildProcess>(target: Target): Target;827-828- /**829- Combines both `pipeStdout()` and `pipeStderr()`.830-831- The `all` option must be set to `true`.832- */833- pipeAll?<Target extends ExecaChildProcess>(target: Target): Target;821+ pipe<Target extends ExecaChildProcess>(target: Target, streamName?: 'stdout' | 'stderr' | 'all' | number): Target;822 };823 824 export type ExecaChildProcess<OptionsType extends Options = Options> = ChildProcess &825 ExecaChildPromise<OptionsType> &26 unmodified lines852 ```853 import {execa} from 'execa';854 855 // Similar to `echo unicorns > stdout.txt` in Bash868-await execa('echo', ['unicorns']).pipeStdout('stdout.txt');856+await execa('echo', ['unicorns'], {stdout: {file: 'stdout.txt'}});857 858 // Similar to `echo unicorns 2> stdout.txt` in Bash871-await execa('echo', ['unicorns']).pipeStderr('stderr.txt');859+await execa('echo', ['unicorns'], {stderr: {file: 'stderr.txt'}});860 861 // Similar to `echo unicorns &> stdout.txt` in Bash874-await execa('echo', ['unicorns'], {all: true}).pipeAll('all.txt');862+await execa('echo', ['unicorns'], {stdout: {file: 'all.txt'}, stderr: {file: 'all.txt'}});863 ```864 865 @example <caption>Redirect input from a file</caption>866 ```8 unmodified lines875 @example <caption>Save and pipe output from a child process</caption>876 ```877 import {execa} from 'execa';878 891-const {stdout} = await execa('echo', ['unicorns']).pipeStdout(process.stdout);879+const {stdout} = await execa('echo', ['unicorns'], {stdout: ['pipe', 'inherit']});880 // Prints `unicorns`881 console.log(stdout);882 // Also returns 'unicorns'883 ```2 unmodified lines886 ```887 import {execa} from 'execa';888 889 // Similar to `echo unicorns | cat` in Bash902-const {stdout} = await execa('echo', ['unicorns']).pipeStdout(execa('cat'));890+const {stdout} = await execa('echo', ['unicorns']).pipe(execa('cat'));891 console.log(stdout);892 //=> 'unicorns'893 ```894 402 unmodified linesmodified:index.js+3 added-4 removed
9 unmodified lines10 import {handleInputAsync, pipeOutputAsync} from './lib/stdio/async.js';11 import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';12 import {normalizeStdioNode} from './lib/stdio/normalize.js';13 import {spawnedKill, validateTimeout, normalizeForceKillAfterDelay} from './lib/kill.js';14-import {addPipeMethods} from './lib/pipe.js';14+import {pipeToProcess} from './lib/pipe.js';15 import {getSpawnedResult, makeAllStream} from './lib/stream.js';16 import {mergePromise} from './lib/promise.js';17 import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';18 import {logCommand, verboseDefault} from './lib/verbose.js';134 unmodified lines153 const controller = new AbortController();154 155 pipeOutputAsync(spawned, stdioStreamsGroups);156 157- spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned), options, controller);157+ spawned.kill = spawnedKill.bind(undefined, spawned.kill.bind(spawned), options, controller);158 spawned.all = makeAllStream(spawned, options);159+ spawned.pipe = pipeToProcess.bind(undefined, {spawned, stdioStreamsGroups, options});160 160- addPipeMethods(spawned);161-161 const promise = handlePromise({spawned, options, stdioStreamsGroups, command, escapedCommand, controller});162 mergePromise(spawned, promise);163 return spawned;164 }192 unmodified linesmodified:index.test-d.ts+9 added-20 removed
80 unmodified lines81 82 const execaBufferPromise = execa('unicorns', {encoding: 'buffer', all: true});83 const writeStream = createWriteStream('output.txt');84 85- expectAssignable<Function | undefined>(execaPromise.pipeStdout);86- expectAssignable<ExecaChildProcess>(execaPromise.pipeStdout!(execaPromise));87- expectAssignable<ExecaChildProcess>(execaPromise.pipeStdout!(execaBufferPromise));88- expectAssignable<ExecaChildProcess>(execaBufferPromise.pipeStdout!(execaPromise));89- expectAssignable<ExecaChildProcess>(execaBufferPromise.pipeStdout!(execaBufferPromise));85+ expectType<typeof execaPromise>(execaBufferPromise.pipe(execaPromise));86+ expectError(execaBufferPromise.pipe(writeStream));87+ expectError(execaBufferPromise.pipe('output.txt'));88+ await execaBufferPromise.pipe(execaPromise, 'stdout');89+ await execaBufferPromise.pipe(execaPromise, 'stderr');90+ await execaBufferPromise.pipe(execaPromise, 'all');91+ await execaBufferPromise.pipe(execaPromise, 3);92+ expectError(execaBufferPromise.pipe(execaPromise, 'other'));93 91- expectAssignable<Function | undefined>(execaPromise.pipeStderr);92- expectAssignable<ExecaChildProcess>(execaPromise.pipeStderr!(execaPromise));93- expectAssignable<ExecaChildProcess>(execaPromise.pipeStderr!(execaBufferPromise));94- expectAssignable<ExecaChildProcess>(execaBufferPromise.pipeStderr!(execaPromise));95- expectAssignable<ExecaChildProcess>(execaBufferPromise.pipeStderr!(execaBufferPromise));96-97- expectAssignable<Function | undefined>(execaPromise.pipeAll);98- expectAssignable<ExecaChildProcess>(execaPromise.pipeAll!(execaPromise));99- expectAssignable<ExecaChildProcess>(execaPromise.pipeAll!(execaBufferPromise));100- expectAssignable<ExecaChildProcess>(execaBufferPromise.pipeAll!(execaPromise));101- expectAssignable<ExecaChildProcess>(execaBufferPromise.pipeAll!(execaBufferPromise));102-94 expectType<Readable>(execaPromise.all);95 const noAllPromise = execa('unicorns');96 expectType<undefined>(noAllPromise.all);97 const noAllResult = await noAllPromise;443 unmodified lines541 expectAssignable<ExecaSyncReturnValue>(unicornsResult);542 expectType<string>(unicornsResult.command);543 expectType<string>(unicornsResult.escapedCommand);544 expectType<number | undefined>(unicornsResult.exitCode);554- expectError(unicornsResult.pipeStdout);555- expectError(unicornsResult.pipeStderr);556- expectError(unicornsResult.pipeAll);545+ expectError(unicornsResult.pipe);546 expectType<boolean>(unicornsResult.failed);547 expectType<boolean>(unicornsResult.timedOut);548 expectType<boolean>(unicornsResult.isCanceled);549 expectType<boolean>(unicornsResult.isTerminated);832 unmodified linesmodified:readme.md+6 added-19 removed
181 unmodified lines182 ```js183 import {execa} from 'execa';184 185 // Similar to `echo unicorns | cat` in Bash186-const {stdout} = await execa('echo', ['unicorns']).pipeStdout(execa('cat'));186+const {stdout} = await execa('echo', ['unicorns']).pipe(execa('cat'));187 console.log(stdout);188 //=> 'unicorns'189 ```190 127 unmodified lines318 This is `undefined` if either:319 - the [`all` option](#all-2) is `false` (the default value)320 - 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)321 322-#### pipeStdout(execaChildProcess)322+#### pipe(execaChildProcess, streamName?)323 324 `execaChildProcess`: [`execa()` return value](#pipe-multiple-processes)325+`streamName`: `"stdout"` (default), `"stderr"`, `"all"` or file descriptor index326 327 [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to another Execa child process' `stdin`.328 328-Returns `execaChildProcess`, which allows chaining `pipeStdout()` then `await`ing the [final result](#childprocessresult).329+A `streamName` can be passed to pipe `"stderr"`, `"all"` (both `stdout` and `stderr`) or any another file descriptor instead of `stdout`.330 330-[`childProcess.stdout`](#stdout) must not be `undefined`.331+[`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`.332 332-#### pipeStderr(execaChildProcess)333+Returns `execaChildProcess`, which allows chaining `.pipe()` then `await`ing the [final result](#childprocessresult).334 334-`execaChildProcess`: [`execa()` return value](#pipe-multiple-processes)335-336-Like [`pipeStdout()`](#pipestdoutexecachildprocess) but piping the child process's `stderr` instead.337-338-[`childProcess.stderr`](#stderr) must not be `undefined`.339-340-#### pipeAll(execaChildProcess)341-342-`execaChildProcess`: [`execa()` return value](#pipe-multiple-processes)343-344-Combines both [`pipeStdout()`](#pipestdoutexecachildprocess) and [`pipeStderr()`](#pipestderrexecachildprocess).345-346-The [`all` option](#all-2) must be set to `true`.347-335 ### childProcessResult336 337 Type: `object`338 608 unmodified lines