Skip to content
Myr

Fix passing the same file or stream to both `stdout` and `stderr` (#1004)

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

authored by ehmicky · committed by GitHub · parent c8a6ed7 · Browse files · 13 files+466 added−76 removed
This commit

State

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

Diff stats

13 files+466 added−76 removed

  • tests:+205 added−28 removed
  • other:+261 added−48 removed

13 files+466 added−76 removed

modified:docs/bash.md+26 added
494 unmodified lines
495```496497[More info.](output.md#file-output)498499### Piping interleaved stdout and stderr to a file500501```sh502# Bash503npm run build &> output.txt504```505506```js507// zx508import {createWriteStream} from 'node:fs';509510const subprocess = $`npm run build`;511const fileStream = createWriteStream('output.txt');512subprocess.pipe(fileStream);513subprocess.stderr.pipe(fileStream);514await subprocess;515```516517```js518// Execa519const output = {file: 'output.txt'};520await $({stdout: output, stderr: output})`npm run build`;521```522523[More info.](output.md#file-output)524525### Piping stdin from a file526527```sh528# Bash
366 unmodified lines
modified:docs/output.md+4 added
modified:lib/io/output-async.js+10 added-10 removed
5 unmodified lines
67// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, after spawning, in async mode8// When multiple input streams are used, we merge them to ensure the output stream ends only once each input stream has ended9export const pipeOutputAsync = (subprocess, fileDescriptors, controller) => {10 const inputStreamsGroups = {};10 const pipeGroups = new Map();1112 for (const [fdNumber, {stdioItems, direction}] of Object.entries(fileDescriptors)) {13 for (const {stream} of stdioItems.filter(({type}) => TRANSFORM_TYPES.has(type))) {14 pipeTransform(subprocess, stream, direction, fdNumber);
4 unmodified lines
19 subprocess,20 stream,21 direction,22 fdNumber,23 inputStreamsGroups,23 pipeGroups,24 controller,25 });26 }27 }2829 for (const [fdNumber, inputStreams] of Object.entries(inputStreamsGroups)) {29 for (const [outputStream, inputStreams] of pipeGroups.entries()) {30 const inputStream = inputStreams.length === 1 ? inputStreams[0] : mergeStreams(inputStreams);31 pipeStreams(inputStream, subprocess.stdio[fdNumber]);31 pipeStreams(inputStream, outputStream);32 }33};3435// When using transforms, `subprocess.stdin|stdout|stderr|stdio` is directly mutated
15 unmodified lines
51const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];5253// Most `std*` option values involve piping `subprocess.std*` to a stream.54// The stream is either passed by the user or created internally.55const pipeStdioItem = ({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller}) => {55const pipeStdioItem = ({subprocess, stream, direction, fdNumber, pipeGroups, controller}) => {56 if (stream === undefined) {57 return;58 }5960 setStandardStreamMaxListeners(stream, controller);6162 if (direction === 'output') {63 pipeStreams(subprocess.stdio[fdNumber], stream);64 } else {65 inputStreamsGroups[fdNumber] = [...(inputStreamsGroups[fdNumber] ?? []), stream];66 }62 const [inputStream, outputStream] = direction === 'output'63 ? [stream, subprocess.stdio[fdNumber]]64 : [subprocess.stdio[fdNumber], stream];65 const outputStreams = pipeGroups.get(inputStream) ?? [];66 pipeGroups.set(inputStream, [...outputStreams, outputStream]);67};6869// Multiple subprocesses might be piping from/to `process.std*` at the same time.70// This is not necessarily an error and should not print a `maxListeners` warning.
10 unmodified lines
modified:lib/io/output-sync.js+15 added-6 removed
1import {writeFileSync} from 'node:fs';1import {writeFileSync, appendFileSync} from 'node:fs';2import {shouldLogOutput, logLinesSync} from '../verbose/output.js';3import {runGeneratorsSync} from '../transform/generator.js';4import {splitLinesSync} from '../transform/split.js';5import {joinToString, joinToUint8Array, bufferToUint8Array} from '../utils/uint-array.js';
6 unmodified lines
12 return {output: Array.from({length: 3})};13 }1415 const state = {};16 const outputFiles = new Set([]);17 const transformedOutput = output.map((result, fdNumber) =>18 transformOutputResultSync({19 result,20 fileDescriptors,21 fdNumber,22 state,23 outputFiles,24 isMaxBuffer,25 verboseInfo,26 }, options));27 return {output: transformedOutput, ...state};28};2928const transformOutputResultSync = ({result, fileDescriptors, fdNumber, state, isMaxBuffer, verboseInfo}, {buffer, encoding, lines, stripFinalNewline, maxBuffer}) => {30const transformOutputResultSync = (31 {result, fileDescriptors, fdNumber, state, outputFiles, isMaxBuffer, verboseInfo},32 {buffer, encoding, lines, stripFinalNewline, maxBuffer},33) => {34 if (result === null) {35 return;36 }37
23 unmodified lines
61 const returnedResult = buffer[fdNumber] ? finalResult : undefined;6263 try {64 if (state.error === undefined) {60 writeToFiles(serializedResult, stdioItems);65 writeToFiles(serializedResult, stdioItems, outputFiles);66 }6768 return returnedResult;69 } catch (error) {
32 unmodified lines
102 return {serializedResult};103};104105// When the `std*` target is a file path/URL or a file descriptor101const writeToFiles = (serializedResult, stdioItems) => {102 for (const {type, path} of stdioItems) {103 if (FILE_TYPES.has(type)) {106const writeToFiles = (serializedResult, stdioItems, outputFiles) => {107 for (const {path} of stdioItems.filter(({type}) => FILE_TYPES.has(type))) {108 const pathString = typeof path === 'string' ? path : path.toString();109 if (outputFiles.has(pathString)) {110 appendFileSync(path, serializedResult);111 } else {112 outputFiles.add(pathString);113 writeFileSync(path, serializedResult);114 }115 }116};
modified:lib/return/early-error.js+1 added-1 removed
3 unmodified lines
4 Readable,5 Writable,6 Duplex,7} from 'node:stream';8import {cleanupCustomStreams} from '../stdio/handle-async.js';8import {cleanupCustomStreams} from '../stdio/handle.js';9import {makeEarlyError} from './result.js';10import {handleResult} from './reject.js';1112// When the subprocess fails to spawn.
48 unmodified lines
added:lib/stdio/duplicate.js+116 added
1import {2 SPECIAL_DUPLICATE_TYPES_SYNC,3 SPECIAL_DUPLICATE_TYPES,4 FORBID_DUPLICATE_TYPES,5 TYPE_TO_MESSAGE,6} from './type.js';78// Duplicates in the same file descriptor is most likely an error.9// However, this can be useful with generators.10export const filterDuplicates = stdioItems => stdioItems.filter((stdioItemOne, indexOne) =>11 stdioItems.every((stdioItemTwo, indexTwo) => stdioItemOne.value !== stdioItemTwo.value12 || indexOne >= indexTwo13 || stdioItemOne.type === 'generator'14 || stdioItemOne.type === 'asyncGenerator'));1516// Check if two file descriptors are sharing the same target.17// For example `{stdout: {file: './output.txt'}, stderr: {file: './output.txt'}}`.18export const getDuplicateStream = ({stdioItem: {type, value, optionName}, direction, fileDescriptors, isSync}) => {19 const otherStdioItems = getOtherStdioItems(fileDescriptors, type);20 if (otherStdioItems.length === 0) {21 return;22 }2324 if (isSync) {25 validateDuplicateStreamSync({26 otherStdioItems,27 type,28 value,29 optionName,30 direction,31 });32 return;33 }3435 if (SPECIAL_DUPLICATE_TYPES.has(type)) {36 return getDuplicateStreamInstance({37 otherStdioItems,38 type,39 value,40 optionName,41 direction,42 });43 }4445 if (FORBID_DUPLICATE_TYPES.has(type)) {46 validateDuplicateTransform({47 otherStdioItems,48 type,49 value,50 optionName,51 });52 }53};5455// Values shared by multiple file descriptors56const getOtherStdioItems = (fileDescriptors, type) => fileDescriptors57 .flatMap(({direction, stdioItems}) => stdioItems58 .filter(stdioItem => stdioItem.type === type)59 .map((stdioItem => ({...stdioItem, direction}))));6061// With `execaSync()`, do not allow setting a file path both in input and output62const validateDuplicateStreamSync = ({otherStdioItems, type, value, optionName, direction}) => {63 if (SPECIAL_DUPLICATE_TYPES_SYNC.has(type)) {64 getDuplicateStreamInstance({65 otherStdioItems,66 type,67 value,68 optionName,69 direction,70 });71 }72};7374// When two file descriptors share the file or stream, we need to re-use the same underlying stream.75// Otherwise, the stream would be closed twice when piping ends.76// This is only an issue with output file descriptors.77// This is not a problem with generator functions since those create a new instance for each file descriptor.78// We also forbid input and output file descriptors sharing the same file or stream, since that does not make sense.79const getDuplicateStreamInstance = ({otherStdioItems, type, value, optionName, direction}) => {80 const duplicateStdioItems = otherStdioItems.filter(stdioItem => hasSameValue(stdioItem, value));81 if (duplicateStdioItems.length === 0) {82 return;83 }8485 const differentStdioItem = duplicateStdioItems.find(stdioItem => stdioItem.direction !== direction);86 throwOnDuplicateStream(differentStdioItem, optionName, type);8788 return direction === 'output' ? duplicateStdioItems[0].stream : undefined;89};9091const hasSameValue = ({type, value}, secondValue) => {92 if (type === 'filePath') {93 return value.path === secondValue.path;94 }9596 if (type === 'fileUrl') {97 return value.href === secondValue.href;98 }99100 return value === secondValue;101};102103// We do not allow two file descriptors to share the same Duplex or TransformStream.104// This is because those are set directly to `subprocess.std*`.105// For example, this could result in `subprocess.stdout` and `subprocess.stderr` being the same value.106// This means reading from either would get data from both stdout and stderr.107const validateDuplicateTransform = ({otherStdioItems, type, value, optionName}) => {108 const duplicateStdioItem = otherStdioItems.find(({value: {transform}}) => transform === value.transform);109 throwOnDuplicateStream(duplicateStdioItem, optionName, type);110};111112const throwOnDuplicateStream = (stdioItem, optionName, type) => {113 if (stdioItem !== undefined) {114 throw new TypeError(`The \`${stdioItem.optionName}\` and \`${optionName}\` options must not target ${TYPE_TO_MESSAGE[type]} that is the same.`);115 }116};
modified:lib/stdio/handle-async.js+1 added-15 removed
1import {createReadStream, createWriteStream} from 'node:fs';2import {Buffer} from 'node:buffer';3import {Readable, Writable, Duplex} from 'node:stream';4import {isStandardStream} from '../utils/standard-stream.js';4import {generatorToStream} from '../transform/generator.js';5import {handleStdio} from './handle.js';6import {TYPE_TO_MESSAGE} from './type.js';7
6 unmodified lines
1415// Create streams used internally for piping when using specific values for the `std*` options, in async mode.16// For example, `stdout: {file}` creates a file stream, which is piped from/to.17const addProperties = {18 fileNumber: forbiddenIfAsync,19 generator: generatorToStream,20 asyncGenerator: generatorToStream,21 nodeStream: ({value}) => ({stream: value}),22 webTransform({value: {transform, writableObjectMode, readableObjectMode}}) {
26 unmodified lines
49 string: forbiddenIfAsync,50 uint8Array: forbiddenIfAsync,51 },52};5354// The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.55// If the subprocess spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.56// We need to create those streams before subprocess spawning, in case their creation fails, e.g. when passing an invalid generator as argument.57// Like this, an exception would be thrown, which would prevent spawning a subprocess.58export const cleanupCustomStreams = fileDescriptors => {59 for (const {stdioItems} of fileDescriptors) {60 for (const {stream} of stdioItems) {61 if (stream !== undefined && !isStandardStream(stream)) {62 stream.destroy();63 }64 }65 }66};
modified:lib/stdio/handle-sync.js+1 added
38 unmodified lines
39 input: {40 ...addProperties,41 fileUrl: ({value}) => ({contents: [bufferToUint8Array(readFileSync(value))]}),42 filePath: ({value: {file}}) => ({contents: [bufferToUint8Array(readFileSync(file))]}),43 fileNumber: forbiddenIfSync,44 iterable: ({value}) => ({contents: [...value]}),45 string: ({value}) => ({contents: [value]}),46 uint8Array: ({value}) => ({contents: [value]}),47 },
10 unmodified lines
modified:lib/stdio/handle.js+81 added-16 removed
1import {getStreamName} from '../utils/standard-stream.js';1import {getStreamName, isStandardStream} from '../utils/standard-stream.js';2import {normalizeTransforms} from '../transform/normalize.js';3import {getFdObjectMode} from '../transform/object-mode.js';4import {5 getStdioItemType,
4 unmodified lines
10import {getStreamDirection} from './direction.js';11import {normalizeStdioOption} from './stdio-option.js';12import {handleNativeStream} from './native.js';13import {handleInputOptions} from './input-option.js';14import {filterDuplicates, getDuplicateStream} from './duplicate.js';1516// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode17// They are converted into an array of `fileDescriptors`.18// Each `fileDescriptor` is normalized, validated and contains all information necessary for further handling.19export const handleStdio = (addProperties, options, verboseInfo, isSync) => {20 const stdio = normalizeStdioOption(options, isSync);20 const fileDescriptors = stdio.map((stdioOption, fdNumber) => getFileDescriptor({21 const initialFileDescriptors = stdio.map((stdioOption, fdNumber) => getFileDescriptor({22 stdioOption,23 fdNumber,23 addProperties,24 options,25 isSync,26 }));27 const fileDescriptors = getFinalFileDescriptors({28 initialFileDescriptors,29 addProperties,30 options,31 isSync,32 });33 options.stdio = fileDescriptors.map(({stdioItems}) => forwardStdio(stdioItems));34 return fileDescriptors;35};3631const getFileDescriptor = ({stdioOption, fdNumber, addProperties, options, isSync}) => {37const getFileDescriptor = ({stdioOption, fdNumber, options, isSync}) => {38 const optionName = getStreamName(fdNumber);39 const {stdioItems: initialStdioItems, isStdioArray} = initializeStdioItems({40 stdioOption,41 fdNumber,
10 unmodified lines
52 }));53 const normalizedStdioItems = normalizeTransforms(stdioItems, optionName, direction, options);54 const objectMode = getFdObjectMode(normalizedStdioItems, direction);55 validateFileObjectMode(normalizedStdioItems, objectMode);50 const finalStdioItems = normalizedStdioItems.map(stdioItem => addStreamProperties(stdioItem, addProperties, direction, options));51 return {direction, objectMode, stdioItems: finalStdioItems};56 return {direction, objectMode, stdioItems: normalizedStdioItems};57};5859// We make sure passing an array with a single item behaves the same as passing that item without an array.60// This is what users would expect.
17 unmodified lines
78 value,79 optionName,80});8177const filterDuplicates = stdioItems => stdioItems.filter((stdioItemOne, indexOne) =>78 stdioItems.every((stdioItemTwo, indexTwo) => stdioItemOne.value !== stdioItemTwo.value79 || indexOne >= indexTwo80 || stdioItemOne.type === 'generator'81 || stdioItemOne.type === 'asyncGenerator'));8282const validateStdioArray = (stdioItems, isStdioArray, optionName) => {83 if (stdioItems.length === 0) {84 throw new TypeError(`The \`${optionName}\` option must not be an empty array.`);85 }
43 unmodified lines
129130// Some `stdio` values require Execa to create streams.131// For example, file paths create file read/write streams.132// Those transformations are specified in `addProperties`, which is both direction-specific and type-specific.134const addStreamProperties = (stdioItem, addProperties, direction, options) => ({135 ...stdioItem,136 ...addProperties[direction][stdioItem.type](stdioItem, options),137});133const getFinalFileDescriptors = ({initialFileDescriptors, addProperties, options, isSync}) => {134 const fileDescriptors = [];135136 try {137 for (const fileDescriptor of initialFileDescriptors) {138 fileDescriptors.push(getFinalFileDescriptor({139 fileDescriptor,140 fileDescriptors,141 addProperties,142 options,143 isSync,144 }));145 }146147 return fileDescriptors;148 } catch (error) {149 cleanupCustomStreams(fileDescriptors);150 throw error;151 }152};153154const getFinalFileDescriptor = ({155 fileDescriptor: {direction, objectMode, stdioItems},156 fileDescriptors,157 addProperties,158 options,159 isSync,160}) => {161 const finalStdioItems = stdioItems.map(stdioItem => addStreamProperties({162 stdioItem,163 addProperties,164 direction,165 options,166 fileDescriptors,167 isSync,168 }));169 return {direction, objectMode, stdioItems: finalStdioItems};170};171172const addStreamProperties = ({stdioItem, addProperties, direction, options, fileDescriptors, isSync}) => {173 const duplicateStream = getDuplicateStream({174 stdioItem,175 direction,176 fileDescriptors,177 isSync,178 });179180 if (duplicateStream !== undefined) {181 return {...stdioItem, stream: duplicateStream};182 }183184 return {185 ...stdioItem,186 ...addProperties[direction][stdioItem.type](stdioItem, options),187 };188};189190// The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.191// If the subprocess spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.192// We need to create those streams before subprocess spawning, in case their creation fails, e.g. when passing an invalid generator as argument.193// Like this, an exception would be thrown, which would prevent spawning a subprocess.194export const cleanupCustomStreams = fileDescriptors => {195 for (const {stdioItems} of fileDescriptors) {196 for (const {stream} of stdioItems) {197 if (stream !== undefined && !isStandardStream(stream)) {198 stream.destroy();199 }200 }201 }202};203204// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `subprocess.std*`.205// When the `std*: Array` option is used, we emulate some of the native values ('inherit', Node.js stream and file descriptor integer). To do so, we also need to pipe to `subprocess.std*`.206// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `subprocess.std*`.207const forwardStdio = stdioItems => {
7 unmodified lines
modified:lib/stdio/type.js+6 added
144 unmodified lines
145// Types which modify `subprocess.std*`146export const TRANSFORM_TYPES = new Set(['generator', 'asyncGenerator', 'duplex', 'webTransform']);147// Types which write to a file or a file descriptor148export const FILE_TYPES = new Set(['fileUrl', 'filePath', 'fileNumber']);149// When two file descriptors of this type share the same target, we need to do some special logic150export const SPECIAL_DUPLICATE_TYPES_SYNC = new Set(['fileUrl', 'filePath']);151export const SPECIAL_DUPLICATE_TYPES = new Set([...SPECIAL_DUPLICATE_TYPES_SYNC, 'webStream', 'nodeStream']);152// Do not allow two file descriptors of this type sharing the same target153export const FORBID_DUPLICATE_TYPES = new Set(['webTransform', 'duplex']);154155// Convert types to human-friendly strings for error messages156export const TYPE_TO_MESSAGE = {157 generator: 'a generator',158 asyncGenerator: 'an async generator',159 fileUrl: 'a file URL',160 filePath: 'a file path string',161 fileNumber: 'a file descriptor number',162 webStream: 'a web stream',163 nodeStream: 'a Node.js stream',164 webTransform: 'a web TransformStream',165 duplex: 'a Duplex stream',
6 unmodified lines
modified:test/stdio/direction.js+5 added-4 removed
3 unmodified lines
4import tempfile from 'tempfile';5import {execa, execaSync} from '../../index.js';6import {getStdio} from '../helpers/stdio.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {foobarString} from '../helpers/input.js';910setFixtureDirectory();1112const testInputOutput = (t, stdioOption, execaMethod) => {
14 unmodified lines
27test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', testInputOutput, process.stderr, execaSync);2829const testAmbiguousDirection = async (t, execaMethod) => {30 const [filePathOne, filePathTwo] = [tempfile(), tempfile()];30 await execaMethod('noop-fd.js', ['3', 'foobar'], getStdio(3, [{file: filePathOne}, {file: filePathTwo}]));31 await execaMethod('noop-fd.js', ['3', foobarString], getStdio(3, [{file: filePathOne}, {file: filePathTwo}]));32 t.deepEqual(33 await Promise.all([readFile(filePathOne, 'utf8'), readFile(filePathTwo, 'utf8')]),33 ['foobar', 'foobar'],34 [foobarString, foobarString],35 );36 await Promise.all([rm(filePathOne), rm(filePathTwo)]);37};38
1 unmodified line
40test('stdio[*] default direction is output - sync', testAmbiguousDirection, execaSync);4142const testAmbiguousMultiple = async (t, fdNumber) => {43 const filePath = tempfile();43 await writeFile(filePath, 'foobar');44 await writeFile(filePath, foobarString);45 const {stdout} = await execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [{file: filePath}, ['foo', 'bar']]));45 t.is(stdout, 'foobarfoobar');46 t.is(stdout, `${foobarString}${foobarString}`);47 await rm(filePath);48};4950test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 0);
1 unmodified line
added:test/stdio/duplicate.js+199 added
1import {once} from 'node:events';2import {createReadStream, createWriteStream} from 'node:fs';3import {readFile, writeFile, rm} from 'node:fs/promises';4import {Readable, Writable} from 'node:stream';5import {pathToFileURL} from 'node:url';6import test from 'ava';7import tempfile from 'tempfile';8import {execa, execaSync} from '../../index.js';9import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10import {11 uppercaseGenerator,12 appendGenerator,13 appendAsyncGenerator,14 casedSuffix,15} from '../helpers/generator.js';16import {appendDuplex} from '../helpers/duplex.js';17import {appendWebTransform} from '../helpers/web-transform.js';18import {foobarString, foobarUint8Array, foobarUppercase} from '../helpers/input.js';19import {fullStdio} from '../helpers/stdio.js';20import {nestedExecaAsync, nestedExecaSync} from '../helpers/nested.js';21import {getAbsolutePath} from '../helpers/file-path.js';22import {noopDuplex} from '../helpers/stream.js';2324setFixtureDirectory();2526const getNativeStream = stream => stream;27const getNonNativeStream = stream => ['pipe', stream];28const getWebWritableStream = stream => Writable.toWeb(stream);2930const getDummyDuplex = () => ({transform: noopDuplex()});31const getDummyWebTransformStream = () => new TransformStream();3233const getDummyPath = async () => {34 const filePath = tempfile();35 await writeFile(filePath, '');36 return filePath;37};3839const getDummyFilePath = async () => ({file: await getDummyPath()});40const getDummyFileURL = async () => pathToFileURL((await getDummyPath()));41const duplexName = 'a Duplex stream';42const webTransformName = 'a web TransformStream';43const filePathName = 'a file path string';44const fileURLName = 'a file URL';4546const getDifferentInputs = stdioOption => ({stdio: [stdioOption, 'pipe', 'pipe', stdioOption]});47const getDifferentOutputs = stdioOption => ({stdout: stdioOption, stderr: stdioOption});48const getDifferentInputsOutputs = stdioOption => ({stdin: stdioOption, stdout: stdioOption});49const differentInputsName = '`stdin` and `stdio[3]`';50const differentOutputsName = '`stdout` and `stderr`';51const differentInputsOutputsName = '`stdin` and `stdout`';5253test('Can use multiple "pipe" on same input file descriptor', async t => {54 const subprocess = execa('stdin.js', {stdin: ['pipe', 'pipe']});55 subprocess.stdin.end(foobarString);56 const {stdout} = await subprocess;57 t.is(stdout, foobarString);58});5960const testTwoPipeOutput = async (t, execaMethod) => {61 const {stdout} = await execaMethod('noop.js', [foobarString], {stdout: ['pipe', 'pipe']});62 t.is(stdout, foobarString);63};6465test('Can use multiple "pipe" on same output file descriptor', testTwoPipeOutput, execa);66test('Can use multiple "pipe" on same output file descriptor, sync', testTwoPipeOutput, execaSync);6768test('Can repeat same stream on same input file descriptor', async t => {69 const stream = Readable.from([foobarString]);70 const {stdout} = await execa('stdin.js', {stdin: ['pipe', stream, stream]});71 t.is(stdout, foobarString);72});7374test('Can repeat same stream on same output file descriptor', async t => {75 let stdout = '';76 const stream = new Writable({77 write(chunk, encoding, done) {78 stdout += chunk.toString();79 done();80 },81 });82 await execa('noop-fd.js', ['1', foobarString], {stdout: ['pipe', stream, stream]});83 t.is(stdout, foobarString);84});8586// eslint-disable-next-line max-params87const testTwoGenerators = async (t, producesTwo, execaMethod, firstGenerator, secondGenerator = firstGenerator) => {88 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: [firstGenerator, secondGenerator]});89 const expectedSuffix = producesTwo ? `${casedSuffix}${casedSuffix}` : casedSuffix;90 t.is(stdout, `${foobarString}${expectedSuffix}`);91};9293test('Can use multiple identical generators', testTwoGenerators, true, execa, appendGenerator().transform);94test('Can use multiple identical generators, options object', testTwoGenerators, true, execa, appendGenerator());95test('Can use multiple identical generators, async', testTwoGenerators, true, execa, appendAsyncGenerator().transform);96test('Can use multiple identical generators, options object, async', testTwoGenerators, true, execa, appendAsyncGenerator());97test('Can use multiple identical generators, sync', testTwoGenerators, true, execaSync, appendGenerator().transform);98test('Can use multiple identical generators, options object, sync', testTwoGenerators, true, execaSync, appendGenerator());99test('Ignore duplicate identical duplexes', testTwoGenerators, false, execa, appendDuplex());100test('Ignore duplicate identical webTransforms', testTwoGenerators, false, execa, appendWebTransform());101test('Can use multiple generators with duplexes', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendDuplex());102test('Can use multiple generators with webTransforms', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendWebTransform());103test('Can use multiple duplexes with webTransforms', testTwoGenerators, true, execa, appendDuplex(), appendWebTransform());104105const testMultiplePipeOutput = async (t, execaMethod) => {106 const {stdout, stderr} = await execaMethod('noop-both.js', [foobarString], fullStdio);107 t.is(stdout, foobarString);108 t.is(stderr, foobarString);109};110111test('Can use multiple "pipe" on different output file descriptors', testMultiplePipeOutput, execa);112test('Can use multiple "pipe" on different output file descriptors, sync', testMultiplePipeOutput, execaSync);113114test('Can re-use same generator on different input file descriptors', async t => {115 const {stdout} = await execa('stdin-fd-both.js', ['3'], getDifferentInputs([foobarUint8Array, uppercaseGenerator(false, false, true)]));116 t.is(stdout, `${foobarUppercase}${foobarUppercase}`);117});118119test('Can re-use same generator on different output file descriptors', async t => {120 const {stdout, stderr} = await execa('noop-both.js', [foobarString], getDifferentOutputs(uppercaseGenerator(false, false, true)));121 t.is(stdout, foobarUppercase);122 t.is(stderr, foobarUppercase);123});124125test('Can re-use same non-native Readable stream on different input file descriptors', async t => {126 const filePath = tempfile();127 await writeFile(filePath, foobarString);128 const stream = createReadStream(filePath);129 await once(stream, 'open');130 const {stdout} = await execa('stdin-fd-both.js', ['3'], getDifferentInputs([new Uint8Array(0), stream]));131 t.is(stdout, `${foobarString}${foobarString}`);132 await rm(filePath);133});134135const testMultipleStreamOutput = async (t, getStreamOption) => {136 const filePath = tempfile();137 const stream = createWriteStream(filePath);138 await once(stream, 'open');139 await execa('noop-both.js', [foobarString], getDifferentOutputs(getStreamOption(stream)));140 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);141 await rm(filePath);142};143144test('Can re-use same native Writable stream on different output file descriptors', testMultipleStreamOutput, getNativeStream);145test('Can re-use same non-native Writable stream on different output file descriptors', testMultipleStreamOutput, getNonNativeStream);146test('Can re-use same web Writable stream on different output file descriptors', testMultipleStreamOutput, getWebWritableStream);147148const testMultipleInheritOutput = async (t, execaMethod) => {149 const {stdout} = await execaMethod('noop-both.js', [foobarString], getDifferentOutputs(1)).parent;150 t.is(stdout, `${foobarString}\n${foobarString}`);151};152153test('Can re-use same parent file descriptor on different output file descriptors', testMultipleInheritOutput, nestedExecaAsync);154test('Can re-use same parent file descriptor on different output file descriptors, sync', testMultipleInheritOutput, nestedExecaSync);155156const testMultipleFileInput = async (t, mapFile) => {157 const filePath = tempfile();158 await writeFile(filePath, foobarString);159 const {stdout} = await execa('stdin-fd-both.js', ['3'], getDifferentInputs([new Uint8Array(0), mapFile(filePath)]));160 t.is(stdout, `${foobarString}${foobarString}`);161 await rm(filePath);162};163164test('Can re-use same file path on different input file descriptors', testMultipleFileInput, getAbsolutePath);165test('Can re-use same file URL on different input file descriptors', testMultipleFileInput, pathToFileURL);166167const testMultipleFileOutput = async (t, mapFile, execaMethod) => {168 const filePath = tempfile();169 await execaMethod('noop-both.js', [foobarString], getDifferentOutputs(mapFile(filePath)));170 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);171 await rm(filePath);172};173174test('Can re-use same file path on different output file descriptors', testMultipleFileOutput, getAbsolutePath, execa);175test('Can re-use same file path on different output file descriptors, sync', testMultipleFileOutput, getAbsolutePath, execaSync);176test('Can re-use same file URL on different output file descriptors', testMultipleFileOutput, pathToFileURL, execa);177test('Can re-use same file URL on different output file descriptors, sync', testMultipleFileOutput, pathToFileURL, execaSync);178179// eslint-disable-next-line max-params180const testMultipleInvalid = async (t, getDummyStream, typeName, getStdio, fdName, execaMethod) => {181 const stdioOption = await getDummyStream();182 t.throws(() => {183 execaMethod('empty.js', getStdio(stdioOption));184 }, {message: `The ${fdName} options must not target ${typeName} that is the same.`});185 if (stdioOption.transform !== undefined) {186 t.true(stdioOption.transform.destroyed);187 }188};189190test('Cannot use same Duplex on different input file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentInputs, differentInputsName, execa);191test('Cannot use same Duplex on different output file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentOutputs, differentOutputsName, execa);192test('Cannot use same Duplex on both input and output file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentInputsOutputs, differentInputsOutputsName, execa);193test('Cannot use same TransformStream on different input file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentInputs, differentInputsName, execa);194test('Cannot use same TransformStream on different output file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentOutputs, differentOutputsName, execa);195test('Cannot use same TransformStream on both input and output file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentInputsOutputs, differentInputsOutputsName, execa);196test('Cannot use same file path on both input and output file descriptors', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execa);197test('Cannot use same file URL on both input and output file descriptors', testMultipleInvalid, getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execa);198test('Cannot use same file path on both input and output file descriptors, sync', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync);199test('Cannot use same file URL on both input and output file descriptors, sync', testMultipleInvalid, getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync);
modified:test/stdio/handle-options.js+1 added-24 removed
1import test from 'ava';2import {execa, execaSync} from '../../index.js';2import {execa} from '../../index.js';3import {getStdio} from '../helpers/stdio.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {appendGenerator, appendAsyncGenerator, casedSuffix} from '../helpers/generator.js';6import {appendDuplex} from '../helpers/duplex.js';7import {appendWebTransform} from '../helpers/web-transform.js';8import {foobarString} from '../helpers/input.js';56setFixtureDirectory();78const testNoPipeOption = async (t, stdioOption, fdNumber) => {
37 unmodified lines
46test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);47test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);48test('stdio[*] can be 3', testNoPipeOption, 3, 3);49test('stdio[*] can be [3]', testNoPipeOption, [3], 3);5455// eslint-disable-next-line max-params56const testTwoGenerators = async (t, producesTwo, execaMethod, firstGenerator, secondGenerator = firstGenerator) => {57 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: [firstGenerator, secondGenerator]});58 const expectedSuffix = producesTwo ? `${casedSuffix}${casedSuffix}` : casedSuffix;59 t.is(stdout, `${foobarString}${expectedSuffix}`);60};6162test('Can use multiple identical generators', testTwoGenerators, true, execa, appendGenerator().transform);63test('Can use multiple identical generators, options object', testTwoGenerators, true, execa, appendGenerator());64test('Can use multiple identical generators, async', testTwoGenerators, true, execa, appendAsyncGenerator().transform);65test('Can use multiple identical generators, options object, async', testTwoGenerators, true, execa, appendAsyncGenerator());66test('Can use multiple identical generators, sync', testTwoGenerators, true, execaSync, appendGenerator().transform);67test('Can use multiple identical generators, options object, sync', testTwoGenerators, true, execaSync, appendGenerator());68test('Ignore duplicate identical duplexes', testTwoGenerators, false, execa, appendDuplex());69test('Ignore duplicate identical webTransforms', testTwoGenerators, false, execa, appendWebTransform());70test('Can use multiple generators with duplexes', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendDuplex());71test('Can use multiple generators with webTransforms', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendWebTransform());72test('Can use multiple duplexes with webTransforms', testTwoGenerators, true, execa, appendDuplex(), appendWebTransform());