Skip to content
Myr

Fix duplicated or conflicting file descriptor targets

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 c6bd387 · Browse files · 7 files+232 added−39 removed
This commit

State

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

Diff stats

7 files+232 added−39 removed

  • tests:+163 added−1 removed
  • other:+69 added−38 removed

7 files+232 added−39 removed

modified:docs/output.md+2 added
43 unmodified lines
44// Append instead of overwriting45await execa({stdout: {file: 'output.txt', append: true}})`npm run build`;46```4748When several file descriptors target the same file, the first one decides whether it is appended to.4950## Terminal output5152The parent process' output can be re-used in the subprocess by passing `'inherit'`. This is especially useful to print to the terminal in command line applications.53
154 unmodified lines
modified:lib/io/output-sync.js+19 added-4 removed
modified:lib/stdio/duplicate.js+26 added-16 removed
1import {resolve} from 'node:path';2import {fileURLToPath} from 'node:url';3import {4 SPECIAL_DUPLICATE_TYPES_SYNC,5 SPECIAL_DUPLICATE_TYPES,6 FORBID_DUPLICATE_TYPES,7 TYPE_TO_MESSAGE,8} from './type.js';910// `{file: './output.txt'}` and a `file:` URL are two ways to target the same file, so both must be compared together11const isFileType = type => SPECIAL_DUPLICATE_TYPES_SYNC.has(type);1213// The file that a `filePath` or `fileUrl` stdio item targets, as an absolute path14export const getFileTarget = ({type, value}) => type === 'filePath'15 ? resolve(value.file)16 : fileURLToPath(value);1718// Duplicates in the same file descriptor is most likely an error.19// However, this can be useful with generators.20export const filterDuplicates = stdioItems => stdioItems.filter((stdioItemOne, indexOne) =>21 stdioItems.every((stdioItemTwo, indexTwo) => !hasSameValueAndDirection(stdioItemOne, stdioItemTwo)
5 unmodified lines
27 && stdioItemOne.direction === stdioItemTwo.direction;2829// Check if two file descriptors are sharing the same target.30// For example `{stdout: {file: './output.txt'}, stderr: {file: './output.txt'}}`.31// The same applies to two items of a single file descriptor, e.g. `{stdout: [{file: './output.txt'}, {file: './output.txt'}]}`.32export const getDuplicateStream = ({stdioItem: {type, value, optionName}, direction, fileDescriptors, isSync}) => {33 const otherStdioItems = getOtherStdioItems(fileDescriptors, type);34 if (otherStdioItems.length === 0) {35 return;
29 unmodified lines
65 });66 }67};6858// Values shared by multiple file descriptors69// Values shared by multiple file descriptors, including the other items of the file descriptor currently being built70const getOtherStdioItems = (fileDescriptors, type) => fileDescriptors71 .flatMap(({direction, stdioItems}) => stdioItems61 .filter(stdioItem => stdioItem.type === type)62 .map((stdioItem => ({...stdioItem, direction}))));72 .map(stdioItem => ({...stdioItem, direction})),73 )74 .filter(stdioItem => isSameDuplicateType(stdioItem.type, type));7576// A `filePath` and a `fileUrl` are compared together, since they can target the same file77const isSameDuplicateType = (otherType, type) => otherType === type || (isFileType(otherType) && isFileType(type));7879// With `execaSync()`, do not allow setting a file path both in input and output80const validateDuplicateStreamSync = ({otherStdioItems, type, value, optionName, direction}) => {81 if (SPECIAL_DUPLICATE_TYPES_SYNC.has(type)) {82 getDuplicateStreamInstance({
11 unmodified lines
94// This is only an issue with output file descriptors.95// This is not a problem with generator functions since those create a new instance for each file descriptor.96// We also forbid input and output file descriptors sharing the same file or stream, since that does not make sense.97const getDuplicateStreamInstance = ({otherStdioItems, type, value, optionName, direction}) => {83 const duplicateStdioItems = otherStdioItems.filter(stdioItem => hasSameValue(stdioItem, value));98 const duplicateStdioItems = otherStdioItems.filter(stdioItem => hasSameValue(stdioItem, type, value));99 if (duplicateStdioItems.length === 0) {100 return;101 }102103 const differentStdioItem = duplicateStdioItems.find(stdioItem => stdioItem.direction !== direction);104 throwOnDuplicateStream(differentStdioItem, optionName, type);105106 // Output streams must be re-used so they are not closed twice.107 // Web streams must be re-used in the input direction too, since they cannot be converted twice: reading one locks it.91 return direction === 'output' ? duplicateStdioItems[0].stream : undefined;108 return direction === 'output' || type === 'webStream' ? duplicateStdioItems[0].stream : undefined;109};11094const hasSameValue = ({type, value}, secondValue) => {95 if (type === 'filePath') {96 return value.file === secondValue.file;97 }111// `type` and `value` are the current item's, `otherStdioItem` is the other one112const hasSameValue = (otherStdioItem, type, value) => isFileType(otherStdioItem.type)113 ? getFileTarget(otherStdioItem) === getFileTarget({type, value})114 : otherStdioItem.value === value;11599 if (type === 'fileUrl') {100 return value.href === secondValue.href;101 }102103 return value === secondValue;104};105116// We do not allow two file descriptors to share the same Duplex or TransformStream.117// This is because those are set directly to `subprocess.std*`.118// For example, this could result in `subprocess.stdout` and `subprocess.stderr` being the same value.119// This means reading from either would get data from both stdout and stderr.
10 unmodified lines
modified:lib/stdio/handle.js+22 added-18 removed
173 unmodified lines
174 const fileDescriptors = [];175176 try {177 for (const fileDescriptor of initialFileDescriptors) {178 fileDescriptors.push(getFinalFileDescriptor({178 addFinalFileDescriptor({179 fileDescriptor,180 fileDescriptors,181 addProperties,182 options,183 isSync,184 }));184 });185 }186187 return fileDescriptors;188 } catch (error) {
1 unmodified line
190 throw error;191 }192};193194const getFinalFileDescriptor = ({195 fileDescriptor: {direction, objectMode, stdioItems},196 fileDescriptors,197 addProperties,198 options,199 isSync,200}) => {201 const finalStdioItems = stdioItems.map(stdioItem => addStreamProperties({202 stdioItem,203 addProperties,204 direction,205 options,206 fileDescriptors,207 isSync,208 }));209 return {direction, objectMode, stdioItems: finalStdioItems};194/*195The file descriptor is added to `fileDescriptors` before its items are, for two reasons:196 - its items are added one at a time, so that each one knows about the previous ones, to detect duplicates within the same file descriptor197 - if an item throws, the streams created by the previous ones are cleaned up too198*/199const addFinalFileDescriptor = ({fileDescriptor, fileDescriptors, addProperties, options, isSync}) => {200 const {direction, objectMode, stdioItems} = fileDescriptor;201 const finalFileDescriptor = {direction, objectMode, stdioItems: []};202 fileDescriptors.push(finalFileDescriptor);203204 for (const stdioItem of stdioItems) {205 finalFileDescriptor.stdioItems.push(addStreamProperties({206 stdioItem,207 addProperties,208 direction,209 options,210 fileDescriptors,211 isSync,212 }));213 }214};215216const addStreamProperties = ({stdioItem, addProperties, direction, options, fileDescriptors, isSync}) => {217 const duplicateStream = getDuplicateStream({
41 unmodified lines
modified:test/stdio/duplicate.js+139 added-1 removed
1import {once} from 'node:events';2import {createReadStream, createWriteStream} from 'node:fs';3import {readFile, writeFile, rm} from 'node:fs/promises';3import {mkdir, readFile, writeFile, rm} from 'node:fs/promises';4import {join} from 'node:path';5import {Readable, Writable} from 'node:stream';6import {pathToFileURL} from 'node:url';7import test from 'ava';8import tempfile from 'tempfile';
167 unmodified lines
176test('Can re-use same file path on different output file descriptors, sync', testMultipleFileOutput, getAbsolutePath, execaSync);177test('Can re-use same file URL on different output file descriptors', testMultipleFileOutput, pathToFileURL, execa);178test('Can re-use same file URL on different output file descriptors, sync', testMultipleFileOutput, pathToFileURL, execaSync);179180// One of the two `append` flags would be silently ignored otherwise181const testAppendConflict = (t, execaMethod, stdoutAppend, stderrAppend) => {182 const filePath = tempfile();183 t.throws(() => {184 execaMethod('empty.js', {185 stdout: {file: filePath, append: stdoutAppend},186 stderr: {file: filePath, append: stderrAppend},187 });188 }, {message: `The ${differentOutputsName} options must not target ${filePathName} that is the same with different \`append\` values.`});189};190191test('Cannot use different `append` values on the same output file path', testAppendConflict, execa, undefined, true);192test('Cannot use different `append` values on the same output file path, reversed', testAppendConflict, execa, true, undefined);193test('Cannot use different `append` values on the same output file path, sync', testAppendConflict, execaSync, undefined, true);194test('Cannot use different `append` values on the same output file path, reversed, sync', testAppendConflict, execaSync, true, undefined);195196// Two items of a single file descriptor must be checked too, not only two different file descriptors197const sameFdName = '`stdout` and `stdout`';198199const testAppendConflictSameFd = (t, execaMethod, appendOne, appendTwo) => {200 const filePath = tempfile();201 t.throws(() => {202 execaMethod('empty.js', {stdout: [{file: filePath, append: appendOne}, {file: filePath, append: appendTwo}]});203 }, {message: `The ${sameFdName} options must not target ${filePathName} that is the same with different \`append\` values.`});204};205206test('Cannot use different `append` values on the same output file path in the same file descriptor', testAppendConflictSameFd, execa, undefined, true);207test('Cannot use different `append` values on the same output file path in the same file descriptor, reversed', testAppendConflictSameFd, execa, true, undefined);208test('Cannot use different `append` values on the same output file path in the same file descriptor, sync', testAppendConflictSameFd, execaSync, undefined, true);209test('Cannot use different `append` values on the same output file path in the same file descriptor, reversed, sync', testAppendConflictSameFd, execaSync, true, undefined);210211const testSameAppend = async (t, execaMethod) => {212 const filePath = tempfile();213 await writeFile(filePath, 'base\n');214 await execaMethod('noop-both.js', [foobarString], {stdout: {file: filePath, append: true}, stderr: {file: filePath, append: true}});215 t.is(await readFile(filePath, 'utf8'), `base\n${foobarString}\n${foobarString}\n`);216 await rm(filePath);217};218219test('Can use the same `append: true` value on the same output file path', testSameAppend, execa);220test('Can use the same `append: true` value on the same output file path, sync', testSameAppend, execaSync);221222const testFalsyAppend = async (t, execaMethod) => {223 const filePath = tempfile();224 await execaMethod('noop-both.js', [foobarString], {stdout: {file: filePath}, stderr: {file: filePath, append: false}});225 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);226 await rm(filePath);227};228229test('Falsy `append` values are the same on the same output file path', testFalsyAppend, execa);230test('Falsy `append` values are the same on the same output file path, sync', testFalsyAppend, execaSync);231232const testMultipleFileInputOutput = async (t, mapFile, execaMethod) => {233 const inputFilePath = tempfile();234 const outputFilePath = tempfile();235 await writeFile(inputFilePath, foobarString);
27 unmodified lines
263test('Cannot use same file path on both input and output file descriptors', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execa);264test('Cannot use same file URL on both input and output file descriptors', testMultipleInvalid, getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execa);265test('Cannot use same file path on both input and output file descriptors, sync', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync);266test('Cannot use same file URL on both input and output file descriptors, sync', testMultipleInvalid, getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync);267268// Piping a Duplex or a web TransformStream into itself would feed it its own output forever.269// Each item uses a distinct wrapper object, around the same stream, so that `filterDuplicates()` does not merge them.270const testSameStreamSameFd = (t, getStream, typeName) => {271 const stream = getStream();272 t.throws(() => {273 execa('empty.js', {stdout: [{transform: stream}, {transform: stream}]});274 }, {message: `The ${sameFdName} options must not target ${typeName} that is the same.`});275};276277test('Cannot use same Duplex twice on the same output file descriptor', testSameStreamSameFd, noopDuplex, duplexName);278test('Cannot use same TransformStream twice on the same output file descriptor', testSameStreamSameFd, () => new TransformStream(), webTransformName);279280// The streams created for the earlier items must be destroyed when a later one is rejected, otherwise they are leaked281test('Earlier streams are destroyed when a later item of the same file descriptor is rejected', t => {282 const stream = noopDuplex();283 t.throws(() => {284 execa('empty.js', {stdout: [{transform: stream}, {transform: stream}]});285 }, {message: `The ${sameFdName} options must not target ${duplexName} that is the same.`});286 t.true(stream.destroyed);287});288289// `{file: './output.txt'}` and a `file:` URL are two ways to target the same file290const testFilePathAndUrl = async (t, execaMethod) => {291 const filePath = tempfile();292 await execaMethod('noop-both.js', [foobarString], {stdout: {file: filePath}, stderr: pathToFileURL(filePath)});293 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);294 await rm(filePath);295};296297const testFileUrlAndPath = async (t, execaMethod) => {298 const filePath = tempfile();299 await execaMethod('noop-both.js', [foobarString], {stdout: pathToFileURL(filePath), stderr: {file: filePath}});300 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);301 await rm(filePath);302};303304test('Can use a file path and a file URL on different output file descriptors', testFilePathAndUrl, execa);305test('Can use a file URL and a file path on different output file descriptors', testFileUrlAndPath, execa);306test('Can use a file path and a file URL on different output file descriptors, sync', testFilePathAndUrl, execaSync);307test('Can use a file URL and a file path on different output file descriptors, sync', testFileUrlAndPath, execaSync);308309// A single file descriptor can target the same file twice. Its output is a single stream, so it must only be written once.310const testSameFileSameFd = async (t, execaMethod) => {311 const filePath = tempfile();312 await execaMethod('noop.js', [foobarString], {stdout: [{file: filePath}, {file: filePath}]});313 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n`);314 await rm(filePath);315};316317test('Can use the same file path twice on the same output file descriptor', testSameFileSameFd, execa);318test('Can use the same file path twice on the same output file descriptor, sync', testSameFileSameFd, execaSync);319320// A file path is resolved before being compared, so equivalent spellings of the same file are detected321const testFilePathNormalized = async (t, execaMethod) => {322 const directory = tempfile();323 await mkdir(directory);324 await mkdir(join(directory, 'subdirectory'));325 const filePath = join(directory, 'output.txt');326 // `join()` would normalize this away, but a raw string keeps the `..` segment327 const equivalentFilePath = `${directory}/subdirectory/../output.txt`;328329 await execaMethod('noop-both.js', [foobarString], {stdout: {file: filePath}, stderr: {file: equivalentFilePath}});330 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);331 await rm(directory, {recursive: true});332};333334test('Can use equivalent file paths on different output file descriptors', testFilePathNormalized, execa);335test('Can use equivalent file paths on different output file descriptors, sync', testFilePathNormalized, execaSync);336337const testFilePathAndUrlNormalized = async (t, execaMethod) => {338 const directory = tempfile();339 await mkdir(directory);340 await mkdir(join(directory, 'subdirectory'));341 const filePath = join(directory, 'output.txt');342 // `join()` would normalize this away, but a raw string keeps the `..` segment343 const equivalentFilePath = `${directory}/subdirectory/../output.txt`;344345 await execaMethod('noop-both.js', [foobarString], {stdout: {file: filePath}, stderr: pathToFileURL(equivalentFilePath)});346 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);347 await rm(directory, {recursive: true});348};349350test('Can use an equivalent file URL on different output file descriptors', testFilePathAndUrlNormalized, execa);351test('Can use an equivalent file URL on a different output file descriptor, sync', testFilePathAndUrlNormalized, execaSync);
modified:test/stdio/native-fd.js+13 added
72 unmodified lines
7374test('stdout cannot use 4+ and another value, sync', testOverflowStreamArraySync, 1);75test('stderr cannot use 4+ and another value, sync', testOverflowStreamArraySync, 2);76test('stdio[*] cannot use 4+ and another value, sync', testOverflowStreamArraySync, 3);7778// `1` and 'inherit' are two spellings of the same target, which only becomes apparent once native values are normalized.79// The output must be written to the inherited file descriptor only once, which the nested parent captures.80// The nested parent's `stdout` has its final newline stripped by the outer `execa()` call.81const testSameTargetOutput = async (t, stdioOption, isSync) => {82 const {stdout} = await nestedSubprocess('noop.js', [foobarString], {stdout: stdioOption, isSync});83 t.is(stdout, foobarString);84};8586test('stdout output is not duplicated with [1, "inherit"]', testSameTargetOutput, [1, 'inherit'], false);87test('stdout output is not duplicated with ["inherit", 1]', testSameTargetOutput, ['inherit', 1], false);88test('stdout output is not duplicated with [1, "inherit"], sync', testSameTargetOutput, [1, 'inherit'], true);89test('stdout output is not duplicated with ["inherit", 1], sync', testSameTargetOutput, ['inherit', 1], true);
modified:test/stdio/web-stream.js+11 added
94 unmodified lines
95 });96 await t.throwsAsync(execa('stdin.js', {stdin: readableStream, timeout: 1}), {message: /timed out/});97 await promise;98});99100// A web stream can only be used once, but like Node.js streams, the same instance101// passed to multiple file descriptors should send its data to each of them.102const testSharedReadableStream = async (t, fixtureArguments, stdio) => {103 const readableStream = Readable.toWeb(Readable.from('foobar'));104 const {stdout} = await execa('stdin-fd.js', fixtureArguments, {stdio: stdio.map(value => value === 'shared' ? readableStream : value)});105 t.is(stdout, 'foobar');106};107108test('stdin can share a ReadableStream with stdio[*]', testSharedReadableStream, ['0'], ['shared', 'pipe', 'pipe', 'shared']);109test('stdio[*] can share a ReadableStream with another stdio[*]', testSharedReadableStream, ['3'], ['pipe', 'pipe', 'pipe', 'shared', 'shared']);