Simplify `std*` options logic (#691)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 0298730 · Browse files · 6 files·+45 added−40 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+45 added−40 removed
- other:+45 added−40 removed
Provenance
- Commit
98b0ee3- Tree
dba588a- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
0298730
6 files changed+45 added−40 removed
modified:lib/stdio/async.js+7 added-5 removed
30 unmodified lines313233343535363738383939404142434445464748494850515253545554565758596030 unmodified lines};
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode// When multiple input streams are used, we merge them to ensure the output stream ends only once each input stream has endedexport const pipeOutputAsync = (spawned, stdioStreams) => {export const pipeOutputAsync = (spawned, stdioStreamsGroups) => { const inputStreamsGroups = {};
for (const stdioStreams of stdioStreamsGroups) { for (const stdioStream of stdioStreams) { pipeStdioOption(spawned.stdio[stdioStream.index], stdioStream, inputStreamsGroups); for (const stdioStream of stdioStreams) { pipeStdioOption(spawned, stdioStream, inputStreamsGroups); } }
for (const [index, inputStreams] of Object.entries(inputStreamsGroups)) { const value = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams); value.pipe(spawned.stdio[index]); }};
const pipeStdioOption = (childStream, {type, value, direction, index}, inputStreamsGroups) => {const pipeStdioOption = (spawned, {type, value, direction, index}, inputStreamsGroups) => { if (type === 'native') { return; }
if (direction === 'output') { childStream.pipe(value); spawned.stdio[index].pipe(value); } else { inputStreamsGroups[index] = [...(inputStreamsGroups[index] ?? []), value]; }};modified:lib/stdio/direction.js+7 added-4 removed
24 unmodified lines25262728293031323331323334343536373839404126 unmodified lines24 unmodified lines
// `stdin`/`stdout`/`stderr` have a known directionconst KNOWN_DIRECTIONS = ['input', 'output', 'output'];
const anyDirection = () => undefined;const alwaysInput = () => 'input';
// `string` can only be added through the `input` option, i.e. does not need to be handled hereconst guessStreamDirection = { fileUrl: () => undefined, filePath: () => undefined, iterable: () => 'input', uint8Array: () => 'input', fileUrl: anyDirection, filePath: anyDirection, iterable: alwaysInput, uint8Array: alwaysInput, webStream: stdioOption => isWritableStream(stdioOption) ? 'output' : 'input', nodeStream(stdioOption) { if (isNodeReadableStream(stdioOption)) { return isNodeWritableStream(stdioOption) ? undefined : 'input';26 unmodified linesmodified:lib/stdio/handle.js+1 added-1 removed
11 unmodified lines12 .map(stdioStreams => validateStreams(stdioStreams))13 .map(stdioStreams => addStreamDirection(stdioStreams))14 .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties));15 options.stdio = transformStdio(stdioStreamsGroups);16- return {stdioStreams: stdioStreamsGroups.flat(), stdioLength: stdioStreamsGroups.length};16+ return stdioStreamsGroups;17 };18 19 // We make sure passing an array with a single item behaves the same as passing that item without an array.20 // This is what users would expect.78 unmodified linesmodified:lib/stdio/sync.js+10 added-8 removed
4 unmodified lines5 import {bufferToUint8Array} from './utils.js';6 7 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode8 export const handleInputSync = options => {9- const {stdioStreams, stdioLength} = handleInput(addPropertiesSync, options);10- addInputOptionSync(stdioStreams, options);11- return {stdioStreams, stdioLength};9+ const stdioStreamsGroups = handleInput(addPropertiesSync, options);10+ addInputOptionSync(stdioStreamsGroups, options);11+ return stdioStreamsGroups;12 };13 14 const forbiddenIfStreamSync = ({value, optionName}) => {15 if (isNodeStream(value)) {25 unmodified lines41 native: forbiddenIfStreamSync,42 },43 };44 45-const addInputOptionSync = (stdioStreams, options) => {46- const inputs = stdioStreams.filter(({type}) => type === 'string' || type === 'uint8Array');45+const addInputOptionSync = (stdioStreamsGroups, options) => {46+ const inputs = stdioStreamsGroups.flat().filter(({type}) => type === 'string' || type === 'uint8Array');47 if (inputs.length === 0) {48 return;49 }50 4 unmodified lines55 56 const serializeInput = ({type, value}) => type === 'string' ? value : new TextDecoder().decode(value);57 58 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in sync mode59-export const pipeOutputSync = (stdioStreams, result) => {59+export const pipeOutputSync = (stdioStreamsGroups, result) => {60 if (result.output === null) {61 return;62 }63 64+ for (const stdioStreams of stdioStreamsGroups) {64- for (const stdioStream of stdioStreams) {65- pipeStdioOptionSync(result.output[stdioStream.index], stdioStream);65+ for (const stdioStream of stdioStreams) {66+ pipeStdioOptionSync(result.output[stdioStream.index], stdioStream);67+ }68 }69 };70 71 const pipeStdioOptionSync = (result, {type, value, direction}) => {8 unmodified linesmodified:lib/stream.js+10 added-11 removed
33 unmodified lines34 return error.bufferedData === undefined ? undefined : applyEncoding(error.bufferedData, encoding);35 }36 };37 38-const getStdioPromise = ({stream, index, stdioStreams, encoding, buffer, maxBuffer}) => {39- const stdioStream = stdioStreams.find(stdioStream => stdioStream.index === index);40- return stdioStream?.direction === 'output' ? getStreamPromise(stream, {encoding, buffer, maxBuffer}) : undefined;41-};38+const getStdioPromise = ({stream, index, stdioStreamsGroups, encoding, buffer, maxBuffer}) => stdioStreamsGroups[index]?.[0]?.direction === 'output'39+ ? getStreamPromise(stream, {encoding, buffer, maxBuffer})40+ : undefined;41 42 const getStreamPromise = async (stream, {encoding, buffer, maxBuffer}) => {43 if (!stream || !buffer) {44 return;20 unmodified lines65 // eslint-disable-next-line unicorn/text-encoding-identifier-case66 const isUtf8Encoding = encoding => encoding === 'utf8' || encoding === 'utf-8';67 68 // Retrieve streams created by the `std*` options70-const getCustomStreams = stdioStreams => stdioStreams.filter(({type}) => type !== 'native');69+const getCustomStreams = stdioStreamsGroups => stdioStreamsGroups.flat().filter(({type}) => type !== 'native');70 71 // Some `stdout`/`stderr` options create a stream, e.g. when passing a file path.72 // The `.pipe()` method automatically ends that stream when `childProcess.stdout|stderr` ends.73 // This makes sure we want for the completion of those streams, in order to catch any error.23 unmodified lines97 // The streams created by the `std*` options are automatically ended by `.pipe()`.98 // However `.pipe()` only does so when the source stream ended, not when it errored.99 // Therefore, when `childProcess.stdin|stdout|stderr` errors, those streams must be manually destroyed.100 const cleanupStdioStreams = (customStreams, error) => {102- for (const customStream of customStreams) {103- if (!STANDARD_STREAMS.includes(customStream.value)) {104- customStream.value.destroy(error);101+ for (const {value} of customStreams) {102+ if (!STANDARD_STREAMS.includes(value)) {103+ value.destroy(error);104 }105 }106 };107 1 unmodified line109 export const getSpawnedResult = async (110 spawned,111 {encoding, buffer, maxBuffer, timeout, killSignal, cleanup, detached},112 context,114- stdioStreams,113+ stdioStreamsGroups,114 ) => {115 const finalizers = [];116 cleanupOnExit(spawned, cleanup, detached, finalizers);118- const customStreams = getCustomStreams(stdioStreams);117+ const customStreams = getCustomStreams(stdioStreamsGroups);118 120- const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, index, stdioStreams, encoding, buffer, maxBuffer}));119+ const stdioPromises = spawned.stdio.map((stream, index) => getStdioPromise({stream, index, stdioStreamsGroups, encoding, buffer, maxBuffer}));120 const allPromise = getStreamPromise(spawned.all, {encoding, buffer, maxBuffer: maxBuffer * 2});121 122 try {123 return await Promise.race([25 unmodified linesmodified:index.js+10 added-11 removed
94 unmodified lines95 export function execa(rawFile, rawArgs, rawOptions) {96 const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, rawOptions);97 validateTimeout(options);98 99- const {stdioStreams, stdioLength} = handleInputAsync(options);99+ const stdioStreamsGroups = handleInputAsync(options);100 101 let spawned;102 try {103 spawned = childProcess.spawn(file, args, options);1 unmodified line105 // Ensure the returned error is always both a promise and a child process106 const dummySpawned = new childProcess.ChildProcess();107 const errorPromise = Promise.reject(makeError({108 error,109- stdio: Array.from({length: stdioLength}),109+ stdio: Array.from({length: stdioStreamsGroups.length}),110 command,111 escapedCommand,112 options,113 timedOut: false,2 unmodified lines116 mergePromise(dummySpawned, errorPromise);117 return dummySpawned;118 }119 120+ pipeOutputAsync(spawned, stdioStreamsGroups);121+122 const context = {isCanceled: false, timedOut: false};123 124 spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));125 spawned.cancel = spawnedCancel.bind(null, spawned, context);124-125- pipeOutputAsync(spawned, stdioStreams);126-126 spawned.all = makeAllStream(spawned, options);127 128 addPipeMethods(spawned);129 131- const promise = handlePromise({spawned, options, context, stdioStreams, command, escapedCommand});130+ const promise = handlePromise({spawned, options, context, stdioStreamsGroups, command, escapedCommand});131 mergePromise(spawned, promise);132 return spawned;133 }134 136-const handlePromise = async ({spawned, options, context, stdioStreams, command, escapedCommand}) => {135+const handlePromise = async ({spawned, options, context, stdioStreamsGroups, command, escapedCommand}) => {136 const [137 [exitCode, signal, error],138 stdioResults,139 allResult,141- ] = await getSpawnedResult(spawned, options, context, stdioStreams);140+ ] = await getSpawnedResult(spawned, options, context, stdioStreamsGroups);141 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));142 const all = handleOutput(options, allResult);143 144 if (error || exitCode !== 0 || signal !== null) {35 unmodified lines180 181 export function execaSync(rawFile, rawArgs, rawOptions) {182 const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, rawOptions);183 185- const {stdioStreams, stdioLength} = handleInputSync(options);184+ const stdioStreamsGroups = handleInputSync(options);185 186 let result;187 try {188 result = childProcess.spawnSync(file, args, options);189 } catch (error) {190 throw makeError({191 error,193- stdio: Array.from({length: stdioLength}),192+ stdio: Array.from({length: stdioStreamsGroups.stdioLength}),193 command,194 escapedCommand,195 options,196 timedOut: false,197 isCanceled: false,198 });199 }200 202- pipeOutputSync(stdioStreams, result);201+ pipeOutputSync(stdioStreamsGroups, result);202 203 const output = result.output || Array.from({length: 3});204 const stdio = output.map(stdioOutput => handleOutput(options, stdioOutput));205 111 unmodified lines