Skip to content
Myr

Refactor `stdio` options (#623)

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

authored by ehmicky · committed by GitHub · parent 14485c7 · Browse files · 10 files+315 added−301 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+315 added−301 removed

  • tests:+4 added−4 removed
  • other:+311 added−297 removed

10 files+315 added−301 removed

added:lib/stdio/async.js+46 added
added:lib/stdio/input.js+98 added
1import {isStream as isNodeStream} from 'is-stream';2import {getStdioOptionType, isRegularUrl, isUnknownStdioString} from './type.js';3import {normalizeStdio} from './normalize.js';45// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode6export const handleInput = (addProperties, options) => {7 const stdio = normalizeStdio(options);8 const stdioArray = arrifyStdio(stdio);9 const stdioStreams = stdioArray.map((stdioOption, index) => getStdioStream(stdioOption, index, addProperties, options));10 options.stdio = transformStdio(stdio, stdioStreams);11 return stdioStreams;12};1314const arrifyStdio = (stdio = []) => Array.isArray(stdio) ? stdio : [stdio, stdio, stdio];1516const getStdioStream = (stdioOption, index, addProperties, {input, inputFile}) => {17 let stdioStream = {18 type: getStdioOptionType(stdioOption),19 value: stdioOption,20 optionName: OPTION_NAMES[index],21 direction: index === 0 ? 'input' : 'output',22 };23 validateFileStdio(stdioStream);2425 stdioStream = handleInputOption(stdioStream, index, input);26 stdioStream = handleInputFileOption(stdioStream, index, inputFile, input);2728 return {29 ...stdioStream,30 ...addProperties[stdioStream.direction][stdioStream.type]?.(stdioStream),31 };32};3334const OPTION_NAMES = ['stdin', 'stdout', 'stderr'];3536const validateFileStdio = ({type, value, optionName}) => {37 if (type !== 'native') {38 return;39 }4041 validateRegularUrl(value, optionName);4243 if (isUnknownStdioString(value)) {44 throw new TypeError(`The \`${optionName}: filePath\` option must either be an absolute file path or start with \`.\`.`);45 }46};4748// Override the `stdin` option with the `input` option49const handleInputOption = (stdioStream, index, input) => {50 if (input === undefined || index !== 0) {51 return stdioStream;52 }5354 const optionName = 'input';55 validateInputOption(stdioStream.value, optionName);56 const type = isNodeStream(input) ? 'nodeStream' : 'stringOrBuffer';57 return {...stdioStream, value: input, type, optionName};58};5960// Override the `stdin` option with the `inputFile` option61const handleInputFileOption = (stdioStream, index, inputFile, input) => {62 if (inputFile === undefined || index !== 0) {63 return stdioStream;64 }6566 if (input !== undefined) {67 throw new TypeError('The `input` and `inputFile` options cannot be both set.');68 }6970 const optionName = 'inputFile';71 validateInputOption(stdioStream.value, optionName);72 validateRegularUrl(inputFile, optionName);73 return {...stdioStream, value: inputFile, type: 'filePath', optionName};74};7576const validateInputOption = (value, optionName) => {77 if (!CAN_USE_INPUT.has(value)) {78 throw new TypeError(`The \`${optionName}\` and \`stdin\` options cannot be both set.`);79 }80};8182const CAN_USE_INPUT = new Set([undefined, null, 'overlapped', 'pipe']);8384const validateRegularUrl = (value, optionName) => {85 if (isRegularUrl(value)) {86 throw new TypeError(`The \`${optionName}: URL\` option must use the \`file:\` scheme.87For example, you can use the \`pathToFileURL()\` method of the \`url\` core module.`);88 }89};9091// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `spawned.std*`.92// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `spawned.std*`.93const transformStdio = (stdio, stdioStreams) => Array.isArray(stdio)94 ? stdio.map((stdioItem, index) => transformStdioItem(stdioItem, index, stdioStreams))95 : stdio;9697const transformStdioItem = (stdioItem, index, stdioStreams) =>98 stdioStreams[index].type !== 'native' && stdioItem !== 'overlapped' ? 'pipe' : stdioItem;
added:lib/stdio/normalize.js+50 added
added:lib/stdio/sync.js+56 added
added:lib/stdio/type.js+51 added
deleted:lib/stdio.js-289 removed
1import {createReadStream, createWriteStream, readFileSync, writeFileSync} from 'node:fs';2import {isAbsolute} from 'node:path';3import {Readable, Writable} from 'node:stream';4import {isStream as isNodeStream} from 'is-stream';56const arrifyStdio = (stdio = []) => Array.isArray(stdio) ? stdio : [stdio, stdio, stdio];78const isIterableStdin = stdinOption => typeof stdinOption === 'object'9 && stdinOption !== null10 && !isNodeStream(stdinOption)11 && !isReadableStream(stdinOption)12 && (typeof stdinOption[Symbol.asyncIterator] === 'function' || typeof stdinOption[Symbol.iterator] === 'function');1314const getIterableStdin = stdioOption => isIterableStdin(stdioOption)15 ? stdioOption16 : undefined;1718const isUrlInstance = stdioOption => Object.prototype.toString.call(stdioOption) === '[object URL]';19const hasFileProtocol = url => url.protocol === 'file:';20const isFileUrl = stdioOption => isUrlInstance(stdioOption) && hasFileProtocol(stdioOption);21const isRegularUrl = stdioOption => isUrlInstance(stdioOption) && !hasFileProtocol(stdioOption);2223const stringIsFilePath = stdioOption => stdioOption.startsWith('.') || isAbsolute(stdioOption);24const isFilePath = stdioOption => typeof stdioOption === 'string' && stringIsFilePath(stdioOption);25const isUnknownStdioString = stdioOption => typeof stdioOption === 'string' && !stringIsFilePath(stdioOption) && !KNOWN_STDIO.has(stdioOption);2627const isReadableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object ReadableStream]';28const isWritableStream = stdioOption => Object.prototype.toString.call(stdioOption) === '[object WritableStream]';2930// Check whether the `stdin` option results in `spawned.stdin` being `undefined`.31// We use a deny list instead of an allow list to be forward compatible with new options.32const cannotPipeStdin = stdinOption => NO_PIPE_STDIO.has(stdinOption)33 || isNodeStream(stdinOption)34 || isReadableStream(stdinOption)35 || typeof stdinOption === 'number'36 || isIterableStdin(stdinOption)37 || isFileUrl(stdinOption)38 || isFilePath(stdinOption);3940const NO_PIPE_STDIO = new Set(['ipc', 'ignore', 'inherit']);41const KNOWN_STDIO = new Set([...NO_PIPE_STDIO, 'overlapped', 'pipe']);4243const validateFileSdio = (stdioOption, optionName) => {44 if (isRegularUrl(stdioOption)) {45 throw new TypeError(`The \`${optionName}: URL\` option must use the \`file:\` scheme.46For example, you can use the \`pathToFileURL()\` method of the \`url\` core module.`);47 }4849 if (isUnknownStdioString(stdioOption)) {50 throw new TypeError(`The \`${optionName}: filePath\` option must either be an absolute file path or start with \`.\`.`);51 }52};5354const validateInputOptions = (stdioArray, input, inputFile) => {55 if (input !== undefined && inputFile !== undefined) {56 throw new TypeError('The `input` and `inputFile` options cannot be both set.');57 }5859 const noPipeStdin = cannotPipeStdin(stdioArray[0]);60 if (noPipeStdin && input !== undefined) {61 throw new TypeError('The `input` and `stdin` options cannot be both set.');62 }6364 if (noPipeStdin && inputFile !== undefined) {65 throw new TypeError('The `inputFile` and `stdin` options cannot be both set.');66 }6768 validateFileSdio(stdioArray[0], 'stdin');69 validateFileSdio(stdioArray[1], 'stdout');70 validateFileSdio(stdioArray[2], 'stderr');71};7273const getStdioStreams = (stdioArray, {input, inputFile}) => [74 {...getStdinStream(stdioArray[0], input, inputFile), isInput: true},75 getOutputStream(stdioArray[1]),76 getOutputStream(stdioArray[2]),77];7879const getStdinStream = (stdinOption, input, inputFile) => {80 const iterableStdin = getIterableStdin(stdinOption);8182 if (iterableStdin !== undefined) {83 return {value: Readable.from(iterableStdin)};84 }8586 if (isReadableStream(stdinOption)) {87 return {value: Readable.fromWeb(stdinOption)};88 }8990 if (isFileUrl(stdinOption) || isFilePath(stdinOption)) {91 return {value: createReadStream(stdinOption), finite: true};92 }9394 if (inputFile !== undefined) {95 return {value: createReadStream(inputFile), finite: true};96 }9798 if (input === undefined) {99 return {};100 }101102 if (isNodeStream(input)) {103 return {value: input};104 }105106 return {value: input, single: true};107};108109const getOutputStream = stdioOption => {110 if (isWritableStream(stdioOption)) {111 return {value: Writable.fromWeb(stdioOption)};112 }113114 if (isFileUrl(stdioOption) || isFilePath(stdioOption)) {115 return {value: createWriteStream(stdioOption), finite: true};116 }117118 return {};119};120121// When the `stdin: Iterable | ReadableStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `spawned.std*`.122// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `spawned.std*`.123const transformStdioItem = (stdioItem, index, stdioStreams) =>124 stdioStreams[index]?.value !== undefined && stdioItem !== 'overlapped' ? 'pipe' : stdioItem;125126const transformStdio = (stdio, stdioStreams) => Array.isArray(stdio)127 ? stdio.map((stdioItem, index) => transformStdioItem(stdioItem, index, stdioStreams))128 : stdio;129130// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async mode131export const handleStdioOption = options => {132 const stdio = normalizeStdio(options);133 const stdioArray = arrifyStdio(stdio);134 validateInputOptions(stdioArray, options.input, options.inputFile);135 const stdioStreams = getStdioStreams(stdioArray, options);136 options.stdio = transformStdio(stdio, stdioStreams);137 return stdioStreams;138};139140// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode141export const pipeStdioOptions = (spawned, stdioStreams) => {142 for (const [index, stdioStream] of stdioStreams.entries()) {143 pipeStdioOption(spawned.stdio[index], stdioStream);144 }145};146147const pipeStdioOption = (childStream, {single, value, isInput}) => {148 if (value === undefined) {149 return;150 }151152 if (!isInput) {153 childStream.pipe(value);154 return;155 }156157 if (single) {158 childStream.end(value);159 return;160 }161162 value.pipe(childStream);163};164165const transformStdioItemSync = stdioItem => isFileUrl(stdioItem) || isFilePath(stdioItem) ? 'pipe' : stdioItem;166167const transformStdioSync = stdio => Array.isArray(stdio)168 ? stdio.map(stdioItem => transformStdioItemSync(stdioItem))169 : stdio;170171const validateInputOptionsSync = (stdinOption, input) => {172 if (getIterableStdin(stdinOption) !== undefined) {173 throw new TypeError('The `stdin` option cannot be an iterable in sync mode');174 }175176 if (isReadableStream(stdinOption)) {177 throw new TypeError('The `stdin` option cannot be a stream in sync mode');178 }179180 if (isNodeStream(input)) {181 throw new TypeError('The `input` option cannot be a stream in sync mode');182 }183};184185const validateOutputOptionsSync = (stdioOption, optionName) => {186 if (isWritableStream(stdioOption)) {187 throw new TypeError(`The \`${optionName}\` option cannot be a stream in sync mode`);188 }189};190191const validateOptionsSync = (stdioArray, {input, inputFile}) => {192 validateInputOptions(stdioArray, input, inputFile);193 validateInputOptionsSync(stdioArray[0], input);194 validateOutputOptionsSync(stdioArray[1], 'stdout');195 validateOutputOptionsSync(stdioArray[2], 'stderr');196};197198const getInputOption = (stdinOption, {input, inputFile}) => {199 if (isFileUrl(stdinOption) || isFilePath(stdinOption)) {200 return readFileSync(stdinOption);201 }202203 if (inputFile !== undefined) {204 return readFileSync(inputFile);205 }206207 return input;208};209210// Handle `input`, `inputFile` and `stdin` options, before spawning, in sync mode211export const handleInputSync = options => {212 const stdio = normalizeStdio(options);213 const stdioArray = arrifyStdio(stdio);214 validateOptionsSync(stdioArray, options);215216 const input = getInputOption(stdioArray[0], options);217 if (input !== undefined) {218 options.input = input;219 }220221 options.stdio = transformStdioSync(stdio);222 return stdioArray;223};224225// Handle `stdout` and `stderr` options, before spawning, in sync mode226const handleOutputOption = (stdioOption, result) => {227 if (result === null) {228 return;229 }230231 if (isFileUrl(stdioOption) || isFilePath(stdioOption)) {232 writeFileSync(stdioOption, result);233 }234};235236export const handleOutputSync = (stdioArray, {stdout, stderr}) => {237 handleOutputOption(stdioArray[1], stdout);238 handleOutputOption(stdioArray[2], stderr);239};240241const aliases = ['stdin', 'stdout', 'stderr'];242243const hasAlias = options => aliases.some(alias => options[alias] !== undefined);244245export const normalizeStdio = options => {246 if (!options) {247 return;248 }249250 const {stdio} = options;251252 if (stdio === undefined) {253 return aliases.map(alias => options[alias]);254 }255256 if (hasAlias(options)) {257 throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map(alias => `\`${alias}\``).join(', ')}`);258 }259260 if (typeof stdio === 'string') {261 return stdio;262 }263264 if (!Array.isArray(stdio)) {265 throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);266 }267268 const length = Math.max(stdio.length, aliases.length);269 return Array.from({length}, (value, index) => stdio[index]);270};271272// `ipc` is pushed unless it is already present273export const normalizeStdioNode = options => {274 const stdio = normalizeStdio(options);275276 if (stdio === 'ipc') {277 return 'ipc';278 }279280 if (stdio === undefined || typeof stdio === 'string') {281 return [stdio, stdio, stdio, 'ipc'];282 }283284 if (stdio.includes('ipc')) {285 return stdio;286 }287288 return [...stdio, 'ipc'];289};
modified:lib/stream.js+3 added-3 removed
56 unmodified lines
57// We need to handle any `error` coming from the `stdin|stdout|stderr` options.58// However, those might be infinite streams, e.g. a TTY passed as input or output.59// We wait for completion or not depending on whether `finite` is `true`.60// In either case, we handle `error` events while the process is running.61const waitForStreamEnd = ({value, finite, single}, processDone) => {62 if (value === undefined || single) {61const waitForStreamEnd = ({value, type}, processDone) => {62 if (type === 'native' || type === 'stringOrBuffer') {63 return;64 }6566 return finite66 return type === 'filePath'67 ? finished(value)68 : Promise.race([processDone, throwOnStreamError(value)]);69};70
34 unmodified lines
modified:test/stdio.js+1 added-1 removed
modified:test/stream.js+3 added-3 removed
533 unmodified lines
534535test('input cannot be a Node.js Readable in sync mode', t => {536 t.throws(() => {537 execaSync('stdin.js', {input: new Stream.PassThrough()});538 }, {message: /The `input` option cannot be a stream in sync mode/});538 }, {message: /The `input` option cannot be a Node\.js stream in sync mode/});539});540541test('stdin cannot be a ReadableStream in sync mode', t => {542 const stdin = Stream.Readable.toWeb(Stream.Readable.from('howdy'));543 t.throws(() => {544 execaSync('stdin.js', {stdin});545 }, {message: /The `stdin` option cannot be a stream in sync mode/});545 }, {message: /The `stdin` option cannot be a web stream in sync mode/});546});547548const testWritableStreamSync = (t, streamName) => {549 t.throws(() => {550 execaSync('noop.js', {[streamName]: new WritableStream()});551 }, {message: new RegExp(`The \`${streamName}\` option cannot be a stream in sync mode`)});551 }, {message: new RegExp(`The \`${streamName}\` option cannot be a web stream in sync mode`)});552};553554test('stdout cannot be a WritableStream in sync mode', testWritableStreamSync, 'stdout');555test('stderr cannot be a WritableStream in sync mode', testWritableStreamSync, 'stderr');
207 unmodified lines
modified:index.js+7 added-5 removed
5 unmodified lines
6import stripFinalNewline from 'strip-final-newline';7import {npmRunPathEnv} from 'npm-run-path';8import onetime from 'onetime';9import {makeError} from './lib/error.js';10import {handleStdioOption, handleInputSync, handleOutputSync, pipeStdioOptions, normalizeStdioNode} from './lib/stdio.js';10import {handleInputAsync, pipeOutputAsync} from './lib/stdio/async.js';11import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';12import {normalizeStdioNode} from './lib/stdio/normalize.js';13import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';14import {addPipeMethods} from './lib/pipe.js';15import {getSpawnedResult, makeAllStream} from './lib/stream.js';16import {mergePromise, getSpawnedPromise} from './lib/promise.js';
59 unmodified lines
76};7778export function execa(file, args, options) {79 const parsed = handleArguments(file, args, options);78 const stdioStreams = handleStdioOption(parsed.options);80 const stdioStreams = handleInputAsync(parsed.options);81 validateTimeout(parsed.options);8283 const command = joinCommand(file, args);84 const escapedCommand = getEscapedCommand(file, args);
74 unmodified lines
159 };160161 const handlePromiseOnce = onetime(handlePromise);162161 pipeStdioOptions(spawned, stdioStreams);163 pipeOutputAsync(spawned, stdioStreams);164165 spawned.all = makeAllStream(spawned, parsed.options);166167 addPipeMethods(spawned);
2 unmodified lines
170}171172export function execaSync(file, args, options) {173 const parsed = handleArguments(file, args, options);172 const stdioArray = handleInputSync(parsed.options);174 const stdioStreams = handleInputSync(parsed.options);175176 const command = joinCommand(file, args);177 const escapedCommand = getEscapedCommand(file, args);178 logCommand(escapedCommand, parsed.options);
15 unmodified lines
194 killed: false,195 });196 }197196 handleOutputSync(stdioArray, result);198 pipeOutputSync(stdioStreams, result);199 const stdout = handleOutput(parsed.options, result.stdout, result.error);200 const stderr = handleOutput(parsed.options, result.stderr, result.error);201202 if (result.error || result.status !== 0 || result.signal !== null) {
111 unmodified lines