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
Provenance
- Commit
ea889c7- Tree
f13b6b3- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
c8a6ed7
13 files changed+466 added−76 removed
modified:docs/bash.md+26 added
494 unmodified lines495 ```496 497 [More info.](output.md#file-output)498 499+### Piping interleaved stdout and stderr to a file500+501+```sh502+# Bash503+npm run build &> output.txt504+```505+506+```js507+// zx508+import {createWriteStream} from 'node:fs';509+510+const subprocess = $`npm run build`;511+const fileStream = createWriteStream('output.txt');512+subprocess.pipe(fileStream);513+subprocess.stderr.pipe(fileStream);514+await subprocess;515+```516+517+```js518+// Execa519+const output = {file: 'output.txt'};520+await $({stdout: output, stderr: output})`npm run build`;521+```522+523+[More info.](output.md#file-output)524+525 ### Piping stdin from a file526 527 ```sh528 # Bash366 unmodified linesmodified:docs/output.md+4 added
30 unmodified lines313233343536373839404142133 unmodified linesExpand all30 unmodified lines```jsawait execa({stdout: {file: 'output.txt'}})`npm run build`;// Or:await execa({stdout: new URL('file:///path/to/output.txt')})`npm run build`;
// Redirect interleaved stdout and stderr to same fileconst output = {file: 'output.txt'};await execa({stdout: output, stderr: output})`npm run build`;```
## Terminal output
133 unmodified linesExpand allmodified:lib/io/output-async.js+10 added-10 removed
5 unmodified lines6 7 // 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 ended9 export const pipeOutputAsync = (subprocess, fileDescriptors, controller) => {10- const inputStreamsGroups = {};10+ const pipeGroups = new Map();11 12 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 lines19 subprocess,20 stream,21 direction,22 fdNumber,23- inputStreamsGroups,23+ pipeGroups,24 controller,25 });26 }27 }28 29- 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 };34 35 // When using transforms, `subprocess.stdin|stdout|stderr|stdio` is directly mutated15 unmodified lines51 const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];52 53 // Most `std*` option values involve piping `subprocess.std*` to a stream.54 // The stream is either passed by the user or created internally.55-const pipeStdioItem = ({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller}) => {55+const pipeStdioItem = ({subprocess, stream, direction, fdNumber, pipeGroups, controller}) => {56 if (stream === undefined) {57 return;58 }59 60 setStandardStreamMaxListeners(stream, controller);61 62- 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 };68 69 // 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 linesmodified:lib/io/output-sync.js+15 added-6 removed
1-import {writeFileSync} from 'node:fs';1+import {writeFileSync, appendFileSync} from 'node:fs';2 import {shouldLogOutput, logLinesSync} from '../verbose/output.js';3 import {runGeneratorsSync} from '../transform/generator.js';4 import {splitLinesSync} from '../transform/split.js';5 import {joinToString, joinToUint8Array, bufferToUint8Array} from '../utils/uint-array.js';6 unmodified lines12 return {output: Array.from({length: 3})};13 }14 15 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 };29 28-const transformOutputResultSync = ({result, fileDescriptors, fdNumber, state, isMaxBuffer, verboseInfo}, {buffer, encoding, lines, stripFinalNewline, maxBuffer}) => {30+const 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 lines61 const returnedResult = buffer[fdNumber] ? finalResult : undefined;62 63 try {64 if (state.error === undefined) {60- writeToFiles(serializedResult, stdioItems);65+ writeToFiles(serializedResult, stdioItems, outputFiles);66 }67 68 return returnedResult;69 } catch (error) {32 unmodified lines102 return {serializedResult};103 };104 105 // When the `std*` target is a file path/URL or a file descriptor101-const writeToFiles = (serializedResult, stdioItems) => {102- for (const {type, path} of stdioItems) {103- if (FILE_TYPES.has(type)) {106+const 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 lines4 Readable,5 Writable,6 Duplex,7 } from 'node:stream';8-import {cleanupCustomStreams} from '../stdio/handle-async.js';8+import {cleanupCustomStreams} from '../stdio/handle.js';9 import {makeEarlyError} from './result.js';10 import {handleResult} from './reject.js';11 12 // When the subprocess fails to spawn.48 unmodified linesadded:lib/stdio/duplicate.js+116 added
1+import {2+ SPECIAL_DUPLICATE_TYPES_SYNC,3+ SPECIAL_DUPLICATE_TYPES,4+ FORBID_DUPLICATE_TYPES,5+ TYPE_TO_MESSAGE,6+} from './type.js';7+8+// Duplicates in the same file descriptor is most likely an error.9+// However, this can be useful with generators.10+export 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'));15+16+// Check if two file descriptors are sharing the same target.17+// For example `{stdout: {file: './output.txt'}, stderr: {file: './output.txt'}}`.18+export const getDuplicateStream = ({stdioItem: {type, value, optionName}, direction, fileDescriptors, isSync}) => {19+ const otherStdioItems = getOtherStdioItems(fileDescriptors, type);20+ if (otherStdioItems.length === 0) {21+ return;22+ }23+24+ if (isSync) {25+ validateDuplicateStreamSync({26+ otherStdioItems,27+ type,28+ value,29+ optionName,30+ direction,31+ });32+ return;33+ }34+35+ if (SPECIAL_DUPLICATE_TYPES.has(type)) {36+ return getDuplicateStreamInstance({37+ otherStdioItems,38+ type,39+ value,40+ optionName,41+ direction,42+ });43+ }44+45+ if (FORBID_DUPLICATE_TYPES.has(type)) {46+ validateDuplicateTransform({47+ otherStdioItems,48+ type,49+ value,50+ optionName,51+ });52+ }53+};54+55+// Values shared by multiple file descriptors56+const getOtherStdioItems = (fileDescriptors, type) => fileDescriptors57+ .flatMap(({direction, stdioItems}) => stdioItems58+ .filter(stdioItem => stdioItem.type === type)59+ .map((stdioItem => ({...stdioItem, direction}))));60+61+// With `execaSync()`, do not allow setting a file path both in input and output62+const 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+};73+74+// 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.79+const getDuplicateStreamInstance = ({otherStdioItems, type, value, optionName, direction}) => {80+ const duplicateStdioItems = otherStdioItems.filter(stdioItem => hasSameValue(stdioItem, value));81+ if (duplicateStdioItems.length === 0) {82+ return;83+ }84+85+ const differentStdioItem = duplicateStdioItems.find(stdioItem => stdioItem.direction !== direction);86+ throwOnDuplicateStream(differentStdioItem, optionName, type);87+88+ return direction === 'output' ? duplicateStdioItems[0].stream : undefined;89+};90+91+const hasSameValue = ({type, value}, secondValue) => {92+ if (type === 'filePath') {93+ return value.path === secondValue.path;94+ }95+96+ if (type === 'fileUrl') {97+ return value.href === secondValue.href;98+ }99+100+ return value === secondValue;101+};102+103+// 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.107+const validateDuplicateTransform = ({otherStdioItems, type, value, optionName}) => {108+ const duplicateStdioItem = otherStdioItems.find(({value: {transform}}) => transform === value.transform);109+ throwOnDuplicateStream(duplicateStdioItem, optionName, type);110+};111+112+const 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
1 import {createReadStream, createWriteStream} from 'node:fs';2 import {Buffer} from 'node:buffer';3 import {Readable, Writable, Duplex} from 'node:stream';4-import {isStandardStream} from '../utils/standard-stream.js';4 import {generatorToStream} from '../transform/generator.js';5 import {handleStdio} from './handle.js';6 import {TYPE_TO_MESSAGE} from './type.js';7 6 unmodified lines14 15 // 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.17 const addProperties = {18+ fileNumber: forbiddenIfAsync,19 generator: generatorToStream,20 asyncGenerator: generatorToStream,21 nodeStream: ({value}) => ({stream: value}),22 webTransform({value: {transform, writableObjectMode, readableObjectMode}}) {26 unmodified lines49 string: forbiddenIfAsync,50 uint8Array: forbiddenIfAsync,51 },52 };53-54-// 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.58-export 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 lines39 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 linesmodified:lib/stdio/handle.js+81 added-16 removed
1-import {getStreamName} from '../utils/standard-stream.js';1+import {getStreamName, isStandardStream} from '../utils/standard-stream.js';2 import {normalizeTransforms} from '../transform/normalize.js';3 import {getFdObjectMode} from '../transform/object-mode.js';4 import {5 getStdioItemType,4 unmodified lines10 import {getStreamDirection} from './direction.js';11 import {normalizeStdioOption} from './stdio-option.js';12 import {handleNativeStream} from './native.js';13 import {handleInputOptions} from './input-option.js';14+import {filterDuplicates, getDuplicateStream} from './duplicate.js';15 16 // 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.19 export 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 };36 31-const getFileDescriptor = ({stdioOption, fdNumber, addProperties, options, isSync}) => {37+const getFileDescriptor = ({stdioOption, fdNumber, options, isSync}) => {38 const optionName = getStreamName(fdNumber);39 const {stdioItems: initialStdioItems, isStdioArray} = initializeStdioItems({40 stdioOption,41 fdNumber,10 unmodified lines52 }));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 };58 59 // 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 lines78 value,79 optionName,80 });81 77-const filterDuplicates = stdioItems => stdioItems.filter((stdioItemOne, indexOne) =>78- stdioItems.every((stdioItemTwo, indexTwo) => stdioItemOne.value !== stdioItemTwo.value79- || indexOne >= indexTwo80- || stdioItemOne.type === 'generator'81- || stdioItemOne.type === 'asyncGenerator'));82-82 const 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 lines129 130 // 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.134-const addStreamProperties = (stdioItem, addProperties, direction, options) => ({135- ...stdioItem,136- ...addProperties[direction][stdioItem.type](stdioItem, options),137-});133+const getFinalFileDescriptors = ({initialFileDescriptors, addProperties, options, isSync}) => {134+ const fileDescriptors = [];135 136+ try {137+ for (const fileDescriptor of initialFileDescriptors) {138+ fileDescriptors.push(getFinalFileDescriptor({139+ fileDescriptor,140+ fileDescriptors,141+ addProperties,142+ options,143+ isSync,144+ }));145+ }146+147+ return fileDescriptors;148+ } catch (error) {149+ cleanupCustomStreams(fileDescriptors);150+ throw error;151+ }152+};153+154+const 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+};171+172+const addStreamProperties = ({stdioItem, addProperties, direction, options, fileDescriptors, isSync}) => {173+ const duplicateStream = getDuplicateStream({174+ stdioItem,175+ direction,176+ fileDescriptors,177+ isSync,178+ });179+180+ if (duplicateStream !== undefined) {181+ return {...stdioItem, stream: duplicateStream};182+ }183+184+ return {185+ ...stdioItem,186+ ...addProperties[direction][stdioItem.type](stdioItem, options),187+ };188+};189+190+// 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.194+export 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+};203+204 // 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*`.207 const forwardStdio = stdioItems => {7 unmodified linesmodified:lib/stdio/type.js+6 added
144 unmodified lines145 // Types which modify `subprocess.std*`146 export const TRANSFORM_TYPES = new Set(['generator', 'asyncGenerator', 'duplex', 'webTransform']);147 // Types which write to a file or a file descriptor148 export 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 logic150+export const SPECIAL_DUPLICATE_TYPES_SYNC = new Set(['fileUrl', 'filePath']);151+export 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 target153+export const FORBID_DUPLICATE_TYPES = new Set(['webTransform', 'duplex']);154 155 // Convert types to human-friendly strings for error messages156 export 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 linesmodified:test/stdio/direction.js+5 added-4 removed
3 unmodified lines4 import tempfile from 'tempfile';5 import {execa, execaSync} from '../../index.js';6 import {getStdio} from '../helpers/stdio.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8+import {foobarString} from '../helpers/input.js';9 10 setFixtureDirectory();11 12 const testInputOutput = (t, stdioOption, execaMethod) => {14 unmodified lines27 test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', testInputOutput, process.stderr, execaSync);28 29 const 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 line40 test('stdio[*] default direction is output - sync', testAmbiguousDirection, execaSync);41 42 const 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 };49 50 test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 0);1 unmodified lineadded:test/stdio/duplicate.js+199 added
1+import {once} from 'node:events';2+import {createReadStream, createWriteStream} from 'node:fs';3+import {readFile, writeFile, rm} from 'node:fs/promises';4+import {Readable, Writable} from 'node:stream';5+import {pathToFileURL} from 'node:url';6+import test from 'ava';7+import tempfile from 'tempfile';8+import {execa, execaSync} from '../../index.js';9+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10+import {11+ uppercaseGenerator,12+ appendGenerator,13+ appendAsyncGenerator,14+ casedSuffix,15+} from '../helpers/generator.js';16+import {appendDuplex} from '../helpers/duplex.js';17+import {appendWebTransform} from '../helpers/web-transform.js';18+import {foobarString, foobarUint8Array, foobarUppercase} from '../helpers/input.js';19+import {fullStdio} from '../helpers/stdio.js';20+import {nestedExecaAsync, nestedExecaSync} from '../helpers/nested.js';21+import {getAbsolutePath} from '../helpers/file-path.js';22+import {noopDuplex} from '../helpers/stream.js';23+24+setFixtureDirectory();25+26+const getNativeStream = stream => stream;27+const getNonNativeStream = stream => ['pipe', stream];28+const getWebWritableStream = stream => Writable.toWeb(stream);29+30+const getDummyDuplex = () => ({transform: noopDuplex()});31+const getDummyWebTransformStream = () => new TransformStream();32+33+const getDummyPath = async () => {34+ const filePath = tempfile();35+ await writeFile(filePath, '');36+ return filePath;37+};38+39+const getDummyFilePath = async () => ({file: await getDummyPath()});40+const getDummyFileURL = async () => pathToFileURL((await getDummyPath()));41+const duplexName = 'a Duplex stream';42+const webTransformName = 'a web TransformStream';43+const filePathName = 'a file path string';44+const fileURLName = 'a file URL';45+46+const getDifferentInputs = stdioOption => ({stdio: [stdioOption, 'pipe', 'pipe', stdioOption]});47+const getDifferentOutputs = stdioOption => ({stdout: stdioOption, stderr: stdioOption});48+const getDifferentInputsOutputs = stdioOption => ({stdin: stdioOption, stdout: stdioOption});49+const differentInputsName = '`stdin` and `stdio[3]`';50+const differentOutputsName = '`stdout` and `stderr`';51+const differentInputsOutputsName = '`stdin` and `stdout`';52+53+test('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+});59+60+const testTwoPipeOutput = async (t, execaMethod) => {61+ const {stdout} = await execaMethod('noop.js', [foobarString], {stdout: ['pipe', 'pipe']});62+ t.is(stdout, foobarString);63+};64+65+test('Can use multiple "pipe" on same output file descriptor', testTwoPipeOutput, execa);66+test('Can use multiple "pipe" on same output file descriptor, sync', testTwoPipeOutput, execaSync);67+68+test('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+});73+74+test('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+});85+86+// eslint-disable-next-line max-params87+const 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+};92+93+test('Can use multiple identical generators', testTwoGenerators, true, execa, appendGenerator().transform);94+test('Can use multiple identical generators, options object', testTwoGenerators, true, execa, appendGenerator());95+test('Can use multiple identical generators, async', testTwoGenerators, true, execa, appendAsyncGenerator().transform);96+test('Can use multiple identical generators, options object, async', testTwoGenerators, true, execa, appendAsyncGenerator());97+test('Can use multiple identical generators, sync', testTwoGenerators, true, execaSync, appendGenerator().transform);98+test('Can use multiple identical generators, options object, sync', testTwoGenerators, true, execaSync, appendGenerator());99+test('Ignore duplicate identical duplexes', testTwoGenerators, false, execa, appendDuplex());100+test('Ignore duplicate identical webTransforms', testTwoGenerators, false, execa, appendWebTransform());101+test('Can use multiple generators with duplexes', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendDuplex());102+test('Can use multiple generators with webTransforms', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendWebTransform());103+test('Can use multiple duplexes with webTransforms', testTwoGenerators, true, execa, appendDuplex(), appendWebTransform());104+105+const 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+};110+111+test('Can use multiple "pipe" on different output file descriptors', testMultiplePipeOutput, execa);112+test('Can use multiple "pipe" on different output file descriptors, sync', testMultiplePipeOutput, execaSync);113+114+test('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+});118+119+test('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+});124+125+test('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+});134+135+const 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+};143+144+test('Can re-use same native Writable stream on different output file descriptors', testMultipleStreamOutput, getNativeStream);145+test('Can re-use same non-native Writable stream on different output file descriptors', testMultipleStreamOutput, getNonNativeStream);146+test('Can re-use same web Writable stream on different output file descriptors', testMultipleStreamOutput, getWebWritableStream);147+148+const testMultipleInheritOutput = async (t, execaMethod) => {149+ const {stdout} = await execaMethod('noop-both.js', [foobarString], getDifferentOutputs(1)).parent;150+ t.is(stdout, `${foobarString}\n${foobarString}`);151+};152+153+test('Can re-use same parent file descriptor on different output file descriptors', testMultipleInheritOutput, nestedExecaAsync);154+test('Can re-use same parent file descriptor on different output file descriptors, sync', testMultipleInheritOutput, nestedExecaSync);155+156+const 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+};163+164+test('Can re-use same file path on different input file descriptors', testMultipleFileInput, getAbsolutePath);165+test('Can re-use same file URL on different input file descriptors', testMultipleFileInput, pathToFileURL);166+167+const 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+};173+174+test('Can re-use same file path on different output file descriptors', testMultipleFileOutput, getAbsolutePath, execa);175+test('Can re-use same file path on different output file descriptors, sync', testMultipleFileOutput, getAbsolutePath, execaSync);176+test('Can re-use same file URL on different output file descriptors', testMultipleFileOutput, pathToFileURL, execa);177+test('Can re-use same file URL on different output file descriptors, sync', testMultipleFileOutput, pathToFileURL, execaSync);178+179+// eslint-disable-next-line max-params180+const 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+};189+190+test('Cannot use same Duplex on different input file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentInputs, differentInputsName, execa);191+test('Cannot use same Duplex on different output file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentOutputs, differentOutputsName, execa);192+test('Cannot use same Duplex on both input and output file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentInputsOutputs, differentInputsOutputsName, execa);193+test('Cannot use same TransformStream on different input file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentInputs, differentInputsName, execa);194+test('Cannot use same TransformStream on different output file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentOutputs, differentOutputsName, execa);195+test('Cannot use same TransformStream on both input and output file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentInputsOutputs, differentInputsOutputsName, execa);196+test('Cannot use same file path on both input and output file descriptors', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execa);197+test('Cannot use same file URL on both input and output file descriptors', testMultipleInvalid, getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execa);198+test('Cannot use same file path on both input and output file descriptors, sync', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync);199+test('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
1 import test from 'ava';2-import {execa, execaSync} from '../../index.js';2+import {execa} from '../../index.js';3 import {getStdio} from '../helpers/stdio.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5-import {appendGenerator, appendAsyncGenerator, casedSuffix} from '../helpers/generator.js';6-import {appendDuplex} from '../helpers/duplex.js';7-import {appendWebTransform} from '../helpers/web-transform.js';8-import {foobarString} from '../helpers/input.js';5 6 setFixtureDirectory();7 8 const testNoPipeOption = async (t, stdioOption, fdNumber) => {37 unmodified lines46 test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);47 test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);48 test('stdio[*] can be 3', testNoPipeOption, 3, 3);49 test('stdio[*] can be [3]', testNoPipeOption, [3], 3);54-55-// eslint-disable-next-line max-params56-const 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-};61-62-test('Can use multiple identical generators', testTwoGenerators, true, execa, appendGenerator().transform);63-test('Can use multiple identical generators, options object', testTwoGenerators, true, execa, appendGenerator());64-test('Can use multiple identical generators, async', testTwoGenerators, true, execa, appendAsyncGenerator().transform);65-test('Can use multiple identical generators, options object, async', testTwoGenerators, true, execa, appendAsyncGenerator());66-test('Can use multiple identical generators, sync', testTwoGenerators, true, execaSync, appendGenerator().transform);67-test('Can use multiple identical generators, options object, sync', testTwoGenerators, true, execaSync, appendGenerator());68-test('Ignore duplicate identical duplexes', testTwoGenerators, false, execa, appendDuplex());69-test('Ignore duplicate identical webTransforms', testTwoGenerators, false, execa, appendWebTransform());70-test('Can use multiple generators with duplexes', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendDuplex());71-test('Can use multiple generators with webTransforms', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendWebTransform());72-test('Can use multiple duplexes with webTransforms', testTwoGenerators, true, execa, appendDuplex(), appendWebTransform());