Allow using the `input`, `inputFile` and `stdin` options together (#666)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 66d0efb · Browse files · 10 files·+80 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
10 files+80 added−109 removed
- tests:+29 added−47 removed
- other:+51 added−62 removed
Provenance
- Commit
beabd25- Tree
6347af6- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
66d0efb
10 files changed+80 added−109 removed
modified:lib/stdio/async.js+4 added-8 removed
1234564 unmodified lines11121314151617181924 unmodified lines44454647464849504849505152535451import {createReadStream, createWriteStream} from 'node:fs';import {Buffer} from 'node:buffer';import {Readable, Writable} from 'node:stream';import mergeStreams from '@sindresorhus/merge-streams';import {handleInput} from './handle.js';
4 unmodified lines input: { filePath: ({value}) => ({value: createReadStream(value)}), webStream: ({value}) => ({value: Readable.fromWeb(value)}), iterable: ({value}) => ({value: Readable.from(value)}), stringOrBuffer: ({value}) => ({value: Readable.from(ArrayBuffer.isView(value) ? Buffer.from(value) : value)}), }, output: { filePath: ({value}) => ({value: createWriteStream(value)}), webStream: ({value}) => ({value: Writable.fromWeb(value)}),24 unmodified lines }
if (direction === 'output') { childStream.pipe(value); return; } else { inputStreamsGroups[index] = [...(inputStreamsGroups[index] ?? []), value]; }
if (type === 'stringOrBuffer') { childStream.end(value); return; }
inputStreamsGroups[index] = [...(inputStreamsGroups[index] ?? []), value];};modified:lib/stdio/handle.js+15 added-13 removed
1234456789101110111213141516171819202121222324252626272829303117 unmodified lines4950515252535454555657585657585960616263606162646566676830 unmodified linesimport {getStdioOptionType, isRegularUrl, isUnknownStdioString} from './type.js';import {addStreamDirection} from './direction.js';import {normalizeStdio} from './normalize.js';import {handleInputOption, handleInputFileOption} from './input.js';import {handleNativeStream} from './native.js';import {handleInputOptions} from './input.js';
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync modeexport const handleInput = (addProperties, options) => { const stdio = normalizeStdio(options); const stdioStreamsGroups = stdio .map((stdioOption, index) => getStdioStreams(stdioOption, index, options)) const [stdinStreams, ...otherStreamsGroups] = stdio.map((stdioOption, index) => getStdioStreams(stdioOption, index)); const stdioStreamsGroups = [[...stdinStreams, ...handleInputOptions(options)], ...otherStreamsGroups] .map(stdioStreams => validateStreams(stdioStreams)) .map(stdioStreams => addStreamDirection(stdioStreams)) .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties)); options.stdio = transformStdio(stdioStreamsGroups); return stdioStreamsGroups.flat();};
// We make sure passing an array with a single item behaves the same as passing that item without an array.// This is what users would expect.// For example, `stdout: ['ignore']` behaves the same as `stdout: 'ignore'`.const getStdioStreams = (stdioOption, index, options) => {const getStdioStreams = (stdioOption, index) => { const optionName = getOptionName(index); const stdioOptions = Array.isArray(stdioOption) ? [...new Set(stdioOption)] : [stdioOption]; const isStdioArray = stdioOptions.length > 1; validateStdioArray(stdioOptions, isStdioArray, optionName); return stdioOptions.map(stdioOption => getStdioStream({stdioOption, optionName, index, isStdioArray, options})); return stdioOptions.map(stdioOption => getStdioStream({stdioOption, optionName, index, isStdioArray}));};
const getOptionName = index => KNOWN_OPTION_NAMES[index] ?? `stdio[${index}]`;const KNOWN_OPTION_NAMES = ['stdin', 'stdout', 'stderr'];17 unmodified lines// Using those `stdio` values together with others for the same stream does not make sense, so we make it fail.// However, we do allow it if the array has a single item.const INVALID_STDIO_ARRAY_OPTIONS = ['ignore', 'ipc'];
const getStdioStream = ({stdioOption, optionName, index, isStdioArray, options: {input, inputFile}}) => {const getStdioStream = ({stdioOption, optionName, index, isStdioArray}) => { const type = getStdioOptionType(stdioOption); let stdioStream = {type, value: stdioOption, optionName, index}; const stdioStream = {type, value: stdioOption, optionName, index}; return handleNativeStream(stdioStream, isStdioArray);};
stdioStream = handleInputOption(stdioStream, input); stdioStream = handleInputFileOption(stdioStream, inputFile, input); stdioStream = handleNativeStream(stdioStream, isStdioArray);const validateStreams = stdioStreams => { for (const stdioStream of stdioStreams) { validateFileStdio(stdioStream); }
validateFileStdio(stdioStream);
return stdioStream; return stdioStreams;};
const validateFileStdio = ({type, value, optionName}) => { if (isRegularUrl(value)) {30 unmodified linesmodified:lib/stdio/input.js+15 added-30 removed
123456734567891011129101112131415151617181920212223242526271617181920212930313233343536import {isStream as isNodeStream} from 'is-stream';
// Override the `stdin` option with the `input` optionexport const handleInputOption = (stdioStream, input) => { if (input === undefined || stdioStream.index !== 0) { return stdioStream; }// Append the `stdin` option with the `input` and `inputFile` optionsexport const handleInputOptions = ({input, inputFile}) => [ handleInputOption(input), handleInputFileOption(inputFile),].filter(Boolean);
const optionName = 'input'; validateInputOption(stdioStream.value, optionName); const type = isNodeStream(input) ? 'nodeStream' : 'stringOrBuffer'; return {...stdioStream, value: input, type, optionName};const handleInputOption = input => input && { type: isNodeStream(input) ? 'nodeStream' : 'stringOrBuffer', value: input, optionName: 'input', index: 0,};
// Override the `stdin` option with the `inputFile` optionexport const handleInputFileOption = (stdioStream, inputFile, input) => { if (inputFile === undefined || stdioStream.index !== 0) { return stdioStream; }
if (input !== undefined) { throw new TypeError('The `input` and `inputFile` options cannot be both set.'); }
const optionName = 'inputFile'; validateInputOption(stdioStream.value, optionName); return {...stdioStream, value: inputFile, type: 'filePath', optionName};const handleInputFileOption = inputFile => inputFile && { type: 'filePath', value: inputFile, optionName: 'inputFile', index: 0,};
const validateInputOption = (value, optionName) => { if (!CAN_USE_INPUT.has(value)) { throw new TypeError(`The \`${optionName}\` and \`stdin\` options cannot be both set.`); }};
const CAN_USE_INPUT = new Set([undefined, null, 'overlapped', 'pipe']);modified:lib/stdio/sync.js+10 added-4 removed
22 unmodified lines23 };24 25 const addPropertiesSync = {26 input: {27- filePath: ({value}) => ({value: readFileSync(value), type: 'stringOrBuffer'}),27+ filePath: ({value}) => ({value: readFileSync(value, 'utf8'), type: 'stringOrBuffer'}),28 webStream: forbiddenIfSync,29 nodeStream: forbiddenIfSync,30 iterable: forbiddenIfSync,31 native: forbiddenIfStreamSync,6 unmodified lines38 },39 };40 41 const addInputOptionSync = (stdioStreams, options) => {42- const inputValue = stdioStreams.find(({type}) => type === 'stringOrBuffer')?.value;43- if (inputValue !== undefined) {44- options.input = inputValue;42+ const inputs = stdioStreams.filter(({type}) => type === 'stringOrBuffer');43+ if (inputs.length === 0) {44+ return;45 }46+47+ options.input = inputs.length === 148+ ? inputs[0].value49+ : inputs.map(({value}) => serializeInput(value)).join('');50 };51 52+const serializeInput = value => typeof value === 'string' ? value : new TextDecoder().decode(value);53+54 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in sync mode55 export const pipeOutputSync = (stdioStreams, result) => {56 if (result.output === null) {57 return;16 unmodified linesmodified:lib/stream.js+1 added-1 removed
60 unmodified lines61 // eslint-disable-next-line unicorn/text-encoding-identifier-case62 const isUtf8Encoding = encoding => encoding === 'utf8' || encoding === 'utf-8';63 64 // Retrieve streams created by the `std*` options65-const getCustomStreams = stdioStreams => stdioStreams.filter(({type}) => type !== 'native' && type !== 'stringOrBuffer');65+const getCustomStreams = stdioStreams => stdioStreams.filter(({type}) => type !== 'native');66 67 // Some `stdout`/`stderr` options create a stream, e.g. when passing a file path.68 // The `.pipe()` method automatically ends that stream when `childProcess.stdout|stderr` ends.69 // This makes sure we want for the completion of those streams, in order to catch any error.78 unmodified linesmodified:test/helpers/stdio.js-1 removed
1234556782 unmodified linesexport const getStdinOption = stdioOption => ({stdin: stdioOption});export const getStdoutOption = stdioOption => ({stdout: stdioOption});export const getStderrOption = stdioOption => ({stderr: stdioOption});export const getStdioOption = stdioOption => ({stdio: ['pipe', 'pipe', 'pipe', stdioOption]});export const getPlainStdioOption = stdioOption => ({stdio: stdioOption});export const getInputOption = input => ({input});export const getInputFileOption = inputFile => ({inputFile});
export const getScriptSync = $ => $.sync;2 unmodified linesmodified:test/stdio/file-path.js+28 added-5 removed
8 unmodified lines9 import {getStdinOption, getStdoutOption, getStderrOption, getStdioOption, getInputFileOption, getScriptSync, identity} from '../helpers/stdio.js';10 11 setFixtureDir();12 13+const textEncoder = new TextEncoder();14+const binaryFoobar = textEncoder.encode('foobar');15 const nonFileUrl = new URL('https://example.com');16 17 const getRelativePath = filePath => relative('.', filePath);18 151 unmodified lines170 171 test('inputFile can be set with $', testInputFileScript, identity);172 test('inputFile can be set with $.sync', testInputFileScript, getScriptSync);173 172-test('inputFile option cannot be set when stdin is set', t => {173- t.throws(() => {174- execa('stdin.js', {inputFile: '', stdin: 'ignore'});175- }, {message: /`inputFile` and `stdin` options/});176-});174+const testMultipleInputs = async (t, allGetOptions, execaMethod) => {175+ const filePath = tempfile();176+ await writeFile(filePath, 'foobar');177+ const options = Object.assign({}, ...allGetOptions.map(getOptions => getOptions(filePath)));178+ const {stdout} = await execaMethod('stdin.js', options);179+ t.is(stdout, 'foobar'.repeat(allGetOptions.length));180+ await rm(filePath);181+};182+183+const getStringInput = () => ({input: 'foobar'});184+const getBinaryInput = () => ({input: binaryFoobar});185+186+test('input String and inputFile can be both set', testMultipleInputs, [getInputFileOption, getStringInput], execa);187+test('input String and stdin can be both set', testMultipleInputs, [getStdinOption, getStringInput], execa);188+test('input Uint8Array and inputFile can be both set', testMultipleInputs, [getInputFileOption, getBinaryInput], execa);189+test('input Uint8Array and stdin can be both set', testMultipleInputs, [getStdinOption, getBinaryInput], execa);190+test('stdin and inputFile can be both set', testMultipleInputs, [getStdinOption, getInputFileOption], execa);191+test('input String, stdin and inputFile can be all set', testMultipleInputs, [getInputFileOption, getStdinOption, getStringInput], execa);192+test('input Uint8Array, stdin and inputFile can be all set', testMultipleInputs, [getInputFileOption, getStdinOption, getBinaryInput], execa);193+test('input String and inputFile can be both set - sync', testMultipleInputs, [getInputFileOption, getStringInput], execaSync);194+test('input String and stdin can be both set - sync', testMultipleInputs, [getStdinOption, getStringInput], execaSync);195+test('input Uint8Array and inputFile can be both set - sync', testMultipleInputs, [getInputFileOption, getBinaryInput], execaSync);196+test('input Uint8Array and stdin can be both set - sync', testMultipleInputs, [getStdinOption, getBinaryInput], execaSync);197+test('stdin and inputFile can be both set - sync', testMultipleInputs, [getStdinOption, getInputFileOption], execaSync);198+test('input String, stdin and inputFile can be all set - sync', testMultipleInputs, [getInputFileOption, getStdinOption, getStringInput], execaSync);199+test('input Uint8Array, stdin and inputFile can be all set - sync', testMultipleInputs, [getInputFileOption, getStdinOption, getBinaryInput], execaSync);modified:test/stdio/input.js+1 added-41 removed
1-import {Readable} from 'node:stream';2-import {pathToFileURL} from 'node:url';1 import test from 'ava';2 import {execa, execaSync, $} from '../../index.js';3 import {setFixtureDir} from '../helpers/fixtures-dir.js';6-import {getStdinOption, getPlainStdioOption, getScriptSync, identity} from '../helpers/stdio.js';7-import {stringGenerator} from '../helpers/generator.js';4+import {getScriptSync, identity} from '../helpers/stdio.js';5 6 setFixtureDir();7 8 const textEncoder = new TextEncoder();9 const binaryFoobar = textEncoder.encode('foobar');10 14-const testInputOptionError = (t, stdin, inputName) => {15- t.throws(() => {16- execa('stdin.js', {stdin, [inputName]: 'foobar'});17- }, {message: new RegExp(`\`${inputName}\` and \`stdin\` options`)});18-};19-20-test('stdin option cannot be an iterable when "input" is used', testInputOptionError, stringGenerator(), 'input');21-test('stdin option cannot be an iterable when "inputFile" is used', testInputOptionError, stringGenerator(), 'inputFile');22-test('stdin option cannot be a file URL when "input" is used', testInputOptionError, pathToFileURL('unknown'), 'input');23-test('stdin option cannot be a file URL when "inputFile" is used', testInputOptionError, pathToFileURL('unknown'), 'inputFile');24-test('stdin option cannot be a file path when "input" is used', testInputOptionError, './unknown', 'input');25-test('stdin option cannot be a file path when "inputFile" is used', testInputOptionError, './unknown', 'inputFile');26-test('stdin option cannot be a ReadableStream when "input" is used', testInputOptionError, new ReadableStream(), 'input');27-test('stdin option cannot be a ReadableStream when "inputFile" is used', testInputOptionError, new ReadableStream(), 'inputFile');28-11 const testInput = async (t, input, execaMethod) => {12 const {stdout} = await execaMethod('stdin.js', {input});13 t.is(stdout, 'foobar');14 };9 unmodified lines24 };25 26 test('input option can be used with $', testInputScript, identity);27 test('input option can be used with $.sync', testInputScript, getScriptSync);46-47-const testInputWithStdinError = (t, input, getOptions, execaMethod) => {48- t.throws(() => {49- execaMethod('stdin.js', {input, ...getOptions('ignore')});50- }, {message: /`input` and `stdin` options/});51-};52-53-test('input option cannot be a String when stdin is set', testInputWithStdinError, 'foobar', getStdinOption, execa);54-test('input option cannot be a String when stdio is set', testInputWithStdinError, 'foobar', getPlainStdioOption, execa);55-test('input option cannot be a String when stdin is set - sync', testInputWithStdinError, 'foobar', getStdinOption, execaSync);56-test('input option cannot be a String when stdio is set - sync', testInputWithStdinError, 'foobar', getPlainStdioOption, execaSync);57-test('input option cannot be a Node.js Readable when stdin is set', testInputWithStdinError, new Readable(), getStdinOption, execa);58-test('input option cannot be a Node.js Readable when stdio is set', testInputWithStdinError, new Readable(), getPlainStdioOption, execa);59-60-const testInputAndInputFile = async (t, execaMethod) => {61- t.throws(() => execaMethod('stdin.js', {inputFile: '', input: ''}), {62- message: /cannot be both set/,63- });64-};65-66-test('inputFile and input cannot be both set', testInputAndInputFile, execa);67-test('inputFile and input cannot be both set - sync', testInputAndInputFile, execaSync);modified:index.d.ts+3 added-3 removed
117 unmodified lines118 - `'inherit'`: Re-use the current process' `stdin`.119 - an integer: Re-use a specific file descriptor from the current process.120 - a Node.js `Readable` stream.121 122- Unless either the synchronous methods, the `input` option or the `inputFile` option is used, the value can also be a:122+ Unless the synchronous methods are used, the value can also be a:123 - file path. If relative, it must start with `.`.124 - file URL.125 - web [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).126 - [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)13 unmodified lines140 - `'inherit'`: Re-use the current process' `stdout`.141 - an integer: Re-use a specific file descriptor from the current process.142 - a Node.js `Writable` stream.143 144- Unless either synchronous methods, the value can also be a:144+ Unless the synchronous methods are used, the value can also be a:145 - file path. If relative, it must start with `.`.146 - file URL.147 - web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).148 12 unmodified lines161 - `'inherit'`: Re-use the current process' `stderr`.162 - an integer: Re-use a specific file descriptor from the current process.163 - a Node.js `Writable` stream.164 165- Unless either synchronous methods, the value can also be a:165+ Unless the synchronous methods are used, the value can also be a:166 - file path. If relative, it must start with `.`.167 - file URL.168 - web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).169 913 unmodified linesmodified:readme.md+3 added-3 removed
579 unmodified lines580 - `'inherit'`: Re-use the current process' `stdin`.581 - an integer: Re-use a specific file descriptor from the current process.582 - a [Node.js `Readable` stream](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr).583 584-Unless either the [synchronous methods](#execasyncfile-arguments-options), the [`input` option](#input) or the [`inputFile` option](#inputfile) is used, the value can also be a:584+Unless the [synchronous methods](#execasyncfile-arguments-options) are used, the value can also be a:585 - file path. If relative, it must start with `.`.586 - file URL.587 - web [`ReadableStream`](https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream).588 - [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols)13 unmodified lines602 - `'inherit'`: Re-use the current process' `stdout`.603 - an integer: Re-use a specific file descriptor from the current process.604 - a [Node.js `Writable` stream](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr).605 606-Unless either [synchronous methods](#execasyncfile-arguments-options), the value can also be a:606+Unless the [synchronous methods](#execasyncfile-arguments-options) are used, the value can also be a:607 - file path. If relative, it must start with `.`.608 - file URL.609 - web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).610 12 unmodified lines623 - `'inherit'`: Re-use the current process' `stderr`.624 - an integer: Re-use a specific file descriptor from the current process.625 - a [Node.js `Writable` stream](#redirect-a-nodejs-stream-fromto-stdinstdoutstderr).626 627-Unless either [synchronous methods](#execasyncfile-arguments-options), the value can also be a:627+Unless the [synchronous methods](#execasyncfile-arguments-options) are used, the value can also be a:628 - file path. If relative, it must start with `.`.629 - file URL.630 - web [`WritableStream`](https://developer.mozilla.org/en-US/docs/Web/API/WritableStream).631 298 unmodified lines