Skip to content
Myr

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

60 files+148 added−13 removed

modified:lib/arguments/command.js+1 added
modified:lib/arguments/cwd.js+2 added
modified:lib/arguments/encoding-option.js+1 added
modified:lib/arguments/escape.js+2 added
modified:lib/arguments/fd-options.js+3 added
1import {parseFd} from './specific.js';23// Retrieve stream targeted by the `to` option4export 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 lines
1314 return destinationStream;15};1617// Retrieve stream targeted by the `from` option18export 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 lines
2728 return sourceStream;29};3031// Keeps track of the options passed to each Execa call32export const SUBPROCESS_OPTIONS = new WeakMap();3334const getFdNumber = (fileDescriptors, fdName, isWritable) => {35 const fdNumber = parseFdNumber(fdName, isWritable);
73 unmodified lines
modified:lib/arguments/file-url.js+2 added
modified:lib/arguments/options.js+2 added
8 unmodified lines
9import {normalizeCwd} from './cwd.js';10import {normalizeFileUrl} from './file-url.js';11import {normalizeFdSpecificOptions} from './specific.js';1213// Normalize the options object, and sometimes also the file paths and arguments.14// Applies default values, validate allowed options, normalize them.15export const normalizeOptions = (filePath, rawArguments, rawOptions) => {16 rawOptions.cwd = normalizeCwd(rawOptions.cwd);17 const [processedFile, processedArguments, processedOptions] = handleNodeOption(filePath, rawArguments, rawOptions);18
66 unmodified lines
modified:lib/arguments/specific.js+5 added
1import isPlainObject from 'is-plain-obj';2import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';3import {verboseDefault} from '../verbose/info.js';45// 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']}`8export const normalizeFdSpecificOptions = options => {9 const optionsCopy = {...options};1011 for (const optionName of FD_SPECIFIC_OPTIONS) {
52 unmodified lines
6465 return fdNumber === 'all' ? [1, 2] : [fdNumber];66};6768// Use the same syntax for fd-specific options and the `from`/`to` options69export const parseFd = fdName => {70 if (fdName === 'all') {71 return fdName;72 }
21 unmodified lines
94 verbose: verboseDefault,95 stripFinalNewline: true,96};9798// List of options which can have different values for `stdout`/`stderr`99export const FD_SPECIFIC_OPTIONS = ['lines', 'buffer', 'maxBuffer', 'verbose', 'stripFinalNewline'];
modified:lib/convert/add.js+1 added
2 unmodified lines
3import {createWritable} from './writable.js';4import {createDuplex} from './duplex.js';5import {createIterable} from './iterable.js';67// Add methods to convert the subprocess to a stream or iterable8export 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 lines
modified:lib/convert/duplex.js+1 added-1 removed
13 unmodified lines
14 onStdinFinished,15 onWritableDestroy,16} from './writable.js';1718// Create a `Duplex` stream combining both18// Create a `Duplex` stream combining both `subprocess.readable()` and `subprocess.writable()`19export 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 lines
modified:lib/convert/iterable.js+1 added
1import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';2import {getFromStream} from '../arguments/fd-options.js';3import {iterateOnSubprocessStream} from '../io/iterate.js';45// Convert the subprocess to an async iterable6export const createIterable = (subprocess, encoding, {7 from,8 binary: binaryOption = false,9 preserveNewlines = false,
25 unmodified lines
modified:lib/io/contents.js+2 added
4 unmodified lines
5import {iterateForResult} from './iterate.js';6import {handleMaxBuffer} from './max-buffer.js';7import {getStripFinalNewline} from './strip-newline.js';89// Retrieve `result.stdout|stderr|all|stdio[*]`10export 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 lines
91 return handleBufferedData(error);92 }93};9495// Ensure we are returning Uint8Arrays when using `encoding: 'buffer'`96const handleBufferedData = ({bufferedData}) => isArrayBuffer(bufferedData)97 ? new Uint8Array(bufferedData)98 : bufferedData;
modified:lib/io/max-buffer.js+6 added
1import {MaxBufferError} from 'get-stream';2import {getStreamName} from '../utils/standard-stream.js';34// When the `maxBuffer` option is hit, a MaxBufferError is thrown.5// The stream is aborted, then specific information is kept for the error message.6export const handleMaxBuffer = ({error, stream, readableObjectMode, lines, encoding, fdNumber}) => {7 if (!(error instanceof MaxBufferError)) {8 throw error;9 }
23 unmodified lines
3334 return 'characters';35};3637// Error message when `maxBuffer` is hit38export 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 lines
49 delete error.maxBufferInfo;50 return {streamName: getStreamName(fdNumber), threshold: maxBuffer[fdNumber], unit};51};5253// 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.56export const isMaxBufferSync = (resultError, output, maxBuffer) => resultError?.code === 'ENOBUFS'57 && output !== null58 && output.some(result => result !== null && result.length > getMaxBufferSync(maxBuffer));59
12 unmodified lines
modified:lib/io/output-async.js+3 added-1 removed
30 unmodified lines
31 pipeStreams(inputStream, subprocess.stdio[fdNumber]);32 }33};3435// `subprocess.stdin|stdout|stderr|stdio` is directly mutated.35// When using transforms, `subprocess.stdin|stdout|stderr|stdio` is directly mutated36const pipeTransform = (subprocess, stream, direction, fdNumber) => {37 if (direction === 'output') {38 pipeStreams(subprocess.stdio[fdNumber], stream);39 } else {
9 unmodified lines
49};5051const SUBPROCESS_STREAM_PROPERTIES = ['stdin', 'stdout', 'stderr'];5253// Most `std*` option values involve piping `subprocess.std*` to a stream.54// The stream is either passed by the user or created internally.55const pipeStdioItem = ({subprocess, stream, direction, fdNumber, inputStreamsGroups, controller}) => {56 if (stream === undefined) {57 return;58 }
22 unmodified lines
modified:lib/io/output-sync.js+5 added
65 unmodified lines
66 return returnedResult;67 }68};6970// Applies transform generators to `stdout`/`stderr`71const runOutputGeneratorsSync = (chunks, stdioItems, encoding, state) => {72 try {73 return runGeneratorsSync(chunks, stdioItems, encoding, false);74 } catch (error) {
1 unmodified line
76 return chunks;77 }78};7980// 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*`83const serializeChunks = ({chunks, objectMode, encoding, lines, stripFinalNewline, fdNumber}) => {84 if (objectMode) {85 return {serializedResult: chunks};86 }
9 unmodified lines
9697 return {serializedResult};98};99100// When the `std*` target is a file path/URL or a file descriptor101const writeToFiles = (serializedResult, stdioItems) => {102 for (const {type, path} of stdioItems) {103 if (FILE_TYPES.has(type)) {104 writeFileSync(path, serializedResult);
3 unmodified lines
modified:lib/io/pipeline.js+1 added-1 removed
1import {finished} from 'node:stream/promises';2import {isStandardStream} from '../utils/standard-stream.js';34// Like `Stream.pipeline(source, destination)`, but does not destroy standard streams.4// Similar to `Stream.pipeline(source, destination)`, but does not destroy standard streams5export const pipeStreams = (source, destination) => {6 source.pipe(destination);7 onSourceFinish(source, destination);8 onDestinationFinish(source, destination);
40 unmodified lines
modified:lib/io/strip-newline.js+3 added
1import stripFinalNewlineFunction from 'strip-final-newline';23// 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.5export const stripNewline = (value, {stripFinalNewline}, fdNumber) => getStripFinalNewline(stripFinalNewline, fdNumber) && value !== undefined && !Array.isArray(value)6 ? stripFinalNewlineFunction(value)7 : value;89// Retrieve `stripFinalNewline` option value, including with `subprocess.all`10export 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()`2export const mapCommandAsync = ({file, commandArguments}) => parseCommand(file, commandArguments);34// Main logic for `execaCommandSync()`5export const mapCommandSync = ({file, commandArguments}) => ({...parseCommand(file, commandArguments), isSync: true});67// Convert `execaCommand(command)` into `execa(file, ...commandArguments)`8const 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 lines
modified:lib/methods/create.js+5 added
3 unmodified lines
4import {execaCoreSync} from './main-sync.js';5import {execaCoreAsync} from './main-async.js';6import {mergeOptions} from './bind.js';78// 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.13export 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 lines
modified:lib/methods/main-async.js+5 added-1 removed
17 unmodified lines
18import {waitForSubprocessResult} from '../resolve/wait-subprocess.js';19import {addConvertedStreams} from '../convert/add.js';20import {mergePromise} from './promise.js';2122// Main shared logic for all async methods: `execa()`, `execaCommand()`, `$`, `execaNode()`23export 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 lines
42 SUBPROCESS_OPTIONS.set(subprocess, {options, fileDescriptors});43 return subprocess;44};4546// Compute arguments to pass to `child_process.spawn()`47const handleAsyncArguments = (rawFile, rawArguments, rawOptions) => {48 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArguments, rawOptions);4950 try {
15 unmodified lines
66 throw error;67 }68};6970// 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()`.72const 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 lines
122 });123 return {subprocess, promise};124};125126// Asynchronous logic, as opposed to the previous logic which can be run synchronously, i.e. can be returned to user right away127const handlePromise = async ({subprocess, options, startTime, verboseInfo, fileDescriptors, originalStreams, command, escapedCommand, controller}) => {128 const context = {timedOut: false};129130 const [errorInfo, [exitCode, signal], stdioResults, allResult] = await waitForSubprocessResult({
51 unmodified lines
modified:lib/methods/main-sync.js+5 added
10 unmodified lines
11import {logEarlyResult} from '../verbose/complete.js';12import {getAllSync} from '../resolve/all-sync.js';13import {getExitResultSync} from '../resolve/exit-sync.js';1415// Main shared logic for all sync methods: `execaSync()`, `execaCommandSync()`, `$.sync()`16export 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 lines
27 });28 return handleResult(result, verboseInfo, options);29};3031// Compute arguments to pass to `child_process.spawnSync()`32const handleSyncArguments = (rawFile, rawArguments, rawOptions) => {33 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArguments, rawOptions);3435 try {
16 unmodified lines
52 throw error;53 }54};5556// Options normalization logic specific to sync methods57const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;5859// Options validation logic specific to sync methods60const validateSyncOptions = ({ipc, detached, cancelSignal}) => {61 if (ipc) {62 throwInvalidSyncOption('ipc: true');63 }
67 unmodified lines
131 });132 }133};134135// The `encoding` option is handled by Execa, not by `child_process.spawnSync()`136const normalizeSpawnSyncOptions = ({encoding, maxBuffer, ...options}) => ({...options, encoding: 'buffer', maxBuffer: getMaxBufferSync(maxBuffer)});137138const getSyncResult = ({error, exitCode, signal, timedOut, isMaxBuffer, stdio, all, options, command, escapedCommand, startTime}) => error === undefined139 ? makeSuccessResult({
22 unmodified lines
modified:lib/methods/node.js+4 added
1import {execPath, execArgv} from 'node:process';2import {basename, resolve} from 'node:path';3import {safeNormalizeFileUrl} from '../arguments/file-url.js';45// `execaNode()` is a shortcut for `execa(..., {node: true})`6export const mapNode = ({options}) => {7 if (options.node === false) {8 throw new TypeError('The "node" option cannot be false with `execaNode()`.');9 }1011 return {options: {...options, node: true}};12};1314// 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`.17export const handleNodeOption = (file, commandArguments, {18 node: shouldHandleNode = false,19 nodePath = execPath,20 nodeOptions = execArgv.filter(nodeOption => !nodeOption.startsWith('--inspect')),
31 unmodified lines
modified:lib/methods/parameters.js+2 added
1import isPlainObject from 'is-plain-obj';2import {safeNormalizeFileUrl} from '../arguments/file-url.js';34// The command `arguments` and `options` are both optional.5// This also does basic validation on them and on the command file.6export const normalizeParameters = (rawFile, rawArguments = [], rawOptions = {}) => {7 const filePath = safeNormalizeFileUrl(rawFile, 'First argument');8 const [commandArguments, options] = isPlainObject(rawArguments)9 ? [[], rawArguments]
22 unmodified lines
modified:lib/methods/script.js+7 added
1// Sets `$.sync` and `$.s`2export const setScriptSync = (boundExeca, createNested, boundOptions) => {3 boundExeca.sync = createNested(mapScriptSync, boundOptions);4 boundExeca.s = boundExeca.sync;5};67// Main logic for `$`8export const mapScriptAsync = ({options}) => getScriptOptions(options);910// Main logic for `$.sync`11const mapScriptSync = ({options}) => ({...getScriptOptions(options), isSync: true});1213// `$` is like `execa` but with script-friendly options: `{stdin: 'inherit', preferLocal: true}`14const getScriptOptions = options => ({options: {...getScriptStdinOption(options), ...options}});1516const getScriptStdinOption = ({input, inputFile, stdio}) => input === undefined && inputFile === undefined && stdio === undefined17 ? {stdin: 'inherit'}18 : {};1920// 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.22export const deepScriptOptions = {preferLocal: true};
modified:lib/methods/template.js+3 added
1import {ChildProcess} from 'node:child_process';2import isPlainObject from 'is-plain-obj';3import {isUint8Array, uint8ArrayToString} from '../utils/uint-array.js';45// Check whether the template string syntax is being used6export const isTemplateString = templates => Array.isArray(templates) && Array.isArray(templates.raw);78// Convert execa`file ...commandArguments` to execa(file, commandArguments)9export const parseTemplates = (templates, expressions) => {10 let tokens = [];1112 for (const [index, template] of templates.entries()) {
94 unmodified lines
107 `${tokens.at(-1)}${nextTokens[0]}`,108 ...nextTokens.slice(1),109 ];110111// Handle `${expression}` inside the template string syntax112const parseExpression = expression => {113 const typeOfExpression = typeof expression;114115 if (typeOfExpression === 'string') {
34 unmodified lines
modified:lib/pipe/abort.js+2 added
1import {aborted} from 'node:util';2import {createNonCommandError} from './throw.js';34// When passing an `unpipeSignal` option, abort piping when the signal is aborted.5// However, do not terminate the subprocesses.6export const unpipeOnAbort = (unpipeSignal, unpipeContext) => unpipeSignal === undefined7 ? []8 : [unpipeOnSignalAbort(unpipeSignal, unpipeContext)];9
11 unmodified lines
modified:lib/pipe/pipe-arguments.js+6 added
1import {normalizeParameters} from '../methods/parameters.js';2import {getStartTime} from '../return/duration.js';3import {SUBPROCESS_OPTIONS, getToStream, getFromStream} from '../arguments/fd-options.js';45// Normalize and validate arguments passed to `source.pipe(destination)`6export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...pipeArguments) => {7 const startTime = getStartTime();8 const {9 destination,
35 unmodified lines
45 return {destinationError: error};46 }47};4849// 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)53const 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 lines
7677 throw new TypeError(`The first argument must be a template string, an options object, or an Execa subprocess: ${firstArgument}`);78};7980// Force `stdin: 'pipe'` with the destination subprocess81const mapDestinationArguments = ({options}) => ({options: {...options, stdin: 'pipe', piped: true}});8283const getSourceStream = (source, from) => {84 try {
6 unmodified lines
modified:lib/pipe/setup.js+1 added
23 unmodified lines
24 });25 return promise;26};2728// Asynchronous logic when piping subprocesses29const handlePipePromise = async ({30 sourcePromise,31 sourceStream,32 sourceOptions,
40 unmodified lines
modified:lib/pipe/throw.js+3 added
1import {makeEarlyError} from '../return/result.js';2import {abortSourceStream, endDestinationStream} from '../io/pipeline.js';34// When passing invalid arguments to `source.pipe()`, throw asynchronously.5// We also abort both subprocesses.6export const handlePipeArgumentsError = ({7 sourceStream,8 sourceError,9 destinationStream,
33 unmodified lines
43 return sourceError;44 }45};4647// Specific error return value when passing invalid arguments to `subprocess.pipe()` or when using `unpipeSignal`48export const createNonCommandError = ({error, fileDescriptors, sourceOptions, startTime}) => makeEarlyError({49 error,50 command: PIPE_COMMAND_MESSAGE,51 escapedCommand: PIPE_COMMAND_MESSAGE,
7 unmodified lines
modified:lib/resolve/all-sync.js+1 added
1import {isUint8Array, concatUint8Arrays} from '../utils/uint-array.js';2import {stripNewline} from '../io/strip-newline.js';34// Retrieve `result.all` with synchronous methods5export const getAllSync = ([, stdout, stderr], options) => {6 if (!options.all) {7 return;8 }
25 unmodified lines
modified:lib/resolve/exit-async.js+3 added
29 unmodified lines
30 return waitForSubprocessExit(subprocess);31 }32};3334// Retrieve the final exit code and|or signal name35export const waitForSuccessfulExit = async exitPromise => {36 const [exitCode, signal] = await exitPromise;3738 if (!isSubprocessErrorExit(exitCode, signal) && isFailedExit(exitCode, signal)) {
2 unmodified lines
4142 return [exitCode, signal];43};4445// When the subprocess fails due to an `error` event46const isSubprocessErrorExit = (exitCode, signal) => exitCode === undefined && signal === undefined;47// When the subprocess fails due to a non-0 exit code or to a signal termination48export const isFailedExit = (exitCode, signal) => exitCode !== 0 || signal !== null;
modified:lib/resolve/exit-sync.js+1 added
1import {DiscardedError} from '../return/final-error.js';2import {isMaxBufferSync} from '../io/max-buffer.js';3import {isFailedExit} from './exit-async.js';45// Retrieve exit code, signal name and error information, with synchronous methods6export 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 lines
modified:lib/resolve/stdio.js+1 added
13 unmodified lines
14 verboseInfo,15 streamInfo,16}));1718// Read the contents of `subprocess.std*` or `subprocess.all` and|or wait for its completion19export const waitForSubprocessStream = async ({stream, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {20 if (!stream) {21 return;22 }
25 unmodified lines
modified:lib/resolve/wait-subprocess.js+3 added
93 unmodified lines
94 isSameDirection: TRANSFORM_TYPES.has(type),95 stopOnExit: type === 'native',96 })));9798// Fails when the subprocess emits an `error` event99const throwOnSubprocessError = async (subprocess, {signal}) => {100 const [error] = await once(subprocess, 'error', {signal});101 throw error;102};103104// Fails right away when calling `subprocess.kill(error)`.105// Does not wait for actual signal termination.106const throwOnInternalError = async (subprocess, {signal}) => {107 const [error] = await once(subprocess, errorSignal, {signal});108 throw error;109};
modified:lib/return/duration.js+3 added
1import {hrtime} from 'node:process';23// Start counting time before spawning the subprocess4export const getStartTime = () => hrtime.bigint();56// Compute duration after the subprocess ended.7// Printed by the `verbose` option.8export 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`.3export 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 lines
31const execaErrorSymbol = Symbol('isExecaError');3233export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';3435// We use two different Error classes for async/sync methods since they have slightly different shape and types36export class ExecaError extends Error {}37setErrorName(ExecaError, ExecaError.name);3839export class ExecaSyncError extends Error {}
1 unmodified line
modified:lib/return/message.js+1 added
3 unmodified lines
4import {escapeLines} from '../arguments/escape.js';5import {getMaxBufferMessage} from '../io/max-buffer.js';6import {DiscardedError, isExecaError} from './final-error.js';78// Computes `error.message`, `error.shortMessage` and `error.originalMessage`9export const createMessages = ({10 stdio,11 all,12 originalError,
89 unmodified lines
modified:lib/return/reject.js+2 added
1import {logFinalResult} from '../verbose/complete.js';23// Applies the `reject` option.4// Also print the final log line with `verbose`.5export const handleResult = (result, verboseInfo, {reject}) => {6 logFinalResult(result, reject, verboseInfo);78 if (result.failed && reject) {
5 unmodified lines
modified:lib/return/result.js+3 added
1 unmodified line
2import {getDurationMs} from './duration.js';3import {getFinalError} from './final-error.js';4import {createMessages} from './message.js';56// Object returned on subprocess success7export const makeSuccessResult = ({8 command,9 escapedCommand,10 stdio,
17 unmodified lines
28 stdio,29 pipedFrom: [],30});3132// Object returned on subprocess failure before spawning33export const makeEarlyError = ({34 error,35 command,36 escapedCommand,
13 unmodified lines
50 options,51 isSync,52});5354// Object returned on subprocess failure55export const makeError = ({56 error: originalError,57 command,58 escapedCommand,
67 unmodified lines
modified:lib/stdio/handle-async.js+2 added
11 unmodified lines
12const forbiddenIfAsync = ({type, optionName}) => {13 throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);14};1516// 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.18const addProperties = {19 generator: generatorToStream,20 asyncGenerator: generatorToStream,21 nodeStream: ({value}) => ({stream: value}),
45 unmodified lines
modified:lib/stdio/handle-sync.js+2 added
20 unmodified lines
21const throwInvalidSyncValue = (optionName, value) => {22 throw new TypeError(`The \`${optionName}\` option cannot be ${value} with synchronous methods.`);23};2425// 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.27const addProperties = {28 generator() {},29 asyncGenerator: forbiddenIfSync,30 webStream: forbiddenIfSync,
26 unmodified lines
modified:lib/stdio/handle.js+5 added-3 removed
11 unmodified lines
12import {handleNativeStream} from './native.js';13import {handleInputOptions} from './input-option.js';1415// 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.18export const handleStdio = (addProperties, options, verboseInfo, isSync) => {19 const stdio = normalizeStdioOption(options, isSync);20 const fileDescriptors = stdio.map((stdioOption, fdNumber) => getFileDescriptor({21 stdioOption,
5 unmodified lines
27 options.stdio = fileDescriptors.map(({stdioItems}) => forwardStdio(stdioItems));28 return fileDescriptors;29};3029// 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'`.31const getFileDescriptor = ({stdioOption, fdNumber, addProperties, options, isSync}) => {32 const optionName = getStreamName(fdNumber);33 const {stdioItems: initialStdioItems, isStdioArray} = initializeStdioItems({34 stdioOption,
15 unmodified lines
50 const finalStdioItems = normalizedStdioItems.map(stdioItem => addStreamProperties(stdioItem, addProperties, direction, options));51 return {direction, objectMode, stdioItems: finalStdioItems};52};5354// 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'`.57const 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 lines
modified:lib/stdio/native.js+2 added
20 unmodified lines
21 ? handleNativeStreamSync({stdioItem, fdNumber, direction})22 : handleNativeStreamAsync({stdioItem, fdNumber});23};2425// Synchronous methods use a different logic.26// 'inherit', file descriptors and process.std* are handled by readFileSync()/writeFileSync().27const handleNativeStreamSync = ({stdioItem, stdioItem: {value, optionName}, fdNumber, direction}) => {28 const targetFd = getTargetFd({29 value,30 optionName,
76 unmodified lines
modified:lib/stdio/stdio-option.js+5 added-1 removed
1import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';23// 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.5export 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 lines
4142 return stdioOption;43};4445// 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.47const normalizeStdioSync = (stdioArray, buffer, verbose) => stdioArray.map((stdioOption, fdNumber) =>48 !buffer[fdNumber]49 && fdNumber !== 050 && verbose[fdNumber] !== 'full'
3 unmodified lines
5455const isOutputPipeOnly = stdioOption => stdioOption === 'pipe'56 || (Array.isArray(stdioOption) && stdioOption.every(item => item === 'pipe'));5758// The `ipc` option adds an `ipc` item to the `stdio` option59const normalizeStdioAsync = (stdioArray, ipc) => ipc && !stdioArray.includes('ipc')60 ? [...stdioArray, 'ipc']61 : stdioArray;
modified:lib/stdio/type.js+2 added
140 unmodified lines
141const isAsyncIterableObject = value => isObject(value) && typeof value[Symbol.asyncIterator] === 'function';142const isIterableObject = value => isObject(value) && typeof value[Symbol.iterator] === 'function';143const isObject = value => typeof value === 'object' && value !== null;144145// Types which modify `subprocess.std*`146export const TRANSFORM_TYPES = new Set(['generator', 'asyncGenerator', 'duplex', 'webTransform']);147// Types which write to a file or a file descriptor148export const FILE_TYPES = new Set(['fileUrl', 'filePath', 'fileNumber']);149150// Convert types to human-friendly strings for error messages151export const TYPE_TO_MESSAGE = {
14 unmodified lines
modified:lib/terminate/cleanup.js+1 added-1 removed
1import {addAbortListener} from 'node:events';2import {onExit} from 'signal-exit';34// `cleanup` option handling4// If the `cleanup` option is used, call `subprocess.kill()` when the parent process exits5export const cleanupOnExit = (subprocess, {cleanup, detached}, {signal}) => {6 if (!cleanup || detached) {7 return;8 }
8 unmodified lines
modified:lib/terminate/kill.js+1 added
1import os from 'node:os';2import {setTimeout} from 'node:timers/promises';3import {isErrorInstance} from '../return/final-error.js';45// Normalize the `forceKillAfterDelay` option6export const normalizeForceKillAfterDelay = forceKillAfterDelay => {7 if (forceKillAfterDelay === false) {8 return forceKillAfterDelay;9 }
79 unmodified lines
modified:lib/terminate/timeout.js+2 added-1 removed
1import {setTimeout} from 'node:timers/promises';2import {DiscardedError} from '../return/final-error.js';34// Validate `timeout` option5export 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};1010// `timeout` option handling11// Fails when the `timeout` option is exceeded12export const throwOnTimeout = (subprocess, timeout, context, controller) => timeout === 0 || timeout === undefined13 ? []14 : [killAfterTimeout(subprocess, timeout, context, controller)];15
6 unmodified lines
modified:lib/transform/encoding-transform.js+1 added-2 removed
1 unmodified line
2import {StringDecoder} from 'node:string_decoder';3import {isUint8Array, bufferToUint8Array} from '../utils/uint-array.js';45/*6When using generators, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.7This allows generator functions to operate with those types instead.6When using binary encodings, add an internal generator that converts chunks from `Buffer` to `string` or `Uint8Array`.7Chunks 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 string
43 unmodified lines
modified:lib/transform/generator.js+2 added
69 unmodified lines
70 });71 return {stream};72};7374// Applies transform generators in sync mode75export const runGeneratorsSync = (chunks, stdioItems, encoding, isInput) => {76 const generators = stdioItems.filter(({type}) => type === 'generator');77 const reversedGenerators = isInput ? generators.reverse() : generators;78
4 unmodified lines
8384 return chunks;85};8687// Generators used internally to convert the chunk type, validate it, and split into lines88const addInternalGenerators = (89 {transform, final, binary, writableObjectMode, readableObjectMode, preserveNewlines},90 encoding,91 optionName,
16 unmodified lines
modified:lib/transform/run-async.js+1 added
1import {callbackify} from 'node:util';23// Applies a series of generator functions asynchronously4export const pushChunks = callbackify(async (getChunks, state, getChunksArguments, transformStream) => {5 state.currentIterable = getChunks(...getChunksArguments);67 try {
53 unmodified lines
modified: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 functions2export const pushChunksSync = (getChunksSync, getChunksArguments, transformStream, done) => {3 try {4 for (const chunk of getChunksSync(...getChunksArguments)) {5 transformStream.push(chunk);
45 unmodified lines
modified:lib/transform/split.js+1 added
1 unmodified line
2export const getSplitLinesGenerator = (binary, preserveNewlines, skipped, state) => binary || skipped3 ? undefined4 : initializeSplitLines(preserveNewlines, state);56// Same but for synchronous methods7export const splitLinesSync = (chunk, preserveNewlines, objectMode) => objectMode8 ? chunk.flatMap(item => splitLinesItemSync(item, preserveNewlines))9 : splitLinesItemSync(chunk, preserveNewlines);10
100 unmodified lines
modified:lib/transform/validate.js+2 added
1import {Buffer} from 'node:buffer';2import {isUint8Array} from '../utils/uint-array.js';34// Validate the type of chunk argument passed to transform generators5export const getValidateTransformInput = (writableObjectMode, optionName) => writableObjectMode6 ? undefined7 : validateStringTransformInput.bind(undefined, optionName);8
4 unmodified lines
1314 yield chunk;15};1617// Validate the type of the value returned by transform generators18export const getValidateTransformReturn = (readableObjectMode, optionName) => readableObjectMode19 ? validateObjectTransformReturn.bind(undefined, optionName)20 : validateStringTransformReturn.bind(undefined, optionName);21
23 unmodified lines
modified:lib/utils/max-listeners.js+1 added
1import {addAbortListener} from 'node:events';23// Temporarily increase the maximum number of listeners on an eventEmitter4export const incrementMaxListeners = (eventEmitter, maxListenersIncrement, signal) => {5 const maxListeners = eventEmitter.getMaxListeners();6 if (maxListeners === 0 || maxListeners === Number.POSITIVE_INFINITY) {7 return;
7 unmodified lines
modified:lib/verbose/info.js+3 added
1import {debuglog} from 'node:util';23// Default value for the `verbose` option4export const verboseDefault = debuglog('execa').enabled ? 'full' : 'none';56// Information computed before spawning, used by the `verbose` option7export const getVerboseInfo = verbose => {8 const verboseId = isVerbose(verbose) ? VERBOSE_ID++ : undefined;9 return {verbose, verboseId};10};
4 unmodified lines
15// 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.17let VERBOSE_ID = 0n;1819// The `verbose` option can have different values for `stdout`/`stderr`20export const isVerbose = verbose => verbose.some(fdVerbose => fdVerbose !== 'none');
modified:lib/verbose/output.js+2 added
22 unmodified lines
23const fdUsesVerbose = fdNumber => fdNumber === 1 || fdNumber === 2;2425const PIPED_STDIO_VALUES = new Set(['pipe', 'overlapped']);2627// `verbose` printing logic with async methods28export const logLines = async (linesIterable, stream, verboseInfo) => {29 for await (const line of linesIterable) {30 if (!isPipingStream(stream)) {31 logLine(line, verboseInfo);32 }33 }34};3536// `verbose` printing logic with sync methods37export const logLinesSync = (linesArray, verboseInfo) => {38 for (const line of linesArray) {39 logLine(line, verboseInfo);40 }
21 unmodified lines
modified:test/arguments/cwd.js+1 added
69 unmodified lines
70}7172const cwdNotExisting = {cwd: 'does_not_exist', expectedCode: 'ENOENT', expectedMessage: 'The "cwd" option is invalid'};73const 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.075const cwdNotDirectory = {cwd: fileURLToPath(import.meta.url), expectedCode: isWindows ? 'ENOENT' : 'ENOTDIR', expectedMessage: 'The "cwd" option is not a directory'};7677const testCwdPostSpawn = async (t, {cwd, expectedCode, expectedMessage}, execaMethod) => {78 const {failed, code, message} = await execaMethod('empty.js', {cwd, reject: false});
26 unmodified lines
modified:test/helpers/fixtures-directory.js+1 added
3 unmodified lines
4import pathKey from 'path-key';56export const PATH_KEY = pathKey();7export const FIXTURES_DIRECTORY_URL = new URL('../fixtures/', import.meta.url);8// @todo: use import.meta.dirname after dropping support for Node <20.11.09export const FIXTURES_DIRECTORY = resolve(fileURLToPath(FIXTURES_DIRECTORY_URL));1011// 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 lines
modified:test/methods/parameters-command.js+1 added
70 unmodified lines
71test('$\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $);72test('$.sync\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $.sync);7374const 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