Fix synchronous input transforms and `inputFile` errors
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 758768f · Browse files · 5 files·+110 added−11 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+110 added−11 removed
- tests:+97 added−2 removed
- other:+13 added−9 removed
Provenance
- Commit
516a5e2- Tree
98f1595- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
758768f
5 files changed+110 added−11 removed
modified:lib/io/input-sync.js+6 added-5 removed
24 unmodified lines252627282930312930313233343435363637383940416 unmodified lines24 unmodified lines const [{type, optionName}] = allStdioItems; throw new TypeError(`Only the \`stdin\` option, not \`${optionName}\`, can be ${TYPE_TO_MESSAGE[type]} with synchronous methods.`); }
const allContents = allStdioItems.map(({contents}) => contents); const transformedContents = allContents.map(contents => applySingleInputGeneratorsSync(contents, stdioItems, options.encoding)); options.input = joinToUint8Array(transformedContents); // All input sources are merged into a single list of chunks, like asynchronous methods merge input streams, so that transforms receive a single stream of data: line splitting spans all sources and `final` runs only once. // Files are read lazily, so that a read failure is reported like any other early error const chunks = allStdioItems.flatMap(({contents}) => typeof contents === 'function' ? contents() : contents); options.input = applyInputGeneratorsSync(chunks, stdioItems, options.encoding);};
const applySingleInputGeneratorsSync = (contents, stdioItems, encoding) => {const applyInputGeneratorsSync = (chunks, stdioItems, encoding) => { // Input transforms use UTF-8 with text encodings, since those only apply to the output const newContents = runGeneratorsSync(contents, stdioItems, getInputEncoding(encoding), true); const newContents = runGeneratorsSync(chunks, stdioItems, getInputEncoding(encoding), true); validateSerializable(newContents); return joinToUint8Array(newContents);};
6 unmodified linesmodified:lib/stdio/handle-sync.js+5 added-3 removed
47 unmodified lines484950515252535354555657575859606162637 unmodified lines47 unmodified linesconst addPropertiesSync = { input: { ...addProperties, native: forbiddenNativeInputIfSync, // Files are read lazily, so that a file which cannot be read is reported like any other early error, instead of being thrown as a raw error fileUrl: ({value}) => ({contents: [bufferToUint8Array(readFileSync(value))]}), filePath: ({value: {file}}) => ({contents: [bufferToUint8Array(readFileSync(file))]}), fileUrl: ({value}) => ({contents: () => [bufferToUint8Array(readFileSync(value))]}), filePath: ({value: {file}}) => ({contents: () => [bufferToUint8Array(readFileSync(file))]}), fileNumber: forbiddenIfSync, iterable: ({value}) => ({contents: [...value]}), string: ({value}) => ({contents: [value]}), uint8Array: ({value}) => ({contents: [value]}), // `contents` is already set when reading from a file descriptor uint8Array: ({value, contents = [value]}) => ({contents}), }, output: { ...addProperties, fileUrl: ({value}) => ({path: value}),7 unmodified linesmodified:lib/stdio/native.js+2 added-1 removed
54 unmodified lines55 if (tty.isatty(targetFdNumber)) {56 throw new TypeError(`The \`${optionName}: ${serializeOptionValue(value)}\` option is invalid: it cannot be a TTY with synchronous methods.`);57 }58 59- return {type: 'uint8Array', value: bufferToUint8Array(readFileSync(targetFdNumber)), optionName};59+ // The file descriptor is read lazily, like `inputFile`, so that a read failure is reported like any other early error, instead of being thrown as a raw error60+ return {type: 'uint8Array', contents: () => [bufferToUint8Array(readFileSync(targetFdNumber))], optionName};61 };62 63 const getTargetFdNumber = (value, fdNumber) => {64 if (value === 'inherit') {43 unmodified linesmodified:test/io/input-sync.js+81 added-1 removed
1223456789106 unmodified lines17181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798import test from 'ava';import {execaSync} from '../../index.js';import {execa, execaSync} from '../../index.js';import {setFixtureDirectory} from '../helpers/fixtures-directory.js';import {getStdio} from '../helpers/stdio.js';import {noopGenerator, serializeGenerator} from '../helpers/generator.js';import {foobarObject, foobarObjectString} from '../helpers/input.js';
setFixtureDirectory();
const getFd3InputMessage = type => `not \`stdio[3]\`, can be ${type}`;6 unmodified lines};
test('Cannot use Uint8Array with stdio[*], sync', testFd3InputSync, new Uint8Array(), getFd3InputMessage('a Uint8Array'));test('Cannot use iterable with stdio[*], sync', testFd3InputSync, [[]], getFd3InputMessage('an iterable'));
/*With asynchronous methods, all `stdin` sources are merged into a single stream before being transformed, so transform state (including line splitting) spans all sources.Synchronous methods must apply the transform pipeline once over the merged sources, not once per source.*/const testMultipleSources = async (t, execaMethod) => { const {stdout} = await execaMethod('stdin.js', { stdin: [['a'], ['b\n'], noopGenerator()], }); t.is(stdout, 'ab');};
test('Multiple stdin sources are transformed as a single stream', testMultipleSources, execa);test('Multiple stdin sources are transformed as a single stream, sync', testMultipleSources, execaSync);
// The generator's `final` function must run once overall, not once per sourceconst finalCountGenerator = { * transform(value) { yield value; }, * final() { yield '[F]'; },};
const testMultipleSourcesFinal = async (t, execaMethod) => { const {stdout} = await execaMethod('stdin.js', { stdin: [['a'], ['b\n'], finalCountGenerator], }); t.is(stdout, 'ab\n[F]');};
test('Generator "final" runs once with multiple stdin sources', testMultipleSourcesFinal, execa);test('Generator "final" runs once with multiple stdin sources, sync', testMultipleSourcesFinal, execaSync);
// Without transforms, multiple sources are simply concatenated, like a single source with multiple chunksconst testMultipleSourcesNoTransform = async (t, execaMethod) => { const {stdout} = await execaMethod('stdin.js', {stdin: [['a'], ['b\n']]}); t.is(stdout, 'ab');};
test('Multiple stdin sources are concatenated without transforms', testMultipleSourcesNoTransform, execa);test('Multiple stdin sources are concatenated without transforms, sync', testMultipleSourcesNoTransform, execaSync);
// A `\r\n` sequence split across two sources must still be detected, like across two chunks of a single sourceconst testWindowsNewlineSpanningSources = async (t, execaMethod) => { const {stdout} = await execaMethod('stdin.js', { stdin: [['x\r'], ['\ny'], noopGenerator()], stripFinalNewline: false, }); t.is(stdout, 'x\r\ny\r\n');};
test('Windows newlines can span multiple stdin sources', testWindowsNewlineSpanningSources, execa);test('Windows newlines can span multiple stdin sources, sync', testWindowsNewlineSpanningSources, execaSync);
// The `input` option is one more source going through the same transforms, in the order the sources were passedconst testInputOptionWithStdinSource = async (t, execaMethod) => { const {stdout} = await execaMethod('stdin.js', { stdin: [['a'], noopGenerator()], input: 'b', }); t.is(stdout, 'ab');};
test('The input option is transformed together with stdin sources', testInputOptionWithStdinSource, execa);test('The input option is transformed together with stdin sources, sync', testInputOptionWithStdinSource, execaSync);
// Object inputs are serialized no matter how many sources they come fromconst testMultipleObjectSources = async (t, execaMethod) => { const {stdout} = await execaMethod('stdin.js', { stdin: [[foobarObject], [foobarObject], serializeGenerator(true)], }); t.is(stdout, `${foobarObjectString}\n${foobarObjectString}`);};
test('Multiple object stdin sources are serialized', testMultipleObjectSources, execa);test('Multiple object stdin sources are serialized, sync', testMultipleObjectSources, execaSync);modified:test/return/early-error.js+16 added-1 removed
1 import {arch} from 'node:os';2 import process from 'node:process';3 import {finished} from 'node:stream/promises';4 import test from 'ava';5-import {execa, execaSync, $} from '../../index.js';5+import {execa, execaSync, $, ExecaError, ExecaSyncError} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {foobarString, foobarUint8Array} from '../helpers/input.js';8 import {fullStdio} from '../helpers/stdio.js';9 import {223 unmodified lines233 test('child_process.spawn() early errors can use .stderr', testEarlyErrorStream, ({stderr}) => stderr);234 test('child_process.spawn() early errors can use .stdio[1]', testEarlyErrorStream, ({stdio}) => stdio[1]);235 test('child_process.spawn() early errors can use .stdio[3]', testEarlyErrorStream, ({stdio}) => stdio[3], fullStdio);236 test('child_process.spawn() early errors can use .all', testEarlyErrorStream, ({all}) => all, {all: true});237+238+// Reading the `inputFile` happens after the file descriptors are set up, so a missing file is reported as an early error, like with asynchronous methods239+test('inputFile which does not exist is an early error', async t => {240+ const error = await t.throwsAsync(execa('stdin.js', {inputFile: 'does_not_exist'}));241+ t.true(error instanceof ExecaError);242+ t.is(error.cause.code, 'ENOENT');243+});244+245+test('inputFile which does not exist is an early error, sync', t => {246+ const error = t.throws(() => {247+ execaSync('stdin.js', {inputFile: 'does_not_exist'});248+ });249+ t.true(error instanceof ExecaSyncError);250+ t.is(error.cause.code, 'ENOENT');251+});