Add more code comments (#984)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent bd3b478 · Browse files · 60 files·+148 added−13 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
60 files+148 added−13 removed
- tests:+3 added−0 removed
- other:+145 added−13 removed
Provenance
- Commit
fdd8a9f- Tree
498bb42- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
bd3b478
60 files changed+148 added−13 removed
modified:lib/arguments/command.js+1 added
2 unmodified lines345678910118 unmodified lines2 unmodified linesimport {getStartTime} from '../return/duration.js';import {joinCommand} from './escape.js';import {normalizeFdSpecificOption} from './specific.js';
// Compute `result.command`, `result.escapedCommand` and `verbose`-related informationexport const handleCommand = (filePath, rawArguments, rawOptions) => { const startTime = getStartTime(); const {command, escapedCommand} = joinCommand(filePath, rawArguments); const verboseInfo = getVerboseInfo(normalizeFdSpecificOption(rawOptions, 'verbose'));8 unmodified linesmodified:lib/arguments/cwd.js+2 added
123456789106 unmodified lines17181920212223242514 unmodified linesimport {statSync} from 'node:fs';import {resolve} from 'node:path';import process from 'node:process';import {safeNormalizeFileUrl} from './file-url.js';
// Normalize `cwd` optionexport const normalizeCwd = (cwd = getDefaultCwd()) => { const cwdString = safeNormalizeFileUrl(cwd, 'The "cwd" option'); return resolve(cwdString);};6 unmodified lines throw error; }};
// When `cwd` option has an invalid value, provide with a better error messageexport const fixCwdError = (originalMessage, cwd) => { if (cwd === getDefaultCwd()) { return originalMessage; }14 unmodified linesmodified:lib/arguments/encoding-option.js+1 added
1234545 unmodified lines// Validate `encoding` optionexport const validateEncoding = ({encoding}) => { if (ENCODINGS.has(encoding)) { return; }45 unmodified linesmodified:lib/arguments/escape.js+2 added
12345678910111213141516171854 unmodified linesimport {platform} from 'node:process';import {stripVTControlCharacters} from 'node:util';
// Compute `result.command` and `result.escapedCommand`export const joinCommand = (filePath, rawArguments) => { const fileAndArguments = [filePath, ...rawArguments]; const command = fileAndArguments.join(' '); const escapedCommand = fileAndArguments .map(fileAndArgument => quoteString(escapeControlCharacters(fileAndArgument))) .join(' '); return {command, escapedCommand};};
// Remove ANSI sequences and escape control characters and newlinesexport const escapeLines = lines => stripVTControlCharacters(lines) .split('\n') .map(line => escapeControlCharacters(line)) .join('\n');54 unmodified linesmodified:lib/arguments/fd-options.js+3 added
1 import {parseFd} from './specific.js';2 3+// Retrieve stream targeted by the `to` option4 export const getToStream = (destination, to = 'stdin') => {5 const isWritable = true;6 const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(destination);7 const fdNumber = getFdNumber(fileDescriptors, to, isWritable);5 unmodified lines13 14 return destinationStream;15 };16 17+// Retrieve stream targeted by the `from` option18 export const getFromStream = (source, from = 'stdout') => {19 const isWritable = false;20 const {options, fileDescriptors} = SUBPROCESS_OPTIONS.get(source);21 const fdNumber = getFdNumber(fileDescriptors, from, isWritable);5 unmodified lines27 28 return sourceStream;29 };30 31+// Keeps track of the options passed to each Execa call32 export const SUBPROCESS_OPTIONS = new WeakMap();33 34 const getFdNumber = (fileDescriptors, fdName, isWritable) => {35 const fdNumber = parseFdNumber(fdName, isWritable);73 unmodified linesmodified:lib/arguments/file-url.js+2 added
12345672 unmodified lines101112131415import {fileURLToPath} from 'node:url';
// Allow some arguments/options to be either a file path string or a file URLexport const safeNormalizeFileUrl = (file, name) => { const fileString = normalizeFileUrl(file);
if (typeof fileString !== 'string') {2 unmodified lines
return fileString;};
// Same but also allows other values, e.g. `boolean` for the `shell` optionexport const normalizeFileUrl = file => file instanceof URL ? fileURLToPath(file) : file;modified:lib/arguments/options.js+2 added
8 unmodified lines9 import {normalizeCwd} from './cwd.js';10 import {normalizeFileUrl} from './file-url.js';11 import {normalizeFdSpecificOptions} from './specific.js';12 13+// Normalize the options object, and sometimes also the file paths and arguments.14+// Applies default values, validate allowed options, normalize them.15 export const normalizeOptions = (filePath, rawArguments, rawOptions) => {16 rawOptions.cwd = normalizeCwd(rawOptions.cwd);17 const [processedFile, processedArguments, processedOptions] = handleNodeOption(filePath, rawArguments, rawOptions);18 66 unmodified linesmodified:lib/arguments/specific.js+5 added
1 import isPlainObject from 'is-plain-obj';2 import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';3 import {verboseDefault} from '../verbose/info.js';4 5+// Some options can have different values for `stdout`/`stderr`/`fd3`.6+// This normalizes those to array of values.7+// For example, `{verbose: {stdout: 'none', stderr: 'full'}}` becomes `{verbose: ['none', 'none', 'full']}`8 export const normalizeFdSpecificOptions = options => {9 const optionsCopy = {...options};10 11 for (const optionName of FD_SPECIFIC_OPTIONS) {52 unmodified lines64 65 return fdNumber === 'all' ? [1, 2] : [fdNumber];66 };67 68+// Use the same syntax for fd-specific options and the `from`/`to` options69 export const parseFd = fdName => {70 if (fdName === 'all') {71 return fdName;72 }21 unmodified lines94 verbose: verboseDefault,95 stripFinalNewline: true,96 };97 98+// List of options which can have different values for `stdout`/`stderr`99 export const FD_SPECIFIC_OPTIONS = ['lines', 'buffer', 'maxBuffer', 'verbose', 'stripFinalNewline'];modified:lib/convert/add.js+1 added
2 unmodified lines3 import {createWritable} from './writable.js';4 import {createDuplex} from './duplex.js';5 import {createIterable} from './iterable.js';6 7+// Add methods to convert the subprocess to a stream or iterable8 export const addConvertedStreams = (subprocess, {encoding}) => {9 const concurrentStreams = initializeConcurrentStreams();10 subprocess.readable = createReadable.bind(undefined, {subprocess, concurrentStreams, encoding});11 subprocess.writable = createWritable.bind(undefined, {subprocess, concurrentStreams});4 unmodified linesmodified:lib/convert/duplex.js+1 added-1 removed
13 unmodified lines14 onStdinFinished,15 onWritableDestroy,16 } from './writable.js';17 18-// Create a `Duplex` stream combining both18+// Create a `Duplex` stream combining both `subprocess.readable()` and `subprocess.writable()`19 export const createDuplex = ({subprocess, concurrentStreams, encoding}, {from, to, binary: binaryOption = true, preserveNewlines = true} = {}) => {20 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);21 const {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams);22 const {subprocessStdin, waitWritableFinal, waitWritableDestroy} = getSubprocessStdin(subprocess, to, concurrentStreams);47 unmodified linesmodified:lib/convert/iterable.js+1 added
1 import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';2 import {getFromStream} from '../arguments/fd-options.js';3 import {iterateOnSubprocessStream} from '../io/iterate.js';4 5+// Convert the subprocess to an async iterable6 export const createIterable = (subprocess, encoding, {7 from,8 binary: binaryOption = false,9 preserveNewlines = false,25 unmodified linesmodified:lib/io/contents.js+2 added
4 unmodified lines5 import {iterateForResult} from './iterate.js';6 import {handleMaxBuffer} from './max-buffer.js';7 import {getStripFinalNewline} from './strip-newline.js';8 9+// Retrieve `result.stdout|stderr|all|stdio[*]`10 export const getStreamOutput = async ({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo: {fileDescriptors}}) => {11 if (shouldLogOutput({12 stdioItems: fileDescriptors[fdNumber]?.stdioItems,13 encoding,77 unmodified lines91 return handleBufferedData(error);92 }93 };94 95+// Ensure we are returning Uint8Arrays when using `encoding: 'buffer'`96 const handleBufferedData = ({bufferedData}) => isArrayBuffer(bufferedData)97 ? new Uint8Array(bufferedData)98 : bufferedData;modified:lib/io/max-buffer.js+6 added
1 import {MaxBufferError} from 'get-stream';2 import {getStreamName} from '../utils/standard-stream.js';3 4+// When the `maxBuffer` option is hit, a MaxBufferError is thrown.5+// The stream is aborted, then specific information is kept for the error message.6 export const handleMaxBuffer = ({error, stream, readableObjectMode, lines, encoding, fdNumber}) => {7 if (!(error instanceof MaxBufferError)) {8 throw error;9 }23 unmodified lines33 34 return 'characters';35 };36 37+// Error message when `maxBuffer` is hit38 export const getMaxBufferMessage = (error, maxBuffer) => {39 const {streamName, threshold, unit} = getMaxBufferInfo(error, maxBuffer);40 return `Command's ${streamName} was larger than ${threshold} ${unit}`;41 };7 unmodified lines49 delete error.maxBufferInfo;50 return {streamName: getStreamName(fdNumber), threshold: maxBuffer[fdNumber], unit};51 };52 53+// The only way to apply `maxBuffer` with `spawnSync()` is to use the native `maxBuffer` option Node.js provides.54+// However, this has multiple limitations, and cannot behave the exact same way as the async behavior.55+// When the `maxBuffer` is hit, a `ENOBUFS` error is thrown.56 export const isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === 'ENOBUFS'57 && output !== null58 && output.some(result => result !== null && result.length > getMaxBufferSync(maxBuffer));59 12 unmodified linesmodified:lib/io/output-async.js+3 added-1 removed
30 unmodified lines31 pipeStreams(inputStream, subprocess.stdio[fdNumber]);32 }33 };34 35-// `subprocess.stdin|stdout|stderr|stdio` is directly mutated.35+// When using transforms, `subprocess.stdin|stdout|stderr|stdio` is directly mutated36 const pipeTransform = (subprocess, stream, direction, fdNumber) => {37 if (direction === 'output') {38 pipeStreams(subprocess.stdio[fdNumber], stream);39 } else {9 unmodified lines49 };50 51 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}) => {56 if (stream === undefined) {57 return;58 }22 unmodified linesmodified:lib/io/output-sync.js+5 added
65 unmodified lines66 return returnedResult;67 }68 };69 70+// Applies transform generators to `stdout`/`stderr`71 const runOutputGeneratorsSync = (chunks, stdioItems, encoding, state) => {72 try {73 return runGeneratorsSync(chunks, stdioItems, encoding, false);74 } catch (error) {1 unmodified line76 return chunks;77 }78 };79 80+// The contents is converted to three stages:81+// - serializedResult: used when the target is a file path/URL or a file descriptor (including 'inherit')82+// - finalResult/returnedResult: returned as `result.std*`83 const serializeChunks = ({chunks, objectMode, encoding, lines, stripFinalNewline, fdNumber}) => {84 if (objectMode) {85 return {serializedResult: chunks};86 }9 unmodified lines96 97 return {serializedResult};98 };99 100+// 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)) {104 writeFileSync(path, serializedResult);3 unmodified linesmodified:lib/io/pipeline.js+1 added-1 removed
1 import {finished} from 'node:stream/promises';2 import {isStandardStream} from '../utils/standard-stream.js';3 4-// Like `Stream.pipeline(source, destination)`, but does not destroy standard streams.4+// Similar to `Stream.pipeline(source, destination)`, but does not destroy standard streams5 export const pipeStreams = (source, destination) => {6 source.pipe(destination);7 onSourceFinish(source, destination);8 onDestinationFinish(source, destination);40 unmodified linesmodified:lib/io/strip-newline.js+3 added
1 import stripFinalNewlineFunction from 'strip-final-newline';2 3+// Apply `stripFinalNewline` option, which applies to `result.stdout|stderr|all|stdio[*]`.4+// If the `lines` option is used, it is applied on each line, but using a different function.5 export const stripNewline = (value, {stripFinalNewline}, fdNumber) => getStripFinalNewline(stripFinalNewline, fdNumber) && value !== undefined && !Array.isArray(value)6 ? stripFinalNewlineFunction(value)7 : value;8 9+// Retrieve `stripFinalNewline` option value, including with `subprocess.all`10 export const getStripFinalNewline = (stripFinalNewline, fdNumber) => fdNumber === 'all'11 ? stripFinalNewline[1] || stripFinalNewline[2]12 : stripFinalNewline[fdNumber];modified:lib/methods/command.js+4 added
1+// Main logic for `execaCommand()`2 export const mapCommandAsync = ({file, commandArguments}) => parseCommand(file, commandArguments);3+4+// Main logic for `execaCommandSync()`5 export const mapCommandSync = ({file, commandArguments}) => ({...parseCommand(file, commandArguments), isSync: true});6 7+// Convert `execaCommand(command)` into `execa(file, ...commandArguments)`8 const parseCommand = (command, unusedArguments) => {9 if (unusedArguments.length > 0) {10 throw new TypeError(`The command and its arguments must be passed as a single string: ${command} ${unusedArguments}.`);11 }18 unmodified linesmodified:lib/methods/create.js+5 added
3 unmodified lines4 import {execaCoreSync} from './main-sync.js';5 import {execaCoreAsync} from './main-async.js';6 import {mergeOptions} from './bind.js';7 8+// Wraps every exported methods to provide the following features:9+// - template string syntax: execa`command argument`10+// - options binding: boundExeca = execa(options)11+// - optional argument/options: execa(file), execa(file, args), execa(file, options), execa(file, args, options)12+// `mapArguments()` and `setBoundExeca()` allows for method-specific logic.13 export const createExeca = (mapArguments, boundOptions, deepOptions, setBoundExeca) => {14 const createNested = (mapArguments, boundOptions, setBoundExeca) => createExeca(mapArguments, boundOptions, deepOptions, setBoundExeca);15 const boundExeca = (...execaArguments) => callBoundExeca({16 mapArguments,49 unmodified linesmodified:lib/methods/main-async.js+5 added-1 removed
17 unmodified lines18 import {waitForSubprocessResult} from '../resolve/wait-subprocess.js';19 import {addConvertedStreams} from '../convert/add.js';20 import {mergePromise} from './promise.js';21 22+// Main shared logic for all async methods: `execa()`, `execaCommand()`, `$`, `execaNode()`23 export const execaCoreAsync = (rawFile, rawArguments, rawOptions, createNested) => {24 const {file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleAsyncArguments(rawFile, rawArguments, rawOptions);25 const {subprocess, promise} = spawnSubprocessAsync({26 file,15 unmodified lines42 SUBPROCESS_OPTIONS.set(subprocess, {options, fileDescriptors});43 return subprocess;44 };45 46+// Compute arguments to pass to `child_process.spawn()`47 const handleAsyncArguments = (rawFile, rawArguments, rawOptions) => {48 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArguments, rawOptions);49 50 try {15 unmodified lines66 throw error;67 }68 };69 70+// Options normalization logic specific to async methods.68-// Prevent passing the `timeout` option directly to `child_process.spawn()`71+// Prevent passing the `timeout` option directly to `child_process.spawn()`.72 const handleAsyncOptions = ({timeout, signal, cancelSignal, ...options}) => {73 if (signal !== undefined) {74 throw new TypeError('The "signal" option has been renamed to "cancelSignal" instead.');75 }46 unmodified lines122 });123 return {subprocess, promise};124 };125 126+// Asynchronous logic, as opposed to the previous logic which can be run synchronously, i.e. can be returned to user right away127 const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller}) => {128 const context = {timedOut: false};129 130 const [errorInfo, [exitCode, signal], stdioResults, allResult] = await waitForSubprocessResult({51 unmodified linesmodified:lib/methods/main-sync.js+5 added
10 unmodified lines11 import {logEarlyResult} from '../verbose/complete.js';12 import {getAllSync} from '../resolve/all-sync.js';13 import {getExitResultSync} from '../resolve/exit-sync.js';14 15+// Main shared logic for all sync methods: `execaSync()`, `execaCommandSync()`, `$.sync()`16 export const execaCoreSync = (rawFile, rawArguments, rawOptions) => {17 const {file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleSyncArguments(rawFile, rawArguments, rawOptions);18 const result = spawnSubprocessSync({19 file,7 unmodified lines27 });28 return handleResult(result, verboseInfo, options);29 };30 31+// Compute arguments to pass to `child_process.spawnSync()`32 const handleSyncArguments = (rawFile, rawArguments, rawOptions) => {33 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArguments, rawOptions);34 35 try {16 unmodified lines52 throw error;53 }54 };55 56+// Options normalization logic specific to sync methods57 const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;58 59+// Options validation logic specific to sync methods60 const validateSyncOptions = ({ipc, detached, cancelSignal}) => {61 if (ipc) {62 throwInvalidSyncOption('ipc: true');63 }67 unmodified lines131 });132 }133 };134 135+// The `encoding` option is handled by Execa, not by `child_process.spawnSync()`136 const normalizeSpawnSyncOptions = ({encoding, maxBuffer, ...options}) => ({...options, encoding: 'buffer', maxBuffer: getMaxBufferSync(maxBuffer)});137 138 const getSyncResult = ({error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime}) => error === undefined139 ? makeSuccessResult({22 unmodified linesmodified:lib/methods/node.js+4 added
1 import {execPath, execArgv} from 'node:process';2 import {basename, resolve} from 'node:path';3 import {safeNormalizeFileUrl} from '../arguments/file-url.js';4 5+// `execaNode()` is a shortcut for `execa(..., {node: true})`6 export const mapNode = ({options}) => {7 if (options.node === false) {8 throw new TypeError('The "node" option cannot be false with `execaNode()`.');9 }10 11 return {options: {...options, node: true}};12 };13 14+// Applies the `node: true` option, and the related `nodePath`/`nodeOptions` options.15+// Modifies the file commands/arguments to ensure the same Node binary and flags are re-used.16+// Also adds `ipc: true` and `shell: false`.17 export const handleNodeOption = (file, commandArguments, {18 node: shouldHandleNode = false,19 nodePath = execPath,20 nodeOptions = execArgv.filter(nodeOption => !nodeOption.startsWith('--inspect')),31 unmodified linesmodified:lib/methods/parameters.js+2 added
1 import isPlainObject from 'is-plain-obj';2 import {safeNormalizeFileUrl} from '../arguments/file-url.js';3 4+// The command `arguments` and `options` are both optional.5+// This also does basic validation on them and on the command file.6 export const normalizeParameters = (rawFile, rawArguments = [], rawOptions = {}) => {7 const filePath = safeNormalizeFileUrl(rawFile, 'First argument');8 const [commandArguments, options] = isPlainObject(rawArguments)9 ? [[], rawArguments]22 unmodified linesmodified:lib/methods/script.js+7 added
1+// Sets `$.sync` and `$.s`2 export const setScriptSync = (boundExeca, createNested, boundOptions) => {3 boundExeca.sync = createNested(mapScriptSync, boundOptions);4 boundExeca.s = boundExeca.sync;5 };6 7+// Main logic for `$`8 export const mapScriptAsync = ({options}) => getScriptOptions(options);9+10+// Main logic for `$.sync`11 const mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});12 13+// `$` is like `execa` but with script-friendly options: `{stdin: 'inherit', preferLocal: true}`14 const getScriptOptions = options => ({options: {...getScriptStdinOption(options), ...options}});15 16 const getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined17 ? {stdin: 'inherit'}18 : {};19 20+// When using $(...).pipe(...), most script-friendly options should apply to both commands.21+// However, some options (like `stdin: 'inherit'`) would create issues with piping, i.e. cannot be deep.22 export const deepScriptOptions = {preferLocal: true};modified:lib/methods/template.js+3 added
1 import {ChildProcess} from 'node:child_process';2 import isPlainObject from 'is-plain-obj';3 import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';4 5+// Check whether the template string syntax is being used6 export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);7 8+// Convert execa`file ...commandArguments` to execa(file, commandArguments)9 export const parseTemplates = (templates, expressions) => {10 let tokens = [];11 12 for (const [index, template] of templates.entries()) {94 unmodified lines107 `${tokens.at(-1)}${nextTokens[0]}`,108 ...nextTokens.slice(1),109 ];110 111+// Handle `${expression}` inside the template string syntax112 const parseExpression = expression => {113 const typeOfExpression = typeof expression;114 115 if (typeOfExpression === 'string') {34 unmodified linesmodified:lib/pipe/abort.js+2 added
1 import {aborted} from 'node:util';2 import {createNonCommandError} from './throw.js';3 4+// When passing an `unpipeSignal` option, abort piping when the signal is aborted.5+// However, do not terminate the subprocesses.6 export const unpipeOnAbort = (unpipeSignal, unpipeContext) => unpipeSignal === undefined7 ? []8 : [unpipeOnSignalAbort(unpipeSignal, unpipeContext)];9 11 unmodified linesmodified:lib/pipe/pipe-arguments.js+6 added
1 import {normalizeParameters} from '../methods/parameters.js';2 import {getStartTime} from '../return/duration.js';3 import {SUBPROCESS_OPTIONS, getToStream, getFromStream} from '../arguments/fd-options.js';4 5+// Normalize and validate arguments passed to `source.pipe(destination)`6 export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...pipeArguments) => {7 const startTime = getStartTime();8 const {9 destination,35 unmodified lines45 return {destinationError: error};46 }47 };48 49+// Piping subprocesses can use three syntaxes:50+// - source.pipe('command', commandArguments, pipeOptionsOrDestinationOptions)51+// - source.pipe`command commandArgument` or source.pipe(pipeOptionsOrDestinationOptions)`command commandArgument`52+// - source.pipe(execa(...), pipeOptions)53 const getDestination = (boundOptions, createNested, firstArgument, ...pipeArguments) => {54 if (Array.isArray(firstArgument)) {55 const destination = createNested(mapDestinationArguments, boundOptions)(firstArgument, ...pipeArguments);56 return {destination, pipeOptions: boundOptions};19 unmodified lines76 77 throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);78 };79 80+// Force `stdin: 'pipe'` with the destination subprocess81 const mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});82 83 const getSourceStream = (source, from) => {84 try {6 unmodified linesmodified:lib/pipe/setup.js+1 added
23 unmodified lines24 });25 return promise;26 };27 28+// Asynchronous logic when piping subprocesses29 const handlePipePromise = async ({30 sourcePromise,31 sourceStream,32 sourceOptions,40 unmodified linesmodified:lib/pipe/throw.js+3 added
1 import {makeEarlyError} from '../return/result.js';2 import {abortSourceStream, endDestinationStream} from '../io/pipeline.js';3 4+// When passing invalid arguments to `source.pipe()`, throw asynchronously.5+// We also abort both subprocesses.6 export const handlePipeArgumentsError = ({7 sourceStream,8 sourceError,9 destinationStream,33 unmodified lines43 return sourceError;44 }45 };46 47+// Specific error return value when passing invalid arguments to `subprocess.pipe()` or when using `unpipeSignal`48 export const createNonCommandError = ({error, fileDescriptors, sourceOptions, startTime}) => makeEarlyError({49 error,50 command: PIPE_COMMAND_MESSAGE,51 escapedCommand: PIPE_COMMAND_MESSAGE,7 unmodified linesmodified:lib/resolve/all-sync.js+1 added
1 import {isUint8Array, concatUint8Arrays} from '../utils/uint-array.js';2 import {stripNewline} from '../io/strip-newline.js';3 4+// Retrieve `result.all` with synchronous methods5 export const getAllSync = ([, stdout, stderr], options) => {6 if (!options.all) {7 return;8 }25 unmodified linesmodified:lib/resolve/exit-async.js+3 added
29 unmodified lines30 return waitForSubprocessExit(subprocess);31 }32 };33 34+// Retrieve the final exit code and|or signal name35 export const waitForSuccessfulExit = async exitPromise => {36 const [exitCode, signal] = await exitPromise;37 38 if (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {2 unmodified lines41 42 return [exitCode, signal];43 };44 45+// When the subprocess fails due to an `error` event46 const isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;47+// When the subprocess fails due to a non-0 exit code or to a signal termination48 export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;modified:lib/resolve/exit-sync.js+1 added
1 import {DiscardedError} from '../return/final-error.js';2 import {isMaxBufferSync} from '../io/max-buffer.js';3 import {isFailedExit} from './exit-async.js';4 5+// Retrieve exit code, signal name and error information, with synchronous methods6 export const getExitResultSync = ({error, status: exitCode, signal, output}, {maxBuffer}) => {7 const resultError = getResultError(error, exitCode, signal);8 const timedOut = resultError?.code === 'ETIMEDOUT';9 const isMaxBuffer = isMaxBufferSync(resultError, output, maxBuffer);16 unmodified linesmodified:lib/resolve/stdio.js+1 added
13 unmodified lines14 verboseInfo,15 streamInfo,16 }));17 18+// Read the contents of `subprocess.std*` or `subprocess.all` and|or wait for its completion19 export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {20 if (!stream) {21 return;22 }25 unmodified linesmodified:lib/resolve/wait-subprocess.js+3 added
93 unmodified lines94 isSameDirection: TRANSFORM_TYPES.has(type),95 stopOnExit: type === 'native',96 })));97 98+// Fails when the subprocess emits an `error` event99 const throwOnSubprocessError = async (subprocess, {signal}) => {100 const [error] = await once(subprocess, 'error', {signal});101 throw error;102 };103 104+// Fails right away when calling `subprocess.kill(error)`.105+// Does not wait for actual signal termination.106 const throwOnInternalError = async (subprocess, {signal}) => {107 const [error] = await once(subprocess, errorSignal, {signal});108 throw error;109 };modified:lib/return/duration.js+3 added
1 import {hrtime} from 'node:process';2 3+// Start counting time before spawning the subprocess4 export const getStartTime = () => hrtime.bigint();5 6+// Compute duration after the subprocess ended.7+// Printed by the `verbose` option.8 export const getDurationMs = startTime => Number(hrtime.bigint() - startTime) / 1e6;modified:lib/return/final-error.js+3 added
1+// When the subprocess fails, this is the error instance being returned.2+// If another error instance is being thrown, it is kept as `error.cause`.3 export const getFinalError = (originalError, message, isSync) => {4 const ErrorClass = isSync ? ExecaSyncError : ExecaError;5 const options = originalError instanceof DiscardedError ? {} : {cause: originalError};6 return new ErrorClass(message, options);24 unmodified lines31 const execaErrorSymbol = Symbol('isExecaError');32 33 export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';34 35+// We use two different Error classes for async/sync methods since they have slightly different shape and types36 export class ExecaError extends Error {}37 setErrorName(ExecaError, ExecaError.name);38 39 export class ExecaSyncError extends Error {}1 unmodified linemodified:lib/return/message.js+1 added
3 unmodified lines4 import {escapeLines} from '../arguments/escape.js';5 import {getMaxBufferMessage} from '../io/max-buffer.js';6 import {DiscardedError, isExecaError} from './final-error.js';7 8+// Computes `error.message`, `error.shortMessage` and `error.originalMessage`9 export const createMessages = ({10 stdio,11 all,12 originalError,89 unmodified linesmodified:lib/return/reject.js+2 added
1 import {logFinalResult} from '../verbose/complete.js';2 3+// Applies the `reject` option.4+// Also print the final log line with `verbose`.5 export const handleResult = (result, verboseInfo, {reject}) => {6 logFinalResult(result, reject, verboseInfo);7 8 if (result.failed && reject) {5 unmodified linesmodified:lib/return/result.js+3 added
1 unmodified line2 import {getDurationMs} from './duration.js';3 import {getFinalError} from './final-error.js';4 import {createMessages} from './message.js';5 6+// Object returned on subprocess success7 export const makeSuccessResult = ({8 command,9 escapedCommand,10 stdio,17 unmodified lines28 stdio,29 pipedFrom: [],30 });31 32+// Object returned on subprocess failure before spawning33 export const makeEarlyError = ({34 error,35 command,36 escapedCommand,13 unmodified lines50 options,51 isSync,52 });53 54+// Object returned on subprocess failure55 export const makeError = ({56 error: originalError,57 command,58 escapedCommand,67 unmodified linesmodified:lib/stdio/handle-async.js+2 added
11 unmodified lines12 const forbiddenIfAsync = ({type, optionName}) => {13 throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);14 };15 16+// Create streams used internally for piping when using specific values for the `std*` options, in async mode.17+// For example, `stdout: {file}` creates a file stream, which is piped from/to.18 const addProperties = {19 generator: generatorToStream,20 asyncGenerator: generatorToStream,21 nodeStream: ({value}) => ({stream: value}),45 unmodified linesmodified:lib/stdio/handle-sync.js+2 added
20 unmodified lines21 const throwInvalidSyncValue = (optionName, value) => {22 throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`);23 };24 25+// Create streams used internally for redirecting when using specific values for the `std*` options, in sync mode.26+// For example, `stdin: {file}` reads the file synchronously, then passes it as the `input` option.27 const addProperties = {28 generator() {},29 asyncGenerator: forbiddenIfSync,30 webStream: forbiddenIfSync,26 unmodified linesmodified:lib/stdio/handle.js+5 added-3 removed
11 unmodified lines12 import {handleNativeStream} from './native.js';13 import {handleInputOptions} from './input-option.js';14 15 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode16+// They are converted into an array of `fileDescriptors`.17+// Each `fileDescriptor` is normalized, validated and contains all information necessary for further handling.18 export const handleStdio = (addProperties, options, verboseInfo, isSync) => {19 const stdio = normalizeStdioOption(options, isSync);20 const fileDescriptors = stdio.map((stdioOption, fdNumber) => getFileDescriptor({21 stdioOption,5 unmodified lines27 options.stdio = fileDescriptors.map(({stdioItems}) => forwardStdio(stdioItems));28 return fileDescriptors;29 };30 29-// We make sure passing an array with a single item behaves the same as passing that item without an array.30-// This is what users would expect.31-// For example, `stdout: ['ignore']` behaves the same as `stdout: 'ignore'`.31 const getFileDescriptor = ({stdioOption, fdNumber, addProperties, options, isSync}) => {32 const optionName = getStreamName(fdNumber);33 const {stdioItems: initialStdioItems, isStdioArray} = initializeStdioItems({34 stdioOption,15 unmodified lines50 const finalStdioItems = normalizedStdioItems.map(stdioItem => addStreamProperties(stdioItem, addProperties, direction, options));51 return {direction, objectMode, stdioItems: finalStdioItems};52 };53 54+// We make sure passing an array with a single item behaves the same as passing that item without an array.55+// This is what users would expect.56+// For example, `stdout: ['ignore']` behaves the same as `stdout: 'ignore'`.57 const initializeStdioItems = ({stdioOption, fdNumber, options, optionName}) => {58 const values = Array.isArray(stdioOption) ? stdioOption : [stdioOption];59 const initialStdioItems = [60 ...values.map(value => initializeStdioItem(value, optionName)),89 unmodified linesmodified:lib/stdio/native.js+2 added
20 unmodified lines21 ? handleNativeStreamSync({stdioItem, fdNumber, direction})22 : handleNativeStreamAsync({stdioItem, fdNumber});23 };24 25+// Synchronous methods use a different logic.26+// 'inherit', file descriptors and process.std* are handled by readFileSync()/writeFileSync().27 const handleNativeStreamSync = ({stdioItem, stdioItem: {value, optionName}, fdNumber, direction}) => {28 const targetFd = getTargetFd({29 value,30 optionName,76 unmodified linesmodified:lib/stdio/stdio-option.js+5 added-1 removed
1 import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';2 3-// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`3+// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`.4+// Also normalize the `stdio` option.5 export const normalizeStdioOption = ({stdio, ipc, buffer, verbose, ...options}, isSync) => {6 const stdioArray = getStdioArray(stdio, options).map((stdioOption, fdNumber) => addDefaultValue(stdioOption, fdNumber));7 return isSync ? normalizeStdioSync(stdioArray, buffer, verbose) : normalizeStdioAsync(stdioArray, ipc);8 };32 unmodified lines41 42 return stdioOption;43 };44 45+// Using `buffer: false` with synchronous methods implies `stdout`/`stderr`: `ignore`.46+// Unless the output is needed, e.g. due to `verbose: 'full'` or to redirecting to a file.47 const normalizeStdioSync = (stdioArray, buffer, verbose) => stdioArray.map((stdioOption, fdNumber) =>48 !buffer[fdNumber]49 && fdNumber !== 050 && verbose[fdNumber] !== 'full'3 unmodified lines54 55 const isOutputPipeOnly = stdioOption => stdioOption === 'pipe'56 || (Array.isArray(stdioOption) && stdioOption.every(item => item === 'pipe'));57 58+// The `ipc` option adds an `ipc` item to the `stdio` option59 const normalizeStdioAsync = (stdioArray, ipc) => ipc && !stdioArray.includes('ipc')60 ? [...stdioArray, 'ipc']61 : stdioArray;modified:lib/stdio/type.js+2 added
140 unmodified lines141 const isAsyncIterableObject = value => isObject(value) && typeof value[Symbol.asyncIterator] === 'function';142 const isIterableObject = value => isObject(value) && typeof value[Symbol.iterator] === 'function';143 const isObject = value => typeof value === 'object' && value !== null;144 145+// 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 150 // Convert types to human-friendly strings for error messages151 export const TYPE_TO_MESSAGE = {14 unmodified linesmodified:lib/terminate/cleanup.js+1 added-1 removed
1 import {addAbortListener} from 'node:events';2 import {onExit} from 'signal-exit';3 4-// `cleanup` option handling4+// If the `cleanup` option is used, call `subprocess.kill()` when the parent process exits5 export const cleanupOnExit = (subprocess, {cleanup, detached}, {signal}) => {6 if (!cleanup || detached) {7 return;8 }8 unmodified linesmodified:lib/terminate/kill.js+1 added
1 import os from 'node:os';2 import {setTimeout} from 'node:timers/promises';3 import {isErrorInstance} from '../return/final-error.js';4 5+// Normalize the `forceKillAfterDelay` option6 export const normalizeForceKillAfterDelay = forceKillAfterDelay => {7 if (forceKillAfterDelay === false) {8 return forceKillAfterDelay;9 }79 unmodified linesmodified:lib/terminate/timeout.js+2 added-1 removed
1 import {setTimeout} from 'node:timers/promises';2 import {DiscardedError} from '../return/final-error.js';3 4+// Validate `timeout` option5 export const validateTimeout = ({timeout}) => {6 if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {7 throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);8 }9 };10 10-// `timeout` option handling11+// Fails when the `timeout` option is exceeded12 export const throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === undefined13 ? []14 : [killAfterTimeout(subprocess, timeout, context, controller)];15 6 unmodified linesmodified:lib/transform/encoding-transform.js+1 added-2 removed
1 unmodified line2 import {StringDecoder} from 'node:string_decoder';3 import {isUint8Array, bufferToUint8Array} from '../utils/uint-array.js';4 5 /*6-When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.7-This allows generator functions to operate with those types instead.6+When using binary encodings, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.7 Chunks might be Buffer, Uint8Array or strings since:8 - `subprocess.stdout|stderr` emits Buffers9 - `subprocess.stdin.write()` accepts Buffer, Uint8Array or string10 - Previous generators might return Uint8Array or string43 unmodified linesmodified:lib/transform/generator.js+2 added
69 unmodified lines70 });71 return {stream};72 };73 74+// Applies transform generators in sync mode75 export const runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => {76 const generators = stdioItems.filter(({type}) => type === 'generator');77 const reversedGenerators = isInput ? generators.reverse() : generators;78 4 unmodified lines83 84 return chunks;85 };86 87+// Generators used internally to convert the chunk type, validate it, and split into lines88 const addInternalGenerators = (89 {transform, final, binary, writableObjectMode, readableObjectMode, preserveNewlines},90 encoding,91 optionName,16 unmodified linesmodified:lib/transform/run-async.js+1 added
1 import {callbackify} from 'node:util';2 3+// Applies a series of generator functions asynchronously4 export const pushChunks = callbackify(async (getChunks, state, getChunksArguments, transformStream) => {5 state.currentIterable = getChunks(...getChunksArguments);6 7 try {53 unmodified linesmodified:lib/transform/run-sync.js+1 added-1 removed
1-// Duplicate the code from `transform-async.js` but as synchronous functions1+// Duplicate the code from `run-async.js` but as synchronous functions2 export const pushChunksSync = (getChunksSync, getChunksArguments, transformStream, done) => {3 try {4 for (const chunk of getChunksSync(...getChunksArguments)) {5 transformStream.push(chunk);45 unmodified linesmodified:lib/transform/split.js+1 added
1 unmodified line2 export const getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped3 ? undefined4 : initializeSplitLines(preserveNewlines, state);5 6+// Same but for synchronous methods7 export const splitLinesSync = (chunk, preserveNewlines, objectMode) => objectMode8 ? chunk.flatMap(item => splitLinesItemSync(item, preserveNewlines))9 : splitLinesItemSync(chunk, preserveNewlines);10 100 unmodified linesmodified:lib/transform/validate.js+2 added
1 import {Buffer} from 'node:buffer';2 import {isUint8Array} from '../utils/uint-array.js';3 4+// Validate the type of chunk argument passed to transform generators5 export const getValidateTransformInput = (writableObjectMode, optionName) => writableObjectMode6 ? undefined7 : validateStringTransformInput.bind(undefined, optionName);8 4 unmodified lines13 14 yield chunk;15 };16 17+// Validate the type of the value returned by transform generators18 export const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode19 ? validateObjectTransformReturn.bind(undefined, optionName)20 : validateStringTransformReturn.bind(undefined, optionName);21 23 unmodified linesmodified:lib/utils/max-listeners.js+1 added
1 import {addAbortListener} from 'node:events';2 3+// Temporarily increase the maximum number of listeners on an eventEmitter4 export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {5 const maxListeners = eventEmitter.getMaxListeners();6 if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {7 return;7 unmodified linesmodified:lib/verbose/info.js+3 added
1 import {debuglog} from 'node:util';2 3+// Default value for the `verbose` option4 export const verboseDefault = debuglog('execa').enabled ? 'full' : 'none';5 6+// Information computed before spawning, used by the `verbose` option7 export const getVerboseInfo = verbose => {8 const verboseId = isVerbose(verbose) ? VERBOSE_ID++ : undefined;9 return {verbose, verboseId};10 };4 unmodified lines15 // As a pro, it is shorter than a normal PID and never re-uses the same id.16 // As a con, it cannot be used to send signals.17 let VERBOSE_ID = 0n;18 19+// The `verbose` option can have different values for `stdout`/`stderr`20 export const isVerbose = verbose => verbose.some(fdVerbose => fdVerbose !== 'none');modified:lib/verbose/output.js+2 added
22 unmodified lines23 const fdUsesVerbose = fdNumber => fdNumber === 1 || fdNumber === 2;24 25 const PIPED_STDIO_VALUES = new Set(['pipe', 'overlapped']);26 27+// `verbose` printing logic with async methods28 export const logLines = async (linesIterable, stream, verboseInfo) => {29 for await (const line of linesIterable) {30 if (!isPipingStream(stream)) {31 logLine(line, verboseInfo);32 }33 }34 };35 36+// `verbose` printing logic with sync methods37 export const logLinesSync = (linesArray, verboseInfo) => {38 for (const line of linesArray) {39 logLine(line, verboseInfo);40 }21 unmodified linesmodified:test/arguments/cwd.js+1 added
69 unmodified lines70 }71 72 const cwdNotExisting = {cwd: 'does_not_exist', expectedCode: 'ENOENT', expectedMessage: 'The "cwd" option is invalid'};73 const cwdTooLong = {cwd: '.'.repeat(1e5), expectedCode: 'ENAMETOOLONG', expectedMessage: 'The "cwd" option is invalid'};74+// @todo: use import.meta.dirname after dropping support for Node <20.11.075 const cwdNotDirectory = {cwd: fileURLToPath(import.meta.url), expectedCode: isWindows ? 'ENOENT' : 'ENOTDIR', expectedMessage: 'The "cwd" option is not a directory'};76 77 const testCwdPostSpawn = async (t, {cwd, expectedCode, expectedMessage}, execaMethod) => {78 const {failed, code, message} = await execaMethod('empty.js', {cwd, reject: false});26 unmodified linesmodified:test/helpers/fixtures-directory.js+1 added
3 unmodified lines4 import pathKey from 'path-key';5 6 export const PATH_KEY = pathKey();7 export const FIXTURES_DIRECTORY_URL = new URL('../fixtures/', import.meta.url);8+// @todo: use import.meta.dirname after dropping support for Node <20.11.09 export const FIXTURES_DIRECTORY = resolve(fileURLToPath(FIXTURES_DIRECTORY_URL));10 11 // Add the fixtures directory to PATH so fixtures can be executed without adding12 // `node`. This is only meant to make writing tests simpler.4 unmodified linesmodified:test/methods/parameters-command.js+1 added
70 unmodified lines71 test('$\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $);72 test('$.sync\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $.sync);73 74 const testRelativePath = async (t, execaMethod) => {75+ // @todo: use import.meta.dirname after dropping support for Node <20.11.076 const rootDirectory = basename(fileURLToPath(new URL('../..', import.meta.url)));77 const pathViaParentDirectory = join('..', rootDirectory, 'test', 'fixtures', 'noop.js');78 const {stdout} = await execaMethod(pathViaParentDirectory);79 t.is(stdout, foobarString);9 unmodified lines