handle.js
This file
Path
lib/stdio/handle.js
266 lines · 9.4 KiB · JavaScript
Last changed by
Fix an uncaught error when a file target cannot be opened and the subprocess fails to spawnSindre Sorhusbefore adoption1cee524
History of this fileTake it
The walk stopped after 200 commits: lines older than 7faa8f5 point at it.
Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
line 1why, one step back1import {getStreamName, isStandardStream} from '../utils/standard-stream.js';Rename files (#977)ehmickybefore adoption4b2e316
lines 2–3why, one step back2import {normalizeTransforms} from '../transform/normalize.js';3import {getFdObjectMode} from '../transform/object-mode.js';Upgrade xo (#980)ehmickybefore adoptionccfa412
lines 4–7why, one step back4import {5 getStdioItemType,6 isRegularUrl,7 isUnknownStdioString,Generalize `{value, input}` to any direction-ambiguous stdio value (#1249)Sindre Sorhusbefore adoption9fbf5ba
line 8why, one step back8 isStdioValueObject,Add `{value: 'pipe', input: true}` to use an additional file descriptor as input (#1246)Sindre Sorhusbefore adoption487a3a4
line 9why, one step back9 checkBooleanOption,Upgrade xo (#980)ehmickybefore adoptionccfa412
lines 10–11why, one step back10 FILE_TYPES,11} from './type.js';Refactor `all` option (#975)ehmickybefore adoption7faa8f5
line 12why, one step back12import {getStreamDirection} from './direction.js';Rename files (#977)ehmickybefore adoption4b2e316
line 13why, one step back13import {normalizeStdioOption} from './stdio-option.js';Refactor `all` option (#975)ehmickybefore adoption7faa8f5
line 14why, one step back14import {handleNativeStream} from './native.js';Rename files (#977)ehmickybefore adoption4b2e316
line 15why, one step back15import {handleInputOptions} from './input-option.js';Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
line 16why, one step back16import {filterDuplicates, getDuplicateStream} from './duplicate.js';Refactor `all` option (#975)ehmickybefore adoption7faa8f5
lines 17–18why, one step back1718// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync modeAdd more code comments (#984)ehmickybefore adoptionfdd8a9f
lines 19–20why, one step back19// They are converted into an array of `fileDescriptors`.20// Each `fileDescriptor` is normalized, validated and contains all information necessary for further handling.Rename files (#977)ehmickybefore adoption4b2e316
line 21why, one step back21export const handleStdio = (addProperties, options, verboseInfo, isSync) => {Refactor `verbose` logic (#1126)ehmickybefore adoptionf9f1199
line 22why, one step back22 const stdio = normalizeStdioOption(options, verboseInfo, isSync);Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
line 23why, one step back23 const initialFileDescriptors = stdio.map((stdioOption, fdNumber) => getFileDescriptor({Upgrade xo (#980)ehmickybefore adoptionccfa412
lines 24–28why, one step back24 stdioOption,25 fdNumber,26 options,27 isSync,28 }));Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
lines 29–34why, one step back29 const fileDescriptors = getFinalFileDescriptors({30 initialFileDescriptors,31 addProperties,32 options,33 isSync,34 });Refactor `all` option (#975)ehmickybefore adoption7faa8f5
lines 35–38why, one step back35 options.stdio = fileDescriptors.map(({stdioItems}) => forwardStdio(stdioItems));36 return fileDescriptors;37};38Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
line 39why, one step back39const getFileDescriptor = ({stdioOption, fdNumber, options, isSync}) => {Refactor `all` option (#975)ehmickybefore adoption7faa8f5
line 40why, one step back40 const optionName = getStreamName(fdNumber);Upgrade xo (#980)ehmickybefore adoptionccfa412
lines 41–46why, one step back41 const {stdioItems: initialStdioItems, isStdioArray} = initializeStdioItems({42 stdioOption,43 fdNumber,44 options,45 optionName,46 });TweaksSindre Sorhusbefore adoption698a1b8
lines 47–52why, one step back47 const direction = getStreamDirection({48 stdioItems: initialStdioItems,49 isStdioArray,50 fdNumber,51 optionName,52 });Upgrade xo (#980)ehmickybefore adoptionccfa412
lines 53–59why, one step back53 const stdioItems = initialStdioItems.map(stdioItem => handleNativeStream({54 stdioItem,55 isStdioArray,56 fdNumber,57 direction,58 isSync,59 }));Refactor `all` option (#975)ehmickybefore adoption7faa8f5
line 60why, one step back60 const normalizedStdioItems = normalizeTransforms(stdioItems, optionName, direction, options);Split files into smaller ones (#976)ehmickybefore adoptiond7c6853
line 61why, one step back61 const objectMode = getFdObjectMode(normalizedStdioItems, direction);Refactor `all` option (#975)ehmickybefore adoption7faa8f5
line 62why, one step back62 validateFileObjectMode(normalizedStdioItems, objectMode);Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
line 63why, one step back63 return {direction, objectMode, stdioItems: normalizedStdioItems};Refactor `all` option (#975)ehmickybefore adoption7faa8f5
lines 64–65why, one step back64};65Add more code comments (#984)ehmickybefore adoptionfdd8a9f
lines 66–68why, one step back66// We make sure passing an array with a single item behaves the same as passing that item without an array.67// This is what users would expect.68// For example, `stdout: ['ignore']` behaves the same as `stdout: 'ignore'`.Refactor `all` option (#975)ehmickybefore adoption7faa8f5
lines 69–70why, one step back69const initializeStdioItems = ({stdioOption, fdNumber, options, optionName}) => {70 const values = Array.isArray(stdioOption) ? stdioOption : [stdioOption];Fix input with inherited stdin (#1232)Puneet Dixitbefore adoption3ed0544
line 71why, one step back71 const inputStdioItems = handleInputOptions(options, fdNumber);Refactor `all` option (#975)ehmickybefore adoption7faa8f5
line 72why, one step back72 const initialStdioItems = [Fix input with inherited stdin (#1232)Puneet Dixitbefore adoption3ed0544
lines 73–74why, one step back73 ...omitInheritedStdin(values.map(value => initializeStdioItem(value, optionName)), inputStdioItems),74 ...inputStdioItems,Refactor `all` option (#975)ehmickybefore adoption7faa8f5
lines 75–82why, one step back75 ];7677 const stdioItems = filterDuplicates(initialStdioItems);78 const isStdioArray = stdioItems.length > 1;79 validateStdioArray(stdioItems, isStdioArray, optionName);80 validateStreams(stdioItems);81 return {stdioItems, isStdioArray};82};Fix input with inherited stdin (#1232)Puneet Dixitbefore adoption3ed0544
lines 83–90why, one step back8384const omitInheritedStdin = (stdioItems, inputStdioItems) => inputStdioItems.length > 0 && isInheritedStdinOnly(stdioItems)85 ? []86 : stdioItems;8788const isInheritedStdinOnly = stdioItems => stdioItems.length === 189 && stdioItems[0].type === 'native'90 && stdioItems[0].value === 'inherit';Refactor `all` option (#975)ehmickybefore adoption7faa8f5
line 91why, one step back91Add `{value: 'pipe', input: true}` to use an additional file descriptor as input (#1246)Sindre Sorhusbefore adoption487a3a4
line 92why, one step back92const initializeStdioItem = (value, optionName) => {Generalize `{value, input}` to any direction-ambiguous stdio value (#1249)Sindre Sorhusbefore adoption9fbf5ba
lines 93–94why, one step back93 if (isStdioValueObject(value)) {94 return initializeStdioValueObject(value, optionName);Add `{value: 'pipe', input: true}` to use an additional file descriptor as input (#1246)Sindre Sorhusbefore adoption487a3a4
lines 95–103why, one step back95 }9697 return {98 type: getStdioItemType(value, optionName),99 value,100 optionName,101 };102};103Generalize `{value, input}` to any direction-ambiguous stdio value (#1249)Sindre Sorhusbefore adoption9fbf5ba
lines 104–105why, one step back104// The `{value, input}` object form wraps any stdio value with an explicit direction.105const initializeStdioValueObject = ({value, input}, optionName) => {Add `{value: 'pipe', input: true}` to use an additional file descriptor as input (#1246)Sindre Sorhusbefore adoption487a3a4
lines 106–108why, one step back106 checkBooleanOption(input, `${optionName}.input`);107108 return {Generalize `{value, input}` to any direction-ambiguous stdio value (#1249)Sindre Sorhusbefore adoption9fbf5ba
line 109why, one step back109 type: getStdioItemType(value, optionName),Add `{value: 'pipe', input: true}` to use an additional file descriptor as input (#1246)Sindre Sorhusbefore adoption487a3a4
lines 110–114why, one step back110 value,111 direction: input ? 'input' : undefined,112 optionName,113 };114};Refactor `all` option (#975)ehmickybefore adoption7faa8f5
lines 115–131why, one step back115116const validateStdioArray = (stdioItems, isStdioArray, optionName) => {117 if (stdioItems.length === 0) {118 throw new TypeError(`The \`${optionName}\` option must not be an empty array.`);119 }120121 if (!isStdioArray) {122 return;123 }124125 for (const {value, optionName} of stdioItems) {126 if (INVALID_STDIO_ARRAY_OPTIONS.has(value)) {127 throw new Error(`The \`${optionName}\` option must not include \`${value}\`.`);128 }129 }130};131Remove the old `stdio: [..., 'ipc']` syntax (#1245)Sindre Sorhusbefore adoptiondcf611c
line 132why, one step back132// Using the `ignore` value together with others for the same stream does not make sense, so we make it fail.Refactor `all` option (#975)ehmickybefore adoption7faa8f5
line 133why, one step back133// However, we do allow it if the array has a single item.Remove the old `stdio: [..., 'ipc']` syntax (#1245)Sindre Sorhusbefore adoptiondcf611c
line 134why, one step back134const INVALID_STDIO_ARRAY_OPTIONS = new Set(['ignore']);Refactor `all` option (#975)ehmickybefore adoption7faa8f5
lines 135–138why, one step back135136const validateStreams = stdioItems => {137 for (const stdioItem of stdioItems) {138 validateFileStdio(stdioItem);Fix invalid `stdio` values being acceptedSindre Sorhusbefore adoptionc6bd387
line 139why, one step back139 validateFileDescriptorStdio(stdioItem);Refactor `all` option (#975)ehmickybefore adoption7faa8f5
lines 140–141why, one step back140 }141};Fix invalid `stdio` values being acceptedSindre Sorhusbefore adoptionc6bd387
lines 142–150why, one step back142143// A number is a file descriptor. Anything else is not a valid one, and passing it to `node:child_process` aborts the current process with a fatal assertion instead of throwing.144const validateFileDescriptorStdio = ({type, value, optionName}) => {145 if (type === 'native' && typeof value === 'number' && (!Number.isInteger(value) || value < 0 || value > MAX_FILE_DESCRIPTOR)) {146 throw new TypeError(`The \`${optionName}\` option must be a non-negative 32-bit integer: got ${value}.`);147 }148};149150// `node:child_process` converts file descriptors to a 32-bit signed integer, and aborts the process when it cannotTweaksSindre Sorhusbefore adoption698a1b8
line 151why, one step back151const MAX_FILE_DESCRIPTOR = (2 ** 31) - 1;Refactor `all` option (#975)ehmickybefore adoption7faa8f5
lines 152–177why, one step back152153const validateFileStdio = ({type, value, optionName}) => {154 if (isRegularUrl(value)) {155 throw new TypeError(`The \`${optionName}: URL\` option must use the \`file:\` scheme.156For example, you can use the \`pathToFileURL()\` method of the \`url\` core module.`);157 }158159 if (isUnknownStdioString(type, value)) {160 throw new TypeError(`The \`${optionName}: { file: '...' }\` option must be used instead of \`${optionName}: '...'\`.`);161 }162};163164const validateFileObjectMode = (stdioItems, objectMode) => {165 if (!objectMode) {166 return;167 }168169 const fileStdioItem = stdioItems.find(({type}) => FILE_TYPES.has(type));170 if (fileStdioItem !== undefined) {171 throw new TypeError(`The \`${fileStdioItem.optionName}\` option cannot use both files and transforms in objectMode.`);172 }173};174175// Some `stdio` values require Execa to create streams.176// For example, file paths create file read/write streams.177// Those transformations are specified in `addProperties`, which is both direction-specific and type-specific.Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
lines 178–182why, one step back178const getFinalFileDescriptors = ({initialFileDescriptors, addProperties, options, isSync}) => {179 const fileDescriptors = [];180181 try {182 for (const fileDescriptor of initialFileDescriptors) {Fix duplicated or conflicting file descriptor targetsSindre Sorhusbefore adoption587045a
line 183why, one step back183 addFinalFileDescriptor({Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
lines 184–188why, one step back184 fileDescriptor,185 fileDescriptors,186 addProperties,187 options,188 isSync,Fix duplicated or conflicting file descriptor targetsSindre Sorhusbefore adoption587045a
line 189why, one step back189 });Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
lines 190–198why, one step back190 }191192 return fileDescriptors;193 } catch (error) {194 cleanupCustomStreams(fileDescriptors);195 throw error;196 }197};198Fix duplicated or conflicting file descriptor targetsSindre Sorhusbefore adoption587045a
lines 199–218why, one step back199/*200The file descriptor is added to `fileDescriptors` before its items are, for two reasons:201 - its items are added one at a time, so that each one knows about the previous ones, to detect duplicates within the same file descriptor202 - if an item throws, the streams created by the previous ones are cleaned up too203*/204const addFinalFileDescriptor = ({fileDescriptor, fileDescriptors, addProperties, options, isSync}) => {205 const {direction, objectMode, stdioItems} = fileDescriptor;206 const finalFileDescriptor = {direction, objectMode, stdioItems: []};207 fileDescriptors.push(finalFileDescriptor);208209 for (const stdioItem of stdioItems) {210 finalFileDescriptor.stdioItems.push(addStreamProperties({211 stdioItem,212 addProperties,213 direction,214 options,215 fileDescriptors,216 isSync,217 }));218 }Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
lines 219–243why, one step back219};220221const addStreamProperties = ({stdioItem, addProperties, direction, options, fileDescriptors, isSync}) => {222 const duplicateStream = getDuplicateStream({223 stdioItem,224 direction,225 fileDescriptors,226 isSync,227 });228229 if (duplicateStream !== undefined) {230 return {...stdioItem, stream: duplicateStream};231 }232233 return {234 ...stdioItem,235 ...addProperties[direction][stdioItem.type](stdioItem, options),236 };237};238239// The stream error handling is performed by the piping logic above, which cannot be performed before subprocess spawning.240// If the subprocess spawning fails (e.g. due to an invalid command), the streams need to be manually destroyed.241// We need to create those streams before subprocess spawning, in case their creation fails, e.g. when passing an invalid generator as argument.242// Like this, an exception would be thrown, which would prevent spawning a subprocess.243export const cleanupCustomStreams = fileDescriptors => {Fix an uncaught error when a file target cannot be opened and the subprocess fails to spawnSindre Sorhusbefore adoption1cee524
lines 244–246why, one step back244 for (const {stream} of fileDescriptors.flatMap(({stdioItems}) => stdioItems)) {245 if (stream === undefined || isStandardStream(stream)) {246 continue;Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
line 247why, one step back247 }Fix an uncaught error when a file target cannot be opened and the subprocess fails to spawnSindre Sorhusbefore adoption1cee524
lines 248–252why, one step back248249 // The stream can still error after being destroyed, e.g. when its file cannot be opened.250 // That error would be uncaught and crash the current process, although it is irrelevant since execa already fails with its own error.251 stream.on('error', () => {});252 stream.destroy();Fix passing the same file or stream to both `stdout` and `stderr` (#1004)ehmickybefore adoptionea889c7
lines 253–254why, one step back253 }254};Refactor `all` option (#975)ehmickybefore adoption7faa8f5
lines 255–266why, one step back255256// When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `subprocess.std*`.257// 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*`.258// Therefore the `std*` options must be either `pipe` or `overlapped`. Other values do not set `subprocess.std*`.259const forwardStdio = stdioItems => {260 if (stdioItems.length > 1) {261 return stdioItems.some(({value}) => value === 'overlapped') ? 'overlapped' : 'pipe';262 }263264 const [{type, value}] = stdioItems;265 return type === 'native' ? value : 'pipe';266};