Skip to content
Myr

Refactor `verbose` logic (#1126)

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

authored by ehmicky · committed by GitHub · parent cbe805c · Browse files · 18 files+245 added−156 removed
This commit

State

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

Diff stats

18 files+245 added−156 removed

  • other:+245 added−156 removed

18 files+245 added−156 removed

modified:lib/arguments/command.js+4 added-3 removed
modified:lib/arguments/specific.js+9 added-1 removed
modified:lib/io/contents.js+39 added-21 removed
5 unmodified lines
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,10export const getStreamOutput = async ({stream, onStreamEnd, fdNumber, encoding, buffer, maxBuffer, lines, allMixed, stripFinalNewline, verboseInfo, streamInfo}) => {11 const logPromise = logOutputAsync({12 stream,13 onStreamEnd,14 fdNumber,15 encoding,16 allMixed,17 verboseInfo,15 fdNumber,16 })) {17 const linesIterable = iterateForResult({18 stream,19 onStreamEnd,20 lines: true,21 encoding,22 stripFinalNewline: true,23 allMixed,24 });25 logLines(linesIterable, stream, verboseInfo);26 }18 streamInfo,19 });2021 if (!buffer) {29 await resumeStream(stream);22 await Promise.all([resumeStream(stream), logPromise]);23 return;24 }2526 const stripFinalNewlineValue = getStripFinalNewline(stripFinalNewline, fdNumber);
4 unmodified lines
31 encoding,32 stripFinalNewline: stripFinalNewlineValue,33 allMixed,34 });35 const [output] = await Promise.all([42 return getStreamContents({43 stream,44 iterable,36 getStreamContents({37 stream,38 iterable,39 fdNumber,40 encoding,41 maxBuffer,42 lines,43 }),44 logPromise,45 ]);46 return output;47};4849const logOutputAsync = async ({stream, onStreamEnd, fdNumber, encoding, allMixed, verboseInfo, streamInfo: {fileDescriptors}}) => {50 if (!shouldLogOutput({51 stdioItems: fileDescriptors[fdNumber]?.stdioItems,52 encoding,53 verboseInfo,54 fdNumber,55 })) {56 return;57 }5859 const linesIterable = iterateForResult({60 stream,61 onStreamEnd,62 lines: true,63 encoding,47 maxBuffer,48 lines,64 stripFinalNewline: true,65 allMixed,66 });67 await logLines(linesIterable, stream, verboseInfo);68};6970// When using `buffer: false`, users need to read `subprocess.stdout|stderr|all` right away71// See https://github.com/sindresorhus/execa/issues/730 and https://github.com/sindresorhus/execa/pull/729#discussion_r1465496310
45 unmodified lines
modified:lib/io/max-buffer.js+4 added-2 removed
1import {MaxBufferError} from 'get-stream';2import {getStreamName} from '../utils/standard-stream.js';3import {getFdSpecificValue} from '../arguments/specific.js';45// When the `maxBuffer` option is hit, a MaxBufferError is thrown.6// The stream is aborted, then specific information is kept for the error message.7export const handleMaxBuffer = ({error, stream, readableObjectMode, lines, encoding, fdNumber}) => {
51 unmodified lines
5960 const {maxBufferInfo: {fdNumber, unit}} = error;61 delete error.maxBufferInfo;6263 const threshold = getFdSpecificValue(maxBuffer, fdNumber);64 if (fdNumber === 'ipc') {63 return {streamName: 'IPC output', threshold: maxBuffer.at(-1), unit: 'messages'};65 return {streamName: 'IPC output', threshold, unit: 'messages'};66 }6766 return {streamName: getStreamName(fdNumber), threshold: maxBuffer[fdNumber], unit};68 return {streamName: getStreamName(fdNumber), threshold, unit};69};7071// The only way to apply `maxBuffer` with `spawnSync()` is to use the native `maxBuffer` option Node.js provides.72// However, this has multiple limitations, and cannot behave the exact same way as the async behavior.
17 unmodified lines
modified:lib/io/output-sync.js+21 added-8 removed
46 unmodified lines
47 stripFinalNewline,48 fdNumber,49 });5051 if (shouldLogOutput({52 stdioItems,53 encoding,54 verboseInfo,51 logOutputSync({52 serializedResult,53 fdNumber,56 })) {57 const linesArray = splitLinesSync(serializedResult, false, objectMode);58 logLinesSync(linesArray, verboseInfo);59 }54 verboseInfo,55 encoding,56 stdioItems,57 objectMode,58 });5960 const returnedResult = buffer[fdNumber] ? finalResult : undefined;6162 try {
37 unmodified lines
100101 return {serializedResult};102};103104const logOutputSync = ({serializedResult, fdNumber, verboseInfo, encoding, stdioItems, objectMode}) => {105 if (!shouldLogOutput({106 stdioItems,107 encoding,108 verboseInfo,109 fdNumber,110 })) {111 return;112 }113114 const linesArray = splitLinesSync(serializedResult, false, objectMode);115 logLinesSync(linesArray, verboseInfo);116};117118// When the `std*` target is a file path/URL or a file descriptor119const writeToFiles = (serializedResult, stdioItems, outputFiles) => {120 for (const {path} of stdioItems.filter(({type}) => FILE_TYPES.has(type))) {121 const pathString = typeof path === 'string' ? path : path.toString();
8 unmodified lines
modified:lib/ipc/buffer-messages.js+3 added-2 removed
modified:lib/ipc/outgoing.js+2 added-1 removed
1import {createDeferred} from '../utils/deferred.js';2import {getFdSpecificValue} from '../arguments/specific.js';3import {SUBPROCESS_OPTIONS} from '../arguments/fd-options.js';4import {validateStrictDeadlock} from './strict.js';56// When `sendMessage()` is ongoing, any `message` being received waits before being emitted.
34 unmodified lines
4142// When `buffer` is `false`, we set up a `message` listener that should be ignored.43// That listener is only meant to intercept `strict` acknowledgement responses.44const getMinListenerCount = anyProcess => SUBPROCESS_OPTIONS.has(anyProcess)44 && !SUBPROCESS_OPTIONS.get(anyProcess).options.buffer.at(-1)45 && !getFdSpecificValue(SUBPROCESS_OPTIONS.get(anyProcess).options.buffer, 'ipc')46 ? 147 : 0;
modified:lib/return/reject.js+1 added-1 removed
modified:lib/stdio/handle.js+1 added-1 removed
15 unmodified lines
16// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode17// They are converted into an array of `fileDescriptors`.18// Each `fileDescriptor` is normalized, validated and contains all information necessary for further handling.19export const handleStdio = (addProperties, options, verboseInfo, isSync) => {20 const stdio = normalizeStdioOption(options, isSync);20 const stdio = normalizeStdioOption(options, verboseInfo, isSync);21 const initialFileDescriptors = stdio.map((stdioOption, fdNumber) => getFileDescriptor({22 stdioOption,23 fdNumber,24 options,
190 unmodified lines
modified:lib/stdio/stdio-option.js+5 added-4 removed
1import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';2import {normalizeIpcStdioArray} from '../ipc/array.js';3import {isFullVerbose} from '../verbose/info.js';45// Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`.6// Also normalize the `stdio` option.6export const normalizeStdioOption = ({stdio, ipc, buffer, verbose, ...options}, isSync) => {7export const normalizeStdioOption = ({stdio, ipc, buffer, ...options}, verboseInfo, isSync) => {8 const stdioArray = getStdioArray(stdio, options).map((stdioOption, fdNumber) => addDefaultValue(stdioOption, fdNumber));9 return isSync9 ? normalizeStdioSync(stdioArray, buffer, verbose)10 ? normalizeStdioSync(stdioArray, buffer, verboseInfo)11 : normalizeIpcStdioArray(stdioArray, ipc);12};1314const getStdioArray = (stdio, options) => {
32 unmodified lines
47};4849// Using `buffer: false` with synchronous methods implies `stdout`/`stderr`: `ignore`.50// Unless the output is needed, e.g. due to `verbose: 'full'` or to redirecting to a file.50const normalizeStdioSync = (stdioArray, buffer, verbose) => stdioArray.map((stdioOption, fdNumber) =>51const normalizeStdioSync = (stdioArray, buffer, verboseInfo) => stdioArray.map((stdioOption, fdNumber) =>52 !buffer[fdNumber]53 && fdNumber !== 053 && verbose[fdNumber] !== 'full'54 && !isFullVerbose(verboseInfo, fdNumber)55 && isOutputPipeOnly(stdioOption)56 ? 'ignore'57 : stdioOption);58
2 unmodified lines
modified:lib/verbose/complete.js+19 added-39 removed
1import prettyMs from 'pretty-ms';2import {gray} from 'yoctocolors';2import {escapeLines} from '../arguments/escape.js';3import {getDurationMs} from '../return/duration.js';4import {isVerbose} from './info.js';5import {verboseLog} from './log.js';6import {logError} from './error.js';78// When `verbose` is `short|full`, print each command's completion, duration and error10export const logFinalResult = ({shortMessage, failed, durationMs}, reject, verboseInfo) => {11 logResult({12 message: shortMessage,13 failed,14 reject,15 durationMs,16 verboseInfo,17 });9export const logFinalResult = ({shortMessage, durationMs, failed}, verboseInfo) => {10 logResult(shortMessage, durationMs, verboseInfo, failed);11};1213// Same but for early validation errors21export const logEarlyResult = (error, startTime, verboseInfo) => {22 logResult({23 message: escapeLines(String(error)),24 failed: true,25 reject: true,26 durationMs: getDurationMs(startTime),27 verboseInfo,28 });14export const logEarlyResult = (error, startTime, {rawOptions, ...verboseInfo}) => {15 const shortMessage = escapeLines(String(error));16 const durationMs = getDurationMs(startTime);17 const earlyVerboseInfo = {...verboseInfo, rawOptions: {...rawOptions, reject: true}};18 logResult(shortMessage, durationMs, earlyVerboseInfo, true);19};2031const logResult = ({message, failed, reject, durationMs, verboseInfo: {verbose, verboseId}}) => {32 if (!isVerbose(verbose)) {21const logResult = (shortMessage, durationMs, verboseInfo, failed) => {22 if (!isVerbose(verboseInfo)) {23 return;24 }2536 const icon = getIcon(failed, reject);37 logError({38 message,26 logError(shortMessage, verboseInfo, failed);27 logDuration(durationMs, verboseInfo, failed);28};2930const logDuration = (durationMs, verboseInfo, failed) => {31 const logMessage = `(done in ${prettyMs(durationMs)})`;32 verboseLog({33 type: 'duration',34 logMessage,35 verboseInfo,36 failed,40 reject,41 verboseId,42 icon,37 });44 logDuration(durationMs, verboseId, icon);38};4647const logDuration = (durationMs, verboseId, icon) => {48 const durationMessage = `(done in ${prettyMs(durationMs)})`;49 verboseLog(durationMessage, verboseId, icon, gray);50};5152const getIcon = (failed, reject) => {53 if (!failed) {54 return 'success';55 }5657 return reject ? 'error' : 'warning';58};
added:lib/verbose/default.js+46 added
1import figures from 'figures';2import {3 gray,4 bold,5 redBright,6 yellowBright,7} from 'yoctocolors';89// Default logger for the `verbose` option10export const defaultLogger = ({type, message, timestamp, failed, piped, commandId, options: {reject = true}}) => {11 const timestampString = serializeTimestamp(timestamp);12 const icon = ICONS[type]({failed, reject, piped});13 const color = COLORS[type]({reject});14 return `${gray(`[${timestampString}]`)} ${gray(`[${commandId}]`)} ${color(icon)} ${color(message)}`;15};1617// Prepending the timestamp allows debugging the slow paths of a subprocess18const serializeTimestamp = timestamp => `${padField(timestamp.getHours(), 2)}:${padField(timestamp.getMinutes(), 2)}:${padField(timestamp.getSeconds(), 2)}.${padField(timestamp.getMilliseconds(), 3)}`;1920const padField = (field, padding) => String(field).padStart(padding, '0');2122const getFinalIcon = ({failed, reject}) => {23 if (!failed) {24 return figures.tick;25 }2627 return reject ? figures.cross : figures.warning;28};2930const ICONS = {31 command: ({piped}) => piped ? '|' : '$',32 output: () => ' ',33 ipc: () => '*',34 error: getFinalIcon,35 duration: getFinalIcon,36};3738const identity = string => string;3940const COLORS = {41 command: () => bold,42 output: () => identity,43 ipc: () => identity,44 error: ({reject}) => reject ? redBright : yellowBright,45 duration: () => gray,46};
modified:lib/verbose/error.js+8 added-7 removed
1import {redBright, yellowBright} from 'yoctocolors';1import {verboseLog} from './log.js';23// When `verbose` is `short|full`, print each command's error when it fails5export const logError = ({message, failed, reject, verboseId, icon}) => {6 if (!failed) {7 return;4export const logError = (logMessage, verboseInfo, failed) => {5 if (failed) {6 verboseLog({7 type: 'error',8 logMessage,9 verboseInfo,10 failed,11 });12 }910 const color = reject ? redBright : yellowBright;11 verboseLog(message, verboseId, icon, color);13};
modified:lib/verbose/info.js+27 added-16 removed
1import {debuglog} from 'node:util';1import {getFdSpecificValue} from '../arguments/specific.js';23// Default value for the `verbose` option4export const verboseDefault = debuglog('execa').enabled ? 'full' : 'none';53// Information computed before spawning, used by the `verbose` option7export const getVerboseInfo = verbose => {8 const verboseId = isVerbose(verbose) ? VERBOSE_ID++ : undefined;4export const getVerboseInfo = (verbose, escapedCommand, rawOptions) => {5 validateVerbose(verbose);10 return {verbose, verboseId};6 const commandId = getCommandId(verbose);7 return {8 verbose,9 escapedCommand,10 commandId,11 rawOptions,12 };13};1415const getCommandId = verbose => isVerbose({verbose}) ? COMMAND_ID++ : undefined;1617// Prepending the `pid` is useful when multiple commands print their output at the same time.18// However, we cannot use the real PID since this is not available with `child_process.spawnSync()`.19// Also, we cannot use the real PID if we want to print it before `child_process.spawn()` is run.20// As a pro, it is shorter than a normal PID and never re-uses the same id.21// As a con, it cannot be used to send signals.18let VERBOSE_ID = 0n;22let COMMAND_ID = 0n;2320// The `verbose` option can have different values for `stdout`/`stderr`21export const isVerbose = verbose => verbose.some(fdVerbose => fdVerbose !== 'none');2224const validateVerbose = verbose => {24 for (const verboseItem of verbose) {25 if (verboseItem === false) {25 for (const fdVerbose of verbose) {26 if (fdVerbose === false) {27 throw new TypeError('The "verbose: false" option was renamed to "verbose: \'none\'".');28 }2929 if (verboseItem === true) {30 if (fdVerbose === true) {31 throw new TypeError('The "verbose: true" option was renamed to "verbose: \'short\'".');32 }3333 if (!VERBOSE_VALUES.has(verboseItem)) {34 if (!VERBOSE_VALUES.has(fdVerbose)) {35 const allowedValues = [...VERBOSE_VALUES].map(allowedValue => `'${allowedValue}'`).join(', ');35 throw new TypeError(`The "verbose" option must not be ${verboseItem}. Allowed values are: ${allowedValues}.`);36 throw new TypeError(`The "verbose" option must not be ${fdVerbose}. Allowed values are: ${allowedValues}.`);37 }38 }39};4041const VERBOSE_VALUES = new Set(['none', 'short', 'full']);4243// The `verbose` option can have different values for `stdout`/`stderr`44export const isVerbose = ({verbose}) => getFdGenericVerbose(verbose) !== 'none';4546// Whether IPC and output and logged47export const isFullVerbose = ({verbose}, fdNumber) => getFdSpecificValue(verbose, fdNumber) === 'full';4849const getFdGenericVerbose = verbose => verbose.every(fdVerbose => fdVerbose === verbose[0])50 ? verbose[0]51 : verbose.find(fdVerbose => fdVerbose !== 'none');
modified:lib/verbose/ipc.js+9 added-3 removed
1import {verboseLog, serializeLogMessage} from './log.js';2import {isFullVerbose} from './info.js';34// When `verbose` is `'full'`, print IPC messages from the subprocess4export const shouldLogIpc = ({verbose}) => verbose.at(-1) === 'full';5export const shouldLogIpc = verboseInfo => isFullVerbose(verboseInfo, 'ipc');66export const logIpcOutput = (message, {verboseId}) => {7 verboseLog(serializeLogMessage(message), verboseId, 'ipc');7export const logIpcOutput = (message, verboseInfo) => {8 const logMessage = serializeLogMessage(message);9 verboseLog({10 type: 'ipc',11 logMessage,12 verboseInfo,13 });14};
modified:lib/verbose/log.js+29 added-38 removed
1import {writeFileSync} from 'node:fs';2import {inspect} from 'node:util';3import figures from 'figures';4import {gray} from 'yoctocolors';3import {escapeLines} from '../arguments/escape.js';4import {defaultLogger} from './default.js';56// Write synchronously to ensure lines are properly ordered and not interleaved with `stdout`8export const verboseLog = (string, verboseId, icon, color) => {9 const prefixedLines = addPrefix(string, verboseId, icon, color);10 writeFileSync(STDERR_FD, `${prefixedLines}\n`);7export const verboseLog = ({type, logMessage, verboseInfo, failed, piped}) => {8 const logObject = getLogObject({9 type,10 failed,11 piped,12 verboseInfo,13 });14 const printedLines = getPrintedLines(logMessage, logObject);15 writeFileSync(STDERR_FD, `${printedLines}\n`);16};1713const STDERR_FD = 2;18const getLogObject = ({19 type,20 failed = false,21 piped = false,22 verboseInfo: {commandId, rawOptions},23}) => ({24 type,25 timestamp: new Date(),26 failed,27 piped,28 commandId,29 options: rawOptions,30});3115const addPrefix = (string, verboseId, icon, color) => string.includes('\n')16 ? string17 .split('\n')18 .map(line => addPrefixToLine(line, verboseId, icon, color))19 .join('\n')20 : addPrefixToLine(string, verboseId, icon, color);32const getPrintedLines = (logMessage, logObject) => logMessage33 .split('\n')34 .map(message => defaultLogger({...logObject, message}))35 .join('\n');3622const addPrefixToLine = (line, verboseId, icon, color = identity) => [23 gray(`[${getTimestamp()}]`),24 gray(`[${verboseId}]`),25 color(ICONS[icon]),26 color(line),27].join(' ');37// Unless a `verbose` function is used, print all logs on `stderr`38const STDERR_FD = 2;3929const identity = string => string;3031// Prepending the timestamp allows debugging the slow paths of a subprocess32const getTimestamp = () => {33 const date = new Date();34 return `${padField(date.getHours(), 2)}:${padField(date.getMinutes(), 2)}:${padField(date.getSeconds(), 2)}.${padField(date.getMilliseconds(), 3)}`;35};3637const padField = (field, padding) => String(field).padStart(padding, '0');3839const ICONS = {40 command: '$',41 pipedCommand: '|',42 output: ' ',43 ipc: '*',44 error: figures.cross,45 warning: figures.warning,46 success: figures.tick,47};4840// Serialize any type to a line string, for logging41export const serializeLogMessage = message => {42 const messageString = typeof message === 'string' ? message : inspect(message);43 const escapedMessage = escapeLines(messageString);
5 unmodified lines
modified:lib/verbose/output.js+10 added-4 removed
1import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';2import {TRANSFORM_TYPES} from '../stdio/type.js';3import {verboseLog, serializeLogMessage} from './log.js';4import {isFullVerbose} from './info.js';56// `ignore` opts-out of `verbose` for a specific stream.7// `ipc` cannot use piping.8// `inherit` would result in double printing.9// They can also lead to double printing when passing file descriptor integers or `process.std*`.10// This only leaves with `pipe` and `overlapped`.10export const shouldLogOutput = ({stdioItems, encoding, verboseInfo: {verbose}, fdNumber}) => fdNumber !== 'all'11 && verbose[fdNumber] === 'full'11export const shouldLogOutput = ({stdioItems, encoding, verboseInfo, fdNumber}) => fdNumber !== 'all'12 && isFullVerbose(verboseInfo, fdNumber)13 && !BINARY_ENCODINGS.has(encoding)14 && fdUsesVerbose(fdNumber)15 && (stdioItems.some(({type, value}) => type === 'native' && PIPED_STDIO_VALUES.has(value))16 || stdioItems.every(({type}) => TRANSFORM_TYPES.has(type)));
31 unmodified lines
48// This is not a critical behavior since changes of the following property would only make `verbose` more verbose.49const isPipingStream = stream => stream._readableState.pipes.length > 0;5051// When `verbose` is `full`, print stdout|stderr51const logLine = (line, {verboseId}) => {52 verboseLog(serializeLogMessage(line), verboseId, 'output');52const logLine = (line, verboseInfo) => {53 const logMessage = serializeLogMessage(line);54 verboseLog({55 type: 'output',56 logMessage,57 verboseInfo,58 });59};
modified:lib/verbose/start.js+8 added-5 removed
1import {bold} from 'yoctocolors';1import {isVerbose} from './info.js';2import {verboseLog} from './log.js';34// When `verbose` is `short|full`, print each command6export const logCommand = (escapedCommand, {verbose, verboseId}, {piped = false}) => {7 if (!isVerbose(verbose)) {5export const logCommand = (escapedCommand, verboseInfo, piped) => {6 if (!isVerbose(verboseInfo)) {7 return;8 }911 const icon = piped ? 'pipedCommand' : 'command';12 verboseLog(escapedCommand, verboseId, icon, bold);10 verboseLog({11 type: 'command',12 logMessage: escapedCommand,13 verboseInfo,14 piped,15 });16};