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
Provenance
- Commit
587045a- Tree
65e6d9f- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
c6bd387
7 files changed+232 added−39 removed
modified:docs/output.md+2 added
43 unmodified lines44 // Append instead of overwriting45 await execa({stdout: {file: 'output.txt', append: true}})`npm run build`;46 ```47 48+When several file descriptors target the same file, the first one decides whether it is appended to.49+50 ## Terminal output51 52 The 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 linesmodified:lib/io/output-sync.js+19 added-4 removed
2 unmodified lines34567891011111 unmodified linesExpand all1231241251261261271281271281291301311321331341351361371381391401411421431441311451461471481491502 unmodified linesimport {runGeneratorsSync} from '../transform/generator.js';import {splitLinesSync} from '../transform/split.js';import {joinToString, joinToUint8Array, bufferToUint8Array} from '../utils/uint-array.js';import {FILE_TYPES} from '../stdio/type.js';import {getFileTarget} from '../stdio/duplicate.js';import {truncateMaxBufferSync} from './max-buffer.js';
// Apply `stdout`/`stderr` options, after spawning, in sync modeexport const transformOutputSync = ({fileDescriptors, syncResult: {output}, options, verboseInfo}) => {111 unmodified linesExpand all
// When the `std*` target is a file path/URL or a file descriptorconst writeToFiles = (serializedResult, stdioItems, outputFiles) => { const fileItems = stdioItems.filter(({type}) => FILE_TYPES.has(type)); for (const {path, append} of fileItems) { const pathString = typeof path === 'string' ? path : path.toString(); if (append || outputFiles.has(pathString)) { const writtenPaths = new Set();
for (const stdioItem of fileItems) { const {type, append} = stdioItem; // A `filePath` and a `fileUrl` can target the same file, so they must share the same key const path = type === 'fileNumber' ? stdioItem.path : getFileTarget(stdioItem);
// A single file descriptor can target the same file twice, e.g. `stdout: [{file}, {file}]`. // Its output is a single stream, so it must only be written once. if (writtenPaths.has(path)) { continue; }
writtenPaths.add(path); // Like with asynchronous methods, when several file descriptors target the same file, the first one decides whether it is appended to if (append || outputFiles.has(path)) { appendFileSync(path, serializedResult); } else { outputFiles.add(pathString); writeFileSync(path, serializedResult); }
outputFiles.add(path); }};modified:lib/stdio/duplicate.js+26 added-16 removed
1+import {resolve} from 'node:path';2+import {fileURLToPath} from 'node:url';3 import {4 SPECIAL_DUPLICATE_TYPES_SYNC,5 SPECIAL_DUPLICATE_TYPES,6 FORBID_DUPLICATE_TYPES,7 TYPE_TO_MESSAGE,8 } from './type.js';9 10+// `{file: './output.txt'}` and a `file:` URL are two ways to target the same file, so both must be compared together11+const isFileType = type => SPECIAL_DUPLICATE_TYPES_SYNC.has(type);12+13+// The file that a `filePath` or `fileUrl` stdio item targets, as an absolute path14+export const getFileTarget = ({type, value}) => type === 'filePath'15+ ? resolve(value.file)16+ : fileURLToPath(value);17+18 // Duplicates in the same file descriptor is most likely an error.19 // However, this can be useful with generators.20 export const filterDuplicates = stdioItems => stdioItems.filter((stdioItemOne, indexOne) =>21 stdioItems.every((stdioItemTwo, indexTwo) => !hasSameValueAndDirection(stdioItemOne, stdioItemTwo)5 unmodified lines27 && stdioItemOne.direction === stdioItemTwo.direction;28 29 // 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'}]}`.32 export const getDuplicateStream = ({stdioItem: {type, value, optionName}, direction, fileDescriptors, isSync}) => {33 const otherStdioItems = getOtherStdioItems(fileDescriptors, type);34 if (otherStdioItems.length === 0) {35 return;29 unmodified lines65 });66 }67 };68 58-// Values shared by multiple file descriptors69+// Values shared by multiple file descriptors, including the other items of the file descriptor currently being built70 const 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));75 76+// A `filePath` and a `fileUrl` are compared together, since they can target the same file77+const isSameDuplicateType = (otherType, type) => otherType === type || (isFileType(otherType) && isFileType(type));78+79 // With `execaSync()`, do not allow setting a file path both in input and output80 const validateDuplicateStreamSync = ({otherStdioItems, type, value, optionName, direction}) => {81 if (SPECIAL_DUPLICATE_TYPES_SYNC.has(type)) {82 getDuplicateStreamInstance({11 unmodified lines94 // 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.97 const 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 }102 103 const differentStdioItem = duplicateStdioItems.find(stdioItem => stdioItem.direction !== direction);104 throwOnDuplicateStream(differentStdioItem, optionName, type);105 106+ // 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 };110 94-const 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 one112+const hasSameValue = (otherStdioItem, type, value) => isFileType(otherStdioItem.type)113+ ? getFileTarget(otherStdioItem) === getFileTarget({type, value})114+ : otherStdioItem.value === value;115 99- if (type === 'fileUrl') {100- return value.href === secondValue.href;101- }102-103- return value === secondValue;104-};105-116 // 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 linesmodified:lib/stdio/handle.js+22 added-18 removed
173 unmodified lines174 const fileDescriptors = [];175 176 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 }186 187 return fileDescriptors;188 } catch (error) {1 unmodified line190 throw error;191 }192 };193 194-const 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+/*195+The 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+*/199+const addFinalFileDescriptor = ({fileDescriptor, fileDescriptors, addProperties, options, isSync}) => {200+ const {direction, objectMode, stdioItems} = fileDescriptor;201+ const finalFileDescriptor = {direction, objectMode, stdioItems: []};202+ fileDescriptors.push(finalFileDescriptor);203+204+ 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 };215 216 const addStreamProperties = ({stdioItem, addProperties, direction, options, fileDescriptors, isSync}) => {217 const duplicateStream = getDuplicateStream({41 unmodified linesmodified:test/stdio/duplicate.js+139 added-1 removed
1 import {once} from 'node:events';2 import {createReadStream, createWriteStream} from 'node:fs';3-import {readFile, writeFile, rm} from 'node:fs/promises';3+import {mkdir, readFile, writeFile, rm} from 'node:fs/promises';4+import {join} from 'node:path';5 import {Readable, Writable} from 'node:stream';6 import {pathToFileURL} from 'node:url';7 import test from 'ava';8 import tempfile from 'tempfile';167 unmodified lines176 test('Can re-use same file path on different output file descriptors, sync', testMultipleFileOutput, getAbsolutePath, execaSync);177 test('Can re-use same file URL on different output file descriptors', testMultipleFileOutput, pathToFileURL, execa);178 test('Can re-use same file URL on different output file descriptors, sync', testMultipleFileOutput, pathToFileURL, execaSync);179 180+// One of the two `append` flags would be silently ignored otherwise181+const 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+};190+191+test('Cannot use different `append` values on the same output file path', testAppendConflict, execa, undefined, true);192+test('Cannot use different `append` values on the same output file path, reversed', testAppendConflict, execa, true, undefined);193+test('Cannot use different `append` values on the same output file path, sync', testAppendConflict, execaSync, undefined, true);194+test('Cannot use different `append` values on the same output file path, reversed, sync', testAppendConflict, execaSync, true, undefined);195+196+// Two items of a single file descriptor must be checked too, not only two different file descriptors197+const sameFdName = '`stdout` and `stdout`';198+199+const 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+};205+206+test('Cannot use different `append` values on the same output file path in the same file descriptor', testAppendConflictSameFd, execa, undefined, true);207+test('Cannot use different `append` values on the same output file path in the same file descriptor, reversed', testAppendConflictSameFd, execa, true, undefined);208+test('Cannot use different `append` values on the same output file path in the same file descriptor, sync', testAppendConflictSameFd, execaSync, undefined, true);209+test('Cannot use different `append` values on the same output file path in the same file descriptor, reversed, sync', testAppendConflictSameFd, execaSync, true, undefined);210+211+const 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+};218+219+test('Can use the same `append: true` value on the same output file path', testSameAppend, execa);220+test('Can use the same `append: true` value on the same output file path, sync', testSameAppend, execaSync);221+222+const 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+};228+229+test('Falsy `append` values are the same on the same output file path', testFalsyAppend, execa);230+test('Falsy `append` values are the same on the same output file path, sync', testFalsyAppend, execaSync);231+232 const testMultipleFileInputOutput = async (t, mapFile, execaMethod) => {233 const inputFilePath = tempfile();234 const outputFilePath = tempfile();235 await writeFile(inputFilePath, foobarString);27 unmodified lines263 test('Cannot use same file path on both input and output file descriptors', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execa);264 test('Cannot use same file URL on both input and output file descriptors', testMultipleInvalid, getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execa);265 test('Cannot use same file path on both input and output file descriptors, sync', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync);266 test('Cannot use same file URL on both input and output file descriptors, sync', testMultipleInvalid, getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync);267+268+// 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.270+const 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+};276+277+test('Cannot use same Duplex twice on the same output file descriptor', testSameStreamSameFd, noopDuplex, duplexName);278+test('Cannot use same TransformStream twice on the same output file descriptor', testSameStreamSameFd, () => new TransformStream(), webTransformName);279+280+// The streams created for the earlier items must be destroyed when a later one is rejected, otherwise they are leaked281+test('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+});288+289+// `{file: './output.txt'}` and a `file:` URL are two ways to target the same file290+const 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+};296+297+const 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+};303+304+test('Can use a file path and a file URL on different output file descriptors', testFilePathAndUrl, execa);305+test('Can use a file URL and a file path on different output file descriptors', testFileUrlAndPath, execa);306+test('Can use a file path and a file URL on different output file descriptors, sync', testFilePathAndUrl, execaSync);307+test('Can use a file URL and a file path on different output file descriptors, sync', testFileUrlAndPath, execaSync);308+309+// A single file descriptor can target the same file twice. Its output is a single stream, so it must only be written once.310+const 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+};316+317+test('Can use the same file path twice on the same output file descriptor', testSameFileSameFd, execa);318+test('Can use the same file path twice on the same output file descriptor, sync', testSameFileSameFd, execaSync);319+320+// A file path is resolved before being compared, so equivalent spellings of the same file are detected321+const 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`;328+329+ 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+};333+334+test('Can use equivalent file paths on different output file descriptors', testFilePathNormalized, execa);335+test('Can use equivalent file paths on different output file descriptors, sync', testFilePathNormalized, execaSync);336+337+const 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`;344+345+ 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+};349+350+test('Can use an equivalent file URL on different output file descriptors', testFilePathAndUrlNormalized, execa);351+test('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 lines73 74 test('stdout cannot use 4+ and another value, sync', testOverflowStreamArraySync, 1);75 test('stderr cannot use 4+ and another value, sync', testOverflowStreamArraySync, 2);76 test('stdio[*] cannot use 4+ and another value, sync', testOverflowStreamArraySync, 3);77+78+// `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.81+const testSameTargetOutput = async (t, stdioOption, isSync) => {82+ const {stdout} = await nestedSubprocess('noop.js', [foobarString], {stdout: stdioOption, isSync});83+ t.is(stdout, foobarString);84+};85+86+test('stdout output is not duplicated with [1, "inherit"]', testSameTargetOutput, [1, 'inherit'], false);87+test('stdout output is not duplicated with ["inherit", 1]', testSameTargetOutput, ['inherit', 1], false);88+test('stdout output is not duplicated with [1, "inherit"], sync', testSameTargetOutput, [1, 'inherit'], true);89+test('stdout output is not duplicated with ["inherit", 1], sync', testSameTargetOutput, ['inherit', 1], true);modified:test/stdio/web-stream.js+11 added
94 unmodified lines95 });96 await t.throwsAsync(execa('stdin.js', {stdin: readableStream, timeout: 1}), {message: /timed out/});97 await promise;98 });99+100+// 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.102+const 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+};107+108+test('stdin can share a ReadableStream with stdio[*]', testSharedReadableStream, ['0'], ['shared', 'pipe', 'pipe', 'shared']);109+test('stdio[*] can share a ReadableStream with another stdio[*]', testSharedReadableStream, ['3'], ['pipe', 'pipe', 'pipe', 'shared', 'shared']);