Handle `inputFile` missing file (#609)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent ec380db · Browse files · 4 files·+149 added−84 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+149 added−84 removed
- tests:+30 added−2 removed
- other:+119 added−82 removed
Provenance
- Commit
8638ce7- Tree
3870fe9- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
ec380db
4 files changed+149 added−84 removed
modified:lib/stdio.js+106 added-13 removed
1234567891011121311121314151617181920212223242526272829303116323334353637383940411920214243442324454647484950515253545556282957585960616263646566676869707172737475767778798034358182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413543 unmodified linesimport {createReadStream, readFileSync} from 'node:fs';import {Readable} from 'node:stream';import {isStream} from 'is-stream';
const aliases = ['stdin', 'stdout', 'stderr'];
const arrifyStdio = (stdio = []) => Array.isArray(stdio) ? stdio : [stdio, stdio, stdio];
const isIterableStdin = stdinOption => typeof stdinOption === 'object' && stdinOption !== null && !isStream(stdinOption) && (typeof stdinOption[Symbol.asyncIterator] === 'function' || typeof stdinOption[Symbol.iterator] === 'function');
const transformStdioItem = (stdioItem, index) => { if (index === 0 && isIterableStdin(stdioItem)) { return 'pipe';const getIterableStdin = stdioArray => isIterableStdin(stdioArray[0]) ? stdioArray[0] : undefined;
// Check whether the `stdin` option results in `spawned.stdin` being `undefined`.// We use a deny list instead of an allow list to be forward compatible with new options.const cannotPipeStdio = stdioOption => NO_PIPE_STDIN.has(stdioOption) || isStream(stdioOption) || typeof stdioOption === 'number' || isIterableStdin(stdioOption);
const NO_PIPE_STDIN = new Set(['ipc', 'ignore', 'inherit']);
const validateInputOptions = (stdioArray, input, inputFile) => { if (input !== undefined && inputFile !== undefined) { throw new TypeError('The `input` and `inputFile` options cannot be both set.'); }
return stdioItem; const noPipeStdin = cannotPipeStdio(stdioArray[0]); if (noPipeStdin && input !== undefined) { throw new TypeError('The `input` and `stdin` options cannot be both set.'); }
if (noPipeStdin && inputFile !== undefined) { throw new TypeError('The `inputFile` and `stdin` options cannot be both set.'); }};
const transformStdio = stdio => Array.isArray(stdio) ? stdio.map((stdioItem, index) => transformStdioItem(stdioItem, index)) : stdio;const getStdioStreams = (stdioArray, {input, inputFile}) => { const iterableStdin = getIterableStdin(stdioArray);
const getStdioStreams = stdio => { if (!Array.isArray(stdio) || !isIterableStdin(stdio[0])) { if (iterableStdin !== undefined) { return {stdinStream: Readable.from(iterableStdin)}; }
if (inputFile !== undefined) { return {stdinStream: createReadStream(inputFile)}; }
if (input === undefined) { return {}; }
const stdinIterableStream = Readable.from(stdio[0]); return {stdinIterableStream}; if (isStream(input)) { return {stdinStream: input}; }
return {stdinInput: input};};
// When the `stdin: iterable`, `input` or `inputFile` option is used, we pipe to `spawned.stdin`.// Therefore the `stdin` option must be either `pipe` or `overlapped`. Other values do not set `spawned.stdin`.const willPipeStdin = (index, {stdinStream, stdinInput}) => index === 0 && (stdinStream !== undefined || stdinInput !== undefined);
const transformStdioItem = (stdioItem, index, stdioStreams) => willPipeStdin(index, stdioStreams) && stdioItem !== 'overlapped' ? 'pipe' : stdioItem;
const transformStdio = (stdio, stdioStreams) => Array.isArray(stdio) ? stdio.map((stdioItem, index) => transformStdioItem(stdioItem, index, stdioStreams)) : stdio;
// Handle `input`, `inputFile` and `stdin` options, before spawning, in async modeexport const handleStdioOption = options => { const stdio = normalizeStdio(options); const stdioArray = arrifyStdio(stdio); validateInputOptions(stdioArray, options.input, options.inputFile); const stdioStreams = getStdioStreams(stdio); options.stdio = transformStdio(stdio); const stdioStreams = getStdioStreams(stdioArray, options); options.stdio = transformStdio(stdio, stdioStreams); return stdioStreams;};
// Handle `input`, `inputFile` and `stdin` options, after spawning, in async modeexport const pipeStdioOption = (spawned, {stdinStream, stdinInput}) => { if (stdinStream !== undefined) { stdinStream.pipe(spawned.stdin); return; }
if (stdinInput !== undefined) { spawned.stdin.end(stdinInput); }};
const validateInputOptionsSync = (stdioArray, input) => { if (getIterableStdin(stdioArray) !== undefined) { throw new TypeError('The `stdin` option cannot be an iterable in sync mode'); }
if (isStream(input)) { throw new TypeError('The `input` option cannot be a stream in sync mode'); }};
const getInputOption = (stdio, {input, inputFile}) => { const stdioArray = arrifyStdio(stdio); validateInputOptions(stdioArray, input, inputFile); validateInputOptionsSync(stdioArray, input);
if (inputFile !== undefined) { return readFileSync(inputFile); }
return input;};
// Handle `input`, `inputFile` and `stdin` options, before spawning, in sync modeexport const handleInputOption = options => { const stdio = normalizeStdio(options);
const input = getInputOption(stdio, options); if (input !== undefined) { options.input = input; }
options.stdio = stdio;};
const hasAlias = options => aliases.some(alias => options[alias] !== undefined);
export const normalizeStdio = options => { if (!options) {43 unmodified linesmodified:lib/stream.js+2 added-55 removed
1 import {once} from 'node:events';2-import {createReadStream, readFileSync} from 'node:fs';2 import {setTimeout} from 'node:timers/promises';4-import {isStream} from 'is-stream';3 import getStream, {getStreamAsBuffer} from 'get-stream';4 import mergeStreams from '@sindresorhus/merge-streams';5 8-export const validateInputOptions = ({input, inputFile}, {stdinIterableStream}) => {9- if (input !== undefined && inputFile !== undefined) {10- throw new TypeError('The `input` and `inputFile` options cannot be both set.');11- }12-13- if (stdinIterableStream !== undefined) {14- if (input !== undefined) {15- throw new TypeError('The `stdin` option cannot be an iterable when the `input` option is set.');16- }17-18- if (inputFile !== undefined) {19- throw new TypeError('The `stdin` option cannot be an iterable when the `inputFile` option is set.');20- }21- }22-};23-24-// `input` and `inputFile` option in sync mode25-export const handleInputSync = ({input, inputFile}, {stdinIterableStream}) => {26- if (stdinIterableStream !== undefined) {27- throw new TypeError('The `stdin` option cannot be an iterable in sync mode');28- }29-30- const inputOption = typeof inputFile === 'string' ? readFileSync(inputFile) : input;31-32- if (isStream(inputOption)) {33- throw new TypeError('The `input` option cannot be a stream in sync mode');34- }35-36- return inputOption;37-};38-39-// `input` and `inputFile` option in async mode40-export const handleInput = (spawned, {input, inputFile}, {stdinIterableStream}) => {41- if (stdinIterableStream !== undefined) {42- stdinIterableStream.pipe(spawned.stdin);43- return;44- }45-46- const inputOption = typeof inputFile === 'string' ? createReadStream(inputFile) : input;47-48- if (inputOption === undefined) {49- return;50- }51-52- if (isStream(inputOption)) {53- inputOption.pipe(spawned.stdin);54- } else {55- spawned.stdin.end(inputOption);56- }57-};58-6 // `all` interleaves `stdout` and `stderr`7 export const makeAllStream = (spawned, {all}) => {8 if (!all || (!spawned.stdout && !spawned.stderr)) {9 return;52 unmodified lines62 throw error;63 };64 65 // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)119-export const getSpawnedResult = async (spawned, {encoding, buffer, maxBuffer}, {stdinIterableStream}, processDone) => {66+export const getSpawnedResult = async (spawned, {encoding, buffer, maxBuffer}, {stdinStream}, processDone) => {67 const stdoutPromise = getStreamPromise(spawned.stdout, {encoding, buffer, maxBuffer});68 const stderrPromise = getStreamPromise(spawned.stderr, {encoding, buffer, maxBuffer});69 const allPromise = getStreamPromise(spawned.all, {encoding, buffer, maxBuffer: maxBuffer * 2});123- const processDoneOrStreamsError = Promise.race([processDone, ...throwOnStreamsError([stdinIterableStream])]);70+ const processDoneOrStreamsError = Promise.race([processDone, ...throwOnStreamsError([stdinStream])]);71 72 try {73 return await Promise.all([processDoneOrStreamsError, stdoutPromise, stderrPromise, allPromise]);74 } catch (error) {9 unmodified linesmodified:test/stream.js+30 added-2 removed
147 unmodified lines148 149 test('stdin option cannot be an iterable when "input" is used', t => {150 t.throws(() => {151 execa('stdin.js', {stdin: ['foo', 'bar'], input: 'foobar'});152- }, {message: /when the `input` option/});152+ }, {message: /`input` and `stdin` options/});153 });154 155 test('stdin option cannot be an iterable when "inputFile" is used', t => {156 t.throws(() => {157 execa('stdin.js', {stdin: ['foo', 'bar'], inputFile: 'dummy.txt'});158- }, {message: /when the `inputFile` option/});158+ }, {message: /`inputFile` and `stdin` options/});159 });160 161 test('stdin option cannot be a generic iterable string', async t => {162 await t.throwsAsync(() => execa('stdin.js', {stdin: 'foobar'}), {code: 'ERR_INVALID_SYNC_FORK_INPUT'});8 unmodified lines171 const {stdout} = await execa('stdin.js', {input: 'foobar'});172 t.is(stdout, 'foobar');173 });174 175+test('input option cannot be a String when stdin is set', t => {176+ t.throws(() => {177+ execa('stdin.js', {input: 'foobar', stdin: 'ignore'});178+ }, {message: /`input` and `stdin` options/});179+});180+181+test('input option cannot be a String when stdio is set', t => {182+ t.throws(() => {183+ execa('stdin.js', {input: 'foobar', stdio: 'ignore'});184+ }, {message: /`input` and `stdin` options/});185+});186+187 test('input option can be a Buffer', async t => {188 const {stdout} = await execa('stdin.js', {input: 'testing12'});189 t.is(stdout, 'testing12');190 });5 unmodified lines196 const {stdout} = await execa('stdin.js', {input: stream});197 t.is(stdout, 'howdy');198 });199 200+test('input option cannot be a Stream when stdin is set', t => {201+ t.throws(() => {202+ execa('stdin.js', {input: new Stream.PassThrough(), stdin: 'ignore'});203+ }, {message: /`input` and `stdin` options/});204+});205+206 test('input option can be used with $', async t => {207 const {stdout} = await $({input: 'foobar'})`stdin.js`;208 t.is(stdout, 'foobar');209 });17 unmodified lines227 message: /cannot be both set/,228 });229 });230 231+test('inputFile option cannot be set when stdin is set', t => {232+ t.throws(() => {233+ execa('stdin.js', {inputFile: '', stdin: 'ignore'});234+ }, {message: /`inputFile` and `stdin` options/});235+});236+237+test('inputFile errors should be handled', async t => {238+ await t.throwsAsync(execa('stdin.js', {inputFile: 'unknown'}), {code: 'ENOENT'});239+});240+241 test('you can write to child.stdin', async t => {242 const subprocess = execa('stdin.js');243 subprocess.stdin.end('unicorns');244 const {stdout} = await subprocess;160 unmodified linesmodified:index.js+11 added-14 removed
5 unmodified lines6 import stripFinalNewline from 'strip-final-newline';7 import {npmRunPathEnv} from 'npm-run-path';8 import onetime from 'onetime';9 import {makeError} from './lib/error.js';10-import {handleStdioOption, normalizeStdioNode} from './lib/stdio.js';10+import {handleStdioOption, handleInputOption, pipeStdioOption, normalizeStdioNode} from './lib/stdio.js';11 import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';12 import {addPipeMethods} from './lib/pipe.js';13-import {validateInputOptions, handleInput, getSpawnedResult, makeAllStream, handleInputSync} from './lib/stream.js';13+import {getSpawnedResult, makeAllStream} from './lib/stream.js';14 import {mergePromise, getSpawnedPromise} from './lib/promise.js';15 import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';16 import {logCommand, verboseDefault} from './lib/verbose.js';17 33 unmodified lines51 };52 53 options.env = getEnv(options);54 55- const stdioStreams = handleStdioOption(options);56-55 if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {56 // #11657 args.unshift('/q');58 }59 62- return {file, args, options, parsed, stdioStreams};60+ return {file, args, options};61 };62 63 const handleOutput = (options, value, error) => {64 if (typeof value !== 'string' && !Buffer.isBuffer(value)) {9 unmodified lines74 };75 76 export function execa(file, args, options) {77 const parsed = handleArguments(file, args, options);78+ const stdioStreams = handleStdioOption(parsed.options);79+ validateTimeout(parsed.options);80+81 const command = joinCommand(file, args);82 const escapedCommand = getEscapedCommand(file, args);83 logCommand(escapedCommand, parsed.options);84 84- validateTimeout(parsed.options);85- validateInputOptions(parsed.options, parsed.stdioStreams);86-85 let spawned;86 try {87 spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);88 } catch (error) {24 unmodified lines113 spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));114 spawned.cancel = spawnedCancel.bind(null, spawned, context);115 116 const handlePromise = async () => {119- const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, parsed.stdioStreams, processDone);117+ const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, stdioStreams, processDone);118 const stdout = handleOutput(parsed.options, stdoutResult);119 const stderr = handleOutput(parsed.options, stderrResult);120 const all = handleOutput(parsed.options, allResult);121 35 unmodified lines157 };158 159 const handlePromiseOnce = onetime(handlePromise);160 163- handleInput(spawned, parsed.options, parsed.stdioStreams);161+ pipeStdioOption(spawned, stdioStreams);162 163 spawned.all = makeAllStream(spawned, parsed.options);164 165 addPipeMethods(spawned);2 unmodified lines168 }169 170 export function execaSync(file, args, options) {171 const parsed = handleArguments(file, args, options);172+ handleInputOption(parsed.options);173+174 const command = joinCommand(file, args);175 const escapedCommand = getEscapedCommand(file, args);176 logCommand(escapedCommand, parsed.options);177 178- validateInputOptions(parsed.options, parsed.stdioStreams);179- const inputOption = handleInputSync(parsed.options, parsed.stdioStreams);180-178 let result;179 try {183- result = childProcess.spawnSync(parsed.file, parsed.args, {...parsed.options, input: inputOption});180+ result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);181 } catch (error) {182 throw makeError({183 error,184 stdout: '',126 unmodified lines