Allow `verbose` option to be a function for custom logging (#1130)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 78edcb9 · Browse files · 58 files·+1720 added−165 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
58 files+1720 added−165 removed
- tests:+1161 added−11 removed
- other:+559 added−154 removed
Provenance
- Commit
8daf348- Tree
9c8cd2c- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
78edcb9
58 files changed+1720 added−165 removed
modified:docs/api.md+82 added-2 removed
1031 unmodified lines1032 More info [here](ipc.md#send-an-initial-message) and [there](input.md#any-input-type).1033 1034 ### options.verbose1035 1036-_Type:_ `'none' | 'short' | 'full'`\1036+_Type:_ `'none' | 'short' | 'full' | Function`\1037 _Default:_ `'none'`1038 1039 If `verbose` is `'short'`, prints the command on [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)): its file, arguments, duration and (if it failed) error message.1040 1041-If `verbose` is `'full'`, the command's [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)), `stderr` and [IPC messages](ipc.md) are also printed.1041+If `verbose` is `'full'` or a function, the command's [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)), `stderr` and [IPC messages](ipc.md) are also printed.1042 1043+A [function](#verbose-function) can be passed to customize logging. Please see [this page](debugging.md#custom-logging) for more information.1044+1045 By default, this applies to both `stdout` and `stderr`, but [different values can also be passed](output.md#stdoutstderr-specific-options).1046 1047 [More info.](debugging.md#verbose-mode)1048 122 unmodified lines1171 If `false`, escapes the command arguments on Windows.1172 1173 [More info.](windows.md#cmdexe-escaping)1174 1175+## Verbose function1176+1177+_Type_: `(string, VerboseObject) => string | undefined`1178+1179+Function passed to the [`verbose`](#optionsverbose) option to customize logging.1180+1181+[More info.](debugging.md#custom-logging)1182+1183+### Verbose object1184+1185+_Type_: `VerboseObject` or `SyncVerboseObject`1186+1187+Subprocess event object, for logging purpose, using the [`verbose`](#optionsverbose) option.1188+1189+#### verboseObject.type1190+1191+_Type_: `string`1192+1193+Event type. This can be:1194+- `'command'`: subprocess start1195+- `'output'`: `stdout`/`stderr` [output](output.md#stdout-and-stderr)1196+- `'ipc'`: IPC [output](ipc.md#retrieve-all-messages)1197+- `'error'`: subprocess [failure](errors.md#subprocess-failure)1198+- `'duration'`: subprocess success or failure1199+1200+#### verboseObject.message1201+1202+_Type_: `string`1203+1204+Depending on [`verboseObject.type`](#verboseobjecttype), this is:1205+- `'command'`: the [`result.escapedCommand`](#resultescapedcommand)1206+- `'output'`: one line from [`result.stdout`](#resultstdout) or [`result.stderr`](#resultstderr)1207+- `'ipc'`: one IPC message from [`result.ipcOutput`](#resultipcoutput)1208+- `'error'`: the [`error.shortMessage`](#errorshortmessage)1209+- `'duration'`: the [`result.durationMs`](#resultdurationms)1210+1211+#### verboseObject.escapedCommand1212+1213+_Type_: `string`1214+1215+The file and [arguments](input.md#command-arguments) that were run. This is the same as [`result.escapedCommand`](#resultescapedcommand).1216+1217+#### verboseObject.options1218+1219+_Type_: [`Options`](#options-1) or [`SyncOptions`](#options-1)1220+1221+The [options](#options-1) passed to the subprocess.1222+1223+#### verboseObject.commandId1224+1225+_Type_: `string`1226+1227+Serial number identifying the subprocess within the current process. It is incremented from `'0'`.1228+1229+This is helpful when multiple subprocesses are running at the same time.1230+1231+This is similar to a [PID](https://en.wikipedia.org/wiki/Process_identifier) except it has no maximum limit, which means it never repeats. Also, it is usually shorter.1232+1233+#### verboseObject.timestamp1234+1235+_Type_: `Date`1236+1237+Event date/time.1238+1239+#### verboseObject.result1240+1241+_Type_: [`Result`](#result), [`SyncResult`](#result) or `undefined`1242+1243+Subprocess [result](#result).1244+1245+This is `undefined` if [`verboseObject.type`](#verboseobjecttype) is `'command'`, `'output'` or `'ipc'`.1246+1247+#### verboseObject.piped1248+1249+_Type_: `boolean`1250+1251+Whether another subprocess is [piped](pipe.md) into this subprocess. This is `false` when [`result.pipedFrom`](#resultfailed) is empty.1252+1253 ## Transform options1254 1255 A transform or an [array of transforms](transform.md#combining) can be passed to the [`stdin`](#optionsstdin), [`stdout`](#optionsstdout), [`stderr`](#optionsstderr) or [`stdio`](#optionsstdio) option.1256 51 unmodified linesmodified:docs/debugging.md+90 added
104 unmodified linesExpand all105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203104 unmodified linesExpand allWhen printed to a terminal, the verbose mode uses colors.
<img alt="execa verbose output" src="../media/verbose.png" width="603">
## Custom logging
### Verbose function
The [`verbose`](api.md#optionsverbose) option can be a function to customize logging.
It is called once per log line. The first argument is the default log line string. The second argument is the same information but as an object instead (documented [here](api.md#verbose-object)).
If a string is returned, it is printed on `stderr`. If `undefined` is returned, nothing is printed.
### Filter logs
```jsimport {execa as execa_} from 'execa';
// Only print log lines showing the subprocess durationconst execa = execa_({ verbose(verboseLine, {type}) { return type === 'duration' ? verboseLine : undefined; },});```
### Transform logs
```jsimport {execa as execa_} from 'execa';
// Prepend current process' PIDconst execa = execa_({ verbose(verboseLine) { return `[${process.pid}] ${verboseLine}` },});```
### Custom log format
```jsimport {execa as execa_} from 'execa';
// Use a different format for the timestampconst execa = execa_({ verbose(verboseLine, {timestamp}) { return verboseLine.replace(timestampRegExp, timestamp.toISOString()); },});
// Timestamp at the start of each log lineconst timestampRegExp = /\d{2}:\d{2}:\d{2}\.\d{3}/;```
### JSON logging
```jsimport {execa as execa_} from 'execa';
const execa = execa_({ verbose(verboseLine, verboseObject) { return JSON.stringify(verboseObject) },});```
### Advanced logging
```jsimport {execa as execa_} from 'execa';import {createLogger, transports} from 'winston';
// Log to a file using Winstonconst transport = new transports.File({filename: 'logs.txt'});const logger = createLogger({transports: [transport]});
const execa = execa_({ verbose(verboseLine, {type, message, ...verboseObject}) { const level = LOG_LEVELS[type]; logger[level](message, verboseObject); },});
const LOG_LEVELS = { command: 'info', output: 'verbose', ipc: 'verbose', error: 'error', duration: 'info',};```
<hr>
[**Next**: 📎 Windows](windows.md)\[**Previous**: 📞 Inter-process communication](ipc.md)\[**Top**: Table of contents](../readme.md#documentation)modified:docs/typescript.md+14 added-2 removed
6 unmodified lines7 # 🤓 TypeScript8 9 ## Available types10 11-The following types can be imported: [`ResultPromise`](api.md#return-value), [`Subprocess`](api.md#subprocess), [`Result`](api.md#result), [`ExecaError`](api.md#execaerror), [`Options`](api.md#options-1), [`StdinOption`](api.md#optionsstdin), [`StdoutStderrOption`](api.md#optionsstdout), [`TemplateExpression`](api.md#execacommand), [`Message`](api.md#subprocesssendmessagemessage-sendmessageoptions), [`ExecaMethod`](api.md#execaoptions), [`ExecaNodeMethod`](api.md#execanodeoptions) and [`ExecaScriptMethod`](api.md#options).11+The following types can be imported: [`ResultPromise`](api.md#return-value), [`Subprocess`](api.md#subprocess), [`Result`](api.md#result), [`ExecaError`](api.md#execaerror), [`Options`](api.md#options-1), [`StdinOption`](api.md#optionsstdin), [`StdoutStderrOption`](api.md#optionsstdout), [`TemplateExpression`](api.md#execacommand), [`Message`](api.md#subprocesssendmessagemessage-sendmessageoptions), [`VerboseObject`](api.md#verbose-object), [`ExecaMethod`](api.md#execaoptions), [`ExecaNodeMethod`](api.md#execanodeoptions) and [`ExecaScriptMethod`](api.md#options).12 13 ```ts14 import {15 execa as execa_,4 unmodified lines20 type StdinOption,21 type StdoutStderrOption,22 type TemplateExpression,23 type Message,24+ type VerboseObject,25 type ExecaMethod,26 } from 'execa';27 28 const execa: ExecaMethod = execa_({preferLocal: true});3 unmodified lines32 stdout: 'pipe' satisfies StdoutStderrOption,33 stderr: 'pipe' satisfies StdoutStderrOption,34 timeout: 1000,35 ipc: true,36+ verbose(verboseLine: string, verboseObject: VerboseObject) {37+ return verboseObject.type === 'duration' ? verboseLine : undefined;38+ },39 };40 const task: TemplateExpression = 'build';41 const message: Message = 'hello world';42 10 unmodified lines53 ```54 55 ## Synchronous execution56 53-Their [synchronous](#synchronous-execution) counterparts are [`SyncResult`](api.md#result), [`ExecaSyncError`](api.md#execasyncerror), [`SyncOptions`](api.md#options-1), [`StdinSyncOption`](api.md#optionsstdin), [`StdoutStderrSyncOption`](api.md#optionsstdout), [`TemplateExpression`](api.md#execacommand), [`ExecaSyncMethod`](api.md#execasyncoptions) and [`ExecaScriptSyncMethod`](api.md#syncoptions).57+Their [synchronous](#synchronous-execution) counterparts are [`SyncResult`](api.md#result), [`ExecaSyncError`](api.md#execasyncerror), [`SyncOptions`](api.md#options-1), [`StdinSyncOption`](api.md#optionsstdin), [`StdoutStderrSyncOption`](api.md#optionsstdout), [`TemplateExpression`](api.md#execacommand), [`SyncVerboseObject`](api.md#verbose-object), [`ExecaSyncMethod`](api.md#execasyncoptions) and [`ExecaScriptSyncMethod`](api.md#syncoptions).58 59 ```ts60 import {61 execaSync as execaSync_,2 unmodified lines64 type SyncOptions,65 type StdinSyncOption,66 type StdoutStderrSyncOption,67 type TemplateExpression,68+ type SyncVerboseObject,69 type ExecaSyncMethod,70 } from 'execa';71 72 const execaSync: ExecaSyncMethod = execaSync_({preferLocal: true});2 unmodified lines75 stdin: 'inherit' satisfies StdinSyncOption,76 stdout: 'pipe' satisfies StdoutStderrSyncOption,77 stderr: 'pipe' satisfies StdoutStderrSyncOption,78 timeout: 1000,79+ verbose(verboseLine: string, verboseObject: SyncVerboseObject) {80+ return verboseObject.type === 'duration' ? verboseLine : undefined;81+ },82 };83 const task: TemplateExpression = 'build';84 85 try {14 unmodified lines100 import {101 execa as execa_,102 ExecaError,103 type Result,104+ type VerboseObject,105 } from 'execa';106 107 const execa = execa_({preferLocal: true});108 6 unmodified lines115 stdout: 'pipe',116 stderr: 'pipe',117 timeout: 1000,118 ipc: true,119+ verbose(verboseLine: string, verboseObject: VerboseObject) {120+ return verboseObject.type === 'duration' ? verboseLine : undefined;121+ },122 } as const;123 const task = 'build';124 const message = 'hello world';125 66 unmodified linesmodified:lib/arguments/command.js+2 added-2 removed
3 unmodified lines45678891011121313141516173 unmodified lines3 unmodified linesimport {joinCommand} from './escape.js';import {normalizeFdSpecificOption} from './specific.js';
// Compute `result.command`, `result.escapedCommand` and `verbose`-related informationexport const handleCommand = (filePath, rawArguments, {piped, ...rawOptions}) => {export const handleCommand = (filePath, rawArguments, rawOptions) => { const startTime = getStartTime(); const {command, escapedCommand} = joinCommand(filePath, rawArguments); const verbose = normalizeFdSpecificOption(rawOptions, 'verbose'); const verboseInfo = getVerboseInfo(verbose, escapedCommand, {...rawOptions}); logCommand(escapedCommand, verboseInfo, piped); logCommand(escapedCommand, verboseInfo); return { command, escapedCommand, startTime,3 unmodified linesmodified:lib/io/contents.js+1 added-1 removed
62 unmodified lines63 encoding,64 stripFinalNewline: true,65 allMixed,66 });67- await logLines(linesIterable, stream, verboseInfo);67+ await logLines(linesIterable, stream, fdNumber, verboseInfo);68 };69 70 // 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_r146549631045 unmodified linesmodified:lib/io/output-sync.js+8 added-2 removed
49 unmodified lines50 51 logOutputSync({52 serializedResult,53 fdNumber,54+ state,55 verboseInfo,56 encoding,57 stdioItems,58 objectMode,42 unmodified lines101 102 return {serializedResult};103 };104 104-const logOutputSync = ({serializedResult, fdNumber, verboseInfo, encoding, stdioItems, objectMode}) => {105+const logOutputSync = ({serializedResult, fdNumber, state, verboseInfo, encoding, stdioItems, objectMode}) => {106 if (!shouldLogOutput({107 stdioItems,108 encoding,109 verboseInfo,2 unmodified lines112 return;113 }114 115 const linesArray = splitLinesSync(serializedResult, false, objectMode);116+117+ try {115- logLinesSync(linesArray, verboseInfo);118+ logLinesSync(linesArray, fdNumber, verboseInfo);119+ } catch (error) {120+ state.error ??= error;121+ }122 };123 124 // When the `std*` target is a file path/URL or a file descriptor125 const writeToFiles = (serializedResult, stdioItems, outputFiles) => {10 unmodified linesmodified:lib/methods/main-async.js+13 added-20 removed
12 unmodified lines13 import {pipeOutputAsync} from '../io/output-async.js';14 import {subprocessKill} from '../terminate/kill.js';15 import {cleanupOnExit} from '../terminate/cleanup.js';16 import {pipeToSubprocess} from '../pipe/setup.js';17-import {logEarlyResult} from '../verbose/complete.js';17 import {makeAllStream} from '../resolve/all-async.js';18 import {waitForSubprocessResult} from '../resolve/wait-subprocess.js';19 import {addConvertedStreams} from '../convert/add.js';20 import {createDeferred} from '../utils/deferred.js';25 unmodified lines46 47 // Compute arguments to pass to `child_process.spawn()`48 const handleAsyncArguments = (rawFile, rawArguments, rawOptions) => {49 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArguments, rawOptions);51-52- try {53- const {file, commandArguments, options: normalizedOptions} = normalizeOptions(rawFile, rawArguments, rawOptions);54- const options = handleAsyncOptions(normalizedOptions);55- const fileDescriptors = handleStdioAsync(options, verboseInfo);56- return {57- file,58- commandArguments,59- command,60- escapedCommand,61- startTime,62- verboseInfo,63- options,64- fileDescriptors,65- };50+ const {file, commandArguments, options: normalizedOptions} = normalizeOptions(rawFile, rawArguments, rawOptions);51+ const options = handleAsyncOptions(normalizedOptions);52+ const fileDescriptors = handleStdioAsync(options, verboseInfo);53+ return {54+ file,55+ commandArguments,56+ command,57+ escapedCommand,58+ startTime,59+ verboseInfo,60+ options,61+ fileDescriptors,62+ };66- } catch (error) {67- logEarlyResult(error, startTime, verboseInfo);68- throw error;69- }63 };64 65 // Options normalization logic specific to async methods.66 // Prevent passing the `timeout` option directly to `child_process.spawn()`.127 unmodified linesmodified:lib/methods/main-sync.js+14 added-21 removed
6 unmodified lines7 import {stripNewline} from '../io/strip-newline.js';8 import {addInputOptionsSync} from '../io/input-sync.js';9 import {transformOutputSync} from '../io/output-sync.js';10 import {getMaxBufferSync} from '../io/max-buffer.js';11-import {logEarlyResult} from '../verbose/complete.js';11 import {getAllSync} from '../resolve/all-sync.js';12 import {getExitResultSync} from '../resolve/exit-sync.js';13 14 // Main shared logic for all sync methods: `execaSync()`, `$.sync()`14 unmodified lines29 30 // Compute arguments to pass to `child_process.spawnSync()`31 const handleSyncArguments = (rawFile, rawArguments, rawOptions) => {32 const {command, escapedCommand, startTime, verboseInfo} = handleCommand(rawFile, rawArguments, rawOptions);34-35- try {36- const syncOptions = normalizeSyncOptions(rawOptions);37- const {file, commandArguments, options} = normalizeOptions(rawFile, rawArguments, syncOptions);38- validateSyncOptions(options);39- const fileDescriptors = handleStdioSync(options, verboseInfo);40- return {41- file,42- commandArguments,43- command,44- escapedCommand,45- startTime,46- verboseInfo,47- options,48- fileDescriptors,49- };33+ const syncOptions = normalizeSyncOptions(rawOptions);34+ const {file, commandArguments, options} = normalizeOptions(rawFile, rawArguments, syncOptions);35+ validateSyncOptions(options);36+ const fileDescriptors = handleStdioSync(options, verboseInfo);37+ return {38+ file,39+ commandArguments,40+ command,41+ escapedCommand,42+ startTime,43+ verboseInfo,44+ options,45+ fileDescriptors,46+ };50- } catch (error) {51- logEarlyResult(error, startTime, verboseInfo);52- throw error;53- }47 };48 49 // Options normalization logic specific to sync methods50 const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;112 unmodified linesmodified:lib/return/reject.js+2 added-2 removed
1-import {logFinalResult} from '../verbose/complete.js';1+import {logResult} 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, verboseInfo);6+ logResult(result, verboseInfo);7 8 if (result.failed && reject) {9 throw result;10 }3 unmodified linesmodified:lib/stdio/stdio-option.js+1 added-1 removed
1 import {STANDARD_STREAMS_ALIASES} from '../utils/standard-stream.js';2 import {normalizeIpcStdioArray} from '../ipc/array.js';3-import {isFullVerbose} from '../verbose/info.js';3+import {isFullVerbose} from '../verbose/values.js';4 5 // Add support for `stdin`/`stdout`/`stderr` as an alias for `stdio`.6 // Also normalize the `stdio` option.7 export const normalizeStdioOption = ({stdio, ipc, buffer, ...options}, verboseInfo, isSync) => {53 unmodified linesmodified:lib/verbose/complete.js+9 added-23 removed
1 import prettyMs from 'pretty-ms';2-import {escapeLines} from '../arguments/escape.js';3-import {getDurationMs} from '../return/duration.js';4-import {isVerbose} from './info.js';2+import {isVerbose} from './values.js';3 import {verboseLog} from './log.js';4 import {logError} from './error.js';5 8-// When `verbose` is `short|full`, print each command's completion, duration and error9-export const logFinalResult = ({shortMessage, durationMs, failed}, verboseInfo) => {10- logResult(shortMessage, durationMs, verboseInfo, failed);11-};12-13-// Same but for early validation errors14-export 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-};20-21-const logResult = (shortMessage, durationMs, verboseInfo, failed) => {6+// When `verbose` is `short|full|custom`, print each command's completion, duration and error7+export const logResult = (result, verboseInfo) => {8 if (!isVerbose(verboseInfo)) {9 return;10 }11 26- logError(shortMessage, verboseInfo, failed);27- logDuration(durationMs, verboseInfo, failed);12+ logError(result, verboseInfo);13+ logDuration(result, verboseInfo);14 };15 30-const logDuration = (durationMs, verboseInfo, failed) => {31- const logMessage = `(done in ${prettyMs(durationMs)})`;16+const logDuration = (result, verboseInfo) => {17+ const verboseMessage = `(done in ${prettyMs(result.durationMs)})`;18 verboseLog({19 type: 'duration',34- logMessage,20+ verboseMessage,21 verboseInfo,36- failed,22+ result,23 });24 };added:lib/verbose/custom.js+26 added
1+import {getVerboseFunction} from './values.js';2+3+// Apply the `verbose` function on each line4+export const applyVerboseOnLines = (printedLines, verboseInfo, fdNumber) => {5+ const verboseFunction = getVerboseFunction(verboseInfo, fdNumber);6+ return printedLines7+ .map(({verboseLine, verboseObject}) => applyVerboseFunction(verboseLine, verboseObject, verboseFunction))8+ .filter(printedLine => printedLine !== undefined)9+ .map(printedLine => appendNewline(printedLine))10+ .join('');11+};12+13+const applyVerboseFunction = (verboseLine, verboseObject, verboseFunction) => {14+ if (verboseFunction === undefined) {15+ return verboseLine;16+ }17+18+ const printedLine = verboseFunction(verboseLine, verboseObject);19+ if (typeof printedLine === 'string') {20+ return printedLine;21+ }22+};23+24+const appendNewline = printedLine => printedLine.endsWith('\n')25+ ? printedLine26+ : `${printedLine}\n`;modified:lib/verbose/default.js+10 added-2 removed
4 unmodified lines5 redBright,6 yellowBright,7 } from 'yoctocolors';8 9-// Default logger for the `verbose` option10-export const defaultLogger = ({type, message, timestamp, failed, piped, commandId, options: {reject = true}}) => {9+// Default when `verbose` is not a function10+export const defaultVerboseFunction = ({11+ type,12+ message,13+ timestamp,14+ piped,15+ commandId,16+ result: {failed = false} = {},17+ options: {reject = true},18+}) => {19 const timestampString = serializeTimestamp(timestamp);20 const icon = ICONS[type]({failed, reject, piped});21 const color = COLORS[type]({reject});22 return `${gray(`[${timestampString}]`)} ${gray(`[${commandId}]`)} ${color(icon)} ${color(message)}`;32 unmodified linesmodified:lib/verbose/error.js+5 added-5 removed
1 import {verboseLog} from './log.js';2 3-// When `verbose` is `short|full`, print each command's error when it fails4-export const logError = (logMessage, verboseInfo, failed) => {5- if (failed) {3+// When `verbose` is `short|full|custom`, print each command's error when it fails4+export const logError = (result, verboseInfo) => {5+ if (result.failed) {6 verboseLog({7 type: 'error',8- logMessage,8+ verboseMessage: result.shortMessage,9 verboseInfo,10- failed,10+ result,11 });12 }13 };modified:lib/verbose/info.js+4 added-16 removed
1-import {getFdSpecificValue} from '../arguments/specific.js';1+import {isVerbose, VERBOSE_VALUES, isVerboseFunction} from './values.js';2 3 // Information computed before spawning, used by the `verbose` option4 export const getVerboseInfo = (verbose, escapedCommand, rawOptions) => {5 validateVerbose(verbose);24 unmodified lines30 if (fdVerbose === true) {31 throw new TypeError('The "verbose: true" option was renamed to "verbose: \'short\'".');32 }33 34- if (!VERBOSE_VALUES.has(fdVerbose)) {35- const allowedValues = [...VERBOSE_VALUES].map(allowedValue => `'${allowedValue}'`).join(', ');36- throw new TypeError(`The "verbose" option must not be ${fdVerbose}. Allowed values are: ${allowedValues}.`);34+ if (!VERBOSE_VALUES.includes(fdVerbose) && !isVerboseFunction(fdVerbose)) {35+ const allowedValues = VERBOSE_VALUES.map(allowedValue => `'${allowedValue}'`).join(', ');36+ throw new TypeError(`The "verbose" option must not be ${fdVerbose}. Allowed values are: ${allowedValues} or a function.`);37 }38 }39 };40-41-const VERBOSE_VALUES = new Set(['none', 'short', 'full']);42-43-// The `verbose` option can have different values for `stdout`/`stderr`44-export const isVerbose = ({verbose}) => getFdGenericVerbose(verbose) !== 'none';45-46-// Whether IPC and output and logged47-export const isFullVerbose = ({verbose}, fdNumber) => getFdSpecificValue(verbose, fdNumber) === 'full';48-49-const getFdGenericVerbose = verbose => verbose.every(fdVerbose => fdVerbose === verbose[0])50- ? verbose[0]51- : verbose.find(fdVerbose => fdVerbose !== 'none');modified:lib/verbose/ipc.js+5 added-4 removed
1-import {verboseLog, serializeLogMessage} from './log.js';2-import {isFullVerbose} from './info.js';1+import {verboseLog, serializeVerboseMessage} from './log.js';2+import {isFullVerbose} from './values.js';3 4 // When `verbose` is `'full'`, print IPC messages from the subprocess5 export const shouldLogIpc = verboseInfo => isFullVerbose(verboseInfo, 'ipc');6 7 export const logIpcOutput = (message, verboseInfo) => {8- const logMessage = serializeLogMessage(message);8+ const verboseMessage = serializeVerboseMessage(message);9 verboseLog({10 type: 'ipc',11- logMessage,11+ verboseMessage,12+ fdNumber: 'ipc',13 verboseInfo,14 });15 };modified:lib/verbose/log.js+22 added-21 removed
1 import {writeFileSync} from 'node:fs';2 import {inspect} from 'node:util';3 import {escapeLines} from '../arguments/escape.js';4-import {defaultLogger} from './default.js';4+import {defaultVerboseFunction} from './default.js';5+import {applyVerboseOnLines} from './custom.js';6 7 // Write synchronously to ensure lines are properly ordered and not interleaved with `stdout`7-export 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`);8+export const verboseLog = ({type, verboseMessage, fdNumber, verboseInfo, result}) => {9+ const verboseObject = getVerboseObject({type, result, verboseInfo});10+ const printedLines = getPrintedLines(verboseMessage, verboseObject);11+ const finalLines = applyVerboseOnLines(printedLines, verboseInfo, fdNumber);12+ writeFileSync(STDERR_FD, finalLines);13 };14 18-const getLogObject = ({15+const getVerboseObject = ({16 type,20- failed = false,21- piped = false,22- verboseInfo: {commandId, rawOptions},17+ result,18+ verboseInfo: {escapedCommand, commandId, rawOptions: {piped = false, ...options}},19 }) => ({20 type,21+ escapedCommand,22+ commandId: `${commandId}`,23 timestamp: new Date(),26- failed,24 piped,28- commandId,29- options: rawOptions,25+ result,26+ options,27 });28 32-const getPrintedLines = (logMessage, logObject) => logMessage29+const getPrintedLines = (verboseMessage, verboseObject) => verboseMessage30 .split('\n')34- .map(message => defaultLogger({...logObject, message}))35- .join('\n');31+ .map(message => getPrintedLine({...verboseObject, message}));32 33+const getPrintedLine = verboseObject => {34+ const verboseLine = defaultVerboseFunction(verboseObject);35+ return {verboseLine, verboseObject};36+};37+38 // Unless a `verbose` function is used, print all logs on `stderr`39 const STDERR_FD = 2;40 41 // Serialize any type to a line string, for logging41-export const serializeLogMessage = message => {42+export const serializeVerboseMessage = message => {43 const messageString = typeof message === 'string' ? message : inspect(message);44 const escapedMessage = escapeLines(messageString);45 return escapedMessage.replaceAll('\t', ' '.repeat(TAB_SIZE));46 };3 unmodified linesmodified:lib/verbose/output.js+10 added-9 removed
1 import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';2 import {TRANSFORM_TYPES} from '../stdio/type.js';3-import {verboseLog, serializeLogMessage} from './log.js';4-import {isFullVerbose} from './info.js';3+import {verboseLog, serializeVerboseMessage} from './log.js';4+import {isFullVerbose} from './values.js';5 6 // `ignore` opts-out of `verbose` for a specific stream.7 // `ipc` cannot use piping.8 // `inherit` would result in double printing.14 unmodified lines23 24 const PIPED_STDIO_VALUES = new Set(['pipe', 'overlapped']);25 26 // `verbose: 'full'` printing logic with async methods27-export const logLines = async (linesIterable, stream, verboseInfo) => {27+export const logLines = async (linesIterable, stream, fdNumber, verboseInfo) => {28 for await (const line of linesIterable) {29 if (!isPipingStream(stream)) {30- logLine(line, verboseInfo);30+ logLine(line, fdNumber, verboseInfo);31 }32 }33 };34 35 // `verbose: 'full'` printing logic with sync methods36-export const logLinesSync = (linesArray, verboseInfo) => {36+export const logLinesSync = (linesArray, fdNumber, verboseInfo) => {37 for (const line of linesArray) {38- logLine(line, verboseInfo);38+ logLine(line, fdNumber, verboseInfo);39 }40 };41 42 // When `subprocess.stdout|stderr.pipe()` is called, `verbose` becomes a noop.5 unmodified lines48 // This is not a critical behavior since changes of the following property would only make `verbose` more verbose.49 const isPipingStream = stream => stream._readableState.pipes.length > 0;50 51 // When `verbose` is `full`, print stdout|stderr52-const logLine = (line, verboseInfo) => {53- const logMessage = serializeLogMessage(line);52+const logLine = (line, fdNumber, verboseInfo) => {53+ const verboseMessage = serializeVerboseMessage(line);54 verboseLog({55 type: 'output',56- logMessage,56+ verboseMessage,57+ fdNumber,58 verboseInfo,59 });60 };modified:lib/verbose/start.js+4 added-5 removed
1-import {isVerbose} from './info.js';1+import {isVerbose} from './values.js';2 import {verboseLog} from './log.js';3 4-// When `verbose` is `short|full`, print each command5-export const logCommand = (escapedCommand, verboseInfo, piped) => {4+// When `verbose` is `short|full|custom`, print each command5+export const logCommand = (escapedCommand, verboseInfo) => {6 if (!isVerbose(verboseInfo)) {7 return;8 }9 10 verboseLog({11 type: 'command',12- logMessage: escapedCommand,12+ verboseMessage: escapedCommand,13 verboseInfo,14- piped,14 });15 };added:lib/verbose/values.js+33 added
1+import {getFdSpecificValue} from '../arguments/specific.js';2+3+// The `verbose` option can have different values for `stdout`/`stderr`4+export const isVerbose = ({verbose}, fdNumber) => getFdVerbose(verbose, fdNumber) !== 'none';5+6+// Whether IPC and output and logged7+export const isFullVerbose = ({verbose}, fdNumber) => !['none', 'short'].includes(getFdVerbose(verbose, fdNumber));8+9+// The `verbose` option can be a function to customize logging10+export const getVerboseFunction = ({verbose}, fdNumber) => {11+ const fdVerbose = getFdVerbose(verbose, fdNumber);12+ return isVerboseFunction(fdVerbose) ? fdVerbose : undefined;13+};14+15+// When using `verbose: {stdout, stderr, fd3, ipc}`:16+// - `verbose.stdout|stderr|fd3` is used for 'output'17+// - `verbose.ipc` is only used for 'ipc'18+// - highest `verbose.*` value is used for 'command', 'error' and 'duration'19+const getFdVerbose = (verbose, fdNumber) => fdNumber === undefined20+ ? getFdGenericVerbose(verbose)21+ : getFdSpecificValue(verbose, fdNumber);22+23+// When using `verbose: {stdout, stderr, fd3, ipc}` and logging is not specific to a file descriptor.24+// We then use the highest `verbose.*` value, using the following order:25+// - function > 'full' > 'short' > 'none'26+// - if several functions are defined: stdout > stderr > fd3 > ipc27+const getFdGenericVerbose = verbose => verbose.find(fdVerbose => isVerboseFunction(fdVerbose))28+ ?? VERBOSE_VALUES.findLast(fdVerbose => verbose.includes(fdVerbose));29+30+// Whether the `verbose` option is customized using a function31+export const isVerboseFunction = fdVerbose => typeof fdVerbose === 'function';32+33+export const VERBOSE_VALUES = ['none', 'short', 'full'];added:test/fixtures/nested/custom-event.js+3 added
1+export const getOptions = ({type, eventProperty}) => ({2+ verbose: (verboseLine, verboseObject) => verboseObject.type === type ? `${verboseObject[eventProperty]}` : undefined,3+});added:test/fixtures/nested/custom-json.js+3 added
1+export const getOptions = ({type}) => ({2+ verbose: (verboseLine, verboseObject) => verboseObject.type === type ? JSON.stringify(verboseObject) : undefined,3+});added:test/fixtures/nested/custom-object-stdout.js+11 added
1+import {foobarObject} from '../../helpers/input.js';2+3+export const getOptions = () => ({4+ verbose: (verboseLine, {type}) => type === 'output' ? verboseLine : undefined,5+ stdout: {6+ * transform() {7+ yield foobarObject;8+ },9+ objectMode: true,10+ },11+});added:test/fixtures/nested/custom-option.js+3 added
1+export const getOptions = ({type, optionName}) => ({2+ verbose: (verboseLine, verboseObject) => verboseObject.type === type ? `${verboseObject.options[optionName]}` : undefined,3+});added:test/fixtures/nested/custom-print-function.js+10 added
1+export const getOptions = ({type, fdNumber, secondFdNumber}) => ({2+ verbose: {3+ [fdNumber](verboseLine, verboseObject) {4+ if (verboseObject.type === type) {5+ console.warn(verboseLine);6+ }7+ },8+ [secondFdNumber]: 'none',9+ },10+});added:test/fixtures/nested/custom-print-multiple.js+10 added
1+export const getOptions = ({type, fdNumber, secondFdNumber}) => ({2+ verbose: {3+ [fdNumber](verboseLine, verboseObject) {4+ if (verboseObject.type === type) {5+ console.warn(verboseLine);6+ }7+ },8+ [secondFdNumber]() {},9+ },10+});added:test/fixtures/nested/custom-print.js+10 added
1+export const getOptions = ({type, fdNumber}) => ({2+ verbose: setFdSpecific(3+ fdNumber,4+ (verboseLine, verboseObject) => verboseObject.type === type ? verboseLine : undefined,5+ ),6+});7+8+const setFdSpecific = (fdNumber, option) => fdNumber === undefined9+ ? option10+ : {[fdNumber]: option};added:test/fixtures/nested/custom-result.js+3 added
1+export const getOptions = ({type}) => ({2+ verbose: (verboseLine, verboseObject) => verboseObject.type === type ? JSON.stringify(verboseObject.result) : undefined,3+});added:test/fixtures/nested/custom-return.js+5 added
1+export const getOptions = ({verboseOutput}) => ({2+ verbose(verboseLine, {type}) {3+ return type === 'command' ? verboseOutput : undefined;4+ },5+});added:test/fixtures/nested/custom-throw.js+7 added
1+export const getOptions = ({type, errorMessage}) => ({2+ verbose(verboseLine, verboseObject) {3+ if (verboseObject.type === type) {4+ throw new Error(errorMessage);5+ }6+ },7+});added:test/fixtures/nested/custom-uppercase.js+5 added
1+export const getOptions = () => ({2+ verbose(verboseLine, {type}) {3+ return type === 'command' ? verboseLine.replace('noop', 'NOOP') : undefined;4+ },5+});added:test/fixtures/nested-pipe-verbose.js+21 added
1+#!/usr/bin/env node2+import {execa, getOneMessage, sendMessage} from '../../index.js';3+import {getNestedOptions} from '../helpers/nested.js';4+5+const {6+ file,7+ commandArguments = [],8+ options: {destinationFile, destinationArguments, ...options},9+ optionsFixture,10+ optionsInput,11+} = await getOneMessage();12+13+const commandOptions = await getNestedOptions(options, optionsFixture, optionsInput);14+15+try {16+ const result = await execa(file, commandArguments, commandOptions)17+ .pipe(destinationFile, destinationArguments, commandOptions);18+ await sendMessage(result);19+} catch (error) {20+ await sendMessage(error);21+}modified:test/fixtures/nested.js+2 added-8 removed
3 unmodified lines4 execaSync,5 getOneMessage,6 sendMessage,7 } from '../../index.js';8+import {getNestedOptions} from '../helpers/nested.js';9 10 const {11 isSync,12 file,2 unmodified lines15 optionsFixture,16 optionsInput,17 } = await getOneMessage();18 18-let commandOptions = options;19+const commandOptions = await getNestedOptions(options, optionsFixture, optionsInput);20 20-// Some subprocess options cannot be serialized between processes.21-// For those, we pass a fixture filename instead, which dynamically creates the options.22-if (optionsFixture !== undefined) {23- const {getOptions} = await import(`./nested/${optionsFixture}`);24- commandOptions = {...commandOptions, ...getOptions({...commandOptions, ...optionsInput})};25-}26-21 try {22 const result = isSync23 ? execaSync(file, commandArguments, commandOptions)24 : await execa(file, commandArguments, commandOptions);4 unmodified linesadded:test/fixtures/noop-verbose.js+12 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {sendMessage} from '../../index.js';4+5+const bytes = process.argv[2];6+console.log(bytes);7+8+try {9+ await sendMessage(bytes);10+} catch {}11+12+process.exitCode = 2;modified:test/helpers/nested.js+12 added
2 unmodified lines3 import {execa} from '../../index.js';4 import {FIXTURES_DIRECTORY_URL} from './fixtures-directory.js';5 6 const WORKER_URL = new URL('worker.js', FIXTURES_DIRECTORY_URL);7+const NESTED_URL = new URL('nested/', FIXTURES_DIRECTORY_URL);8 9 // Like `execa(file, commandArguments, options)` but spawns inside another parent process.10 // This is useful when testing logic where Execa modifies the global state.11 // For example, when it prints to the console, with the `verbose` option.43 unmodified lines55 return result;56 };57 58 export const spawnParentProcess = ({parentFixture, parentOptions, ...ipcInput}) => execa(parentFixture, {...parentOptions, ipcInput});59+60+// Some subprocess options cannot be serialized between processes.61+// For those, we pass a fixture filename instead, which dynamically creates the options.62+export const getNestedOptions = async (options, optionsFixture, optionsInput) => {63+ if (optionsFixture === undefined) {64+ return options;65+ }66+67+ const {getOptions} = await import(new URL(optionsFixture, NESTED_URL));68+ return {...options, ...getOptions({...options, ...optionsInput})};69+};modified:test/helpers/verbose.js+28 added-1 removed
25 unmodified lines26 27 export const runEarlyErrorSubprocess = async (t, isSync) => {28 const {stderr, nestedResult} = await nestedSubprocess('noop.js', [foobarString], {verbose: 'short', cwd: true, isSync});29 t.true(nestedResult instanceof Error);30- t.true(stderr.includes('The "cwd" option must'));30+ t.true(nestedResult.message.startsWith('The "cwd" option must'));31 return stderr;32 };33 34+export const runVerboseSubprocess = ({35+ isSync = false,36+ type,37+ eventProperty,38+ optionName,39+ errorMessage,40+ fdNumber,41+ secondFdNumber,42+ optionsFixture = 'custom-event.js',43+ output = '. .',44+ ...options45+}) => nestedSubprocess('noop-verbose.js', [output], {46+ ipc: !isSync,47+ optionsFixture,48+ optionsInput: {49+ type,50+ eventProperty,51+ optionName,52+ errorMessage,53+ fdNumber,54+ secondFdNumber,55+ },56+ isSync,57+ ...options,58+});59+60 export const getCommandLine = stderr => getCommandLines(stderr)[0];61 export const getCommandLines = stderr => getNormalizedLines(stderr).filter(line => isCommandLine(line));62 const isCommandLine = line => line.includes(' $ ') || line.includes(' | ');63 export const getOutputLine = stderr => getOutputLines(stderr)[0];7 unmodified lines71 const isErrorLine = line => (line.includes(' × ') || line.includes(' ‼ ')) && !isCompletionLine(line);72 export const getCompletionLine = stderr => getCompletionLines(stderr)[0];73 export const getCompletionLines = stderr => getNormalizedLines(stderr).filter(line => isCompletionLine(line));74 const isCompletionLine = line => line.includes('(done in');75+export const getNormalizedLine = stderr => getNormalizedLines(stderr)[0];76 export const getNormalizedLines = stderr => splitLines(normalizeStderr(stderr));77 const splitLines = stderr => stderr.split('\n');78 79 const normalizeStderr = stderr => replaceSymbols(normalizeDuration(normalizeTimestamp(stripVTControlCharacters(stderr))), {useFallback: true});18 unmodified linesmodified:test/verbose/complete.js+1 added-1 removed
89 unmodified lines90 test('Prints completion after errors, "reject" false, sync', testPrintCompletionWarning, true);91 92 const testPrintCompletionEarly = async (t, isSync) => {93 const stderr = await runEarlyErrorSubprocess(t, isSync);94- t.is(getCompletionLine(stderr), `${testTimestamp} [0] × (done in 0ms)`);94+ t.is(getCompletionLine(stderr), undefined);95 };96 97 test('Prints completion after early validation errors', testPrintCompletionEarly, false);98 test('Prints completion after early validation errors, sync', testPrintCompletionEarly, true);31 unmodified linesadded:test/verbose/custom-command.js+97 added
1+import test from 'ava';2+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';3+import {fullStdio} from '../helpers/stdio.js';4+import {5+ QUOTE,6+ getNormalizedLine,7+ testTimestamp,8+ runVerboseSubprocess,9+} from '../helpers/verbose.js';10+11+setFixtureDirectory();12+13+const testPrintCommandCustom = async (t, fdNumber, isSync) => {14+ const {stderr} = await runVerboseSubprocess({15+ optionsFixture: 'custom-print.js',16+ isSync,17+ type: 'command',18+ fdNumber,19+ });20+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] $ noop-verbose.js ${QUOTE}. .${QUOTE}`);21+};22+23+test('Prints command, verbose custom', testPrintCommandCustom, undefined, false);24+test('Prints command, verbose custom, fd-specific stdout', testPrintCommandCustom, 'stdout', false);25+test('Prints command, verbose custom, fd-specific stderr', testPrintCommandCustom, 'stderr', false);26+test('Prints command, verbose custom, fd-specific fd3', testPrintCommandCustom, 'fd3', false);27+test('Prints command, verbose custom, fd-specific ipc', testPrintCommandCustom, 'ipc', false);28+test('Prints command, verbose custom, sync', testPrintCommandCustom, undefined, true);29+test('Prints command, verbose custom, fd-specific stdout, sync', testPrintCommandCustom, 'stdout', true);30+test('Prints command, verbose custom, fd-specific stderr, sync', testPrintCommandCustom, 'stderr', true);31+test('Prints command, verbose custom, fd-specific fd3, sync', testPrintCommandCustom, 'fd3', true);32+test('Prints command, verbose custom, fd-specific ipc, sync', testPrintCommandCustom, 'ipc', true);33+34+const testPrintCommandOrder = async (t, fdNumber, secondFdNumber, hasOutput) => {35+ const {stderr} = await runVerboseSubprocess({36+ optionsFixture: 'custom-print-multiple.js',37+ type: 'command',38+ fdNumber,39+ secondFdNumber,40+ ...fullStdio,41+ });42+43+ if (hasOutput) {44+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] $ noop-verbose.js ${QUOTE}. .${QUOTE}`);45+ } else {46+ t.is(stderr, '');47+ }48+};49+50+test('Prints command, verbose custom, fd-specific stdout+stderr', testPrintCommandOrder, 'stdout', 'stderr', true);51+test('Prints command, verbose custom, fd-specific stderr+stdout', testPrintCommandOrder, 'stderr', 'stdout', false);52+test('Prints command, verbose custom, fd-specific stdout+fd3', testPrintCommandOrder, 'stdout', 'fd3', true);53+test('Prints command, verbose custom, fd-specific fd3+stdout', testPrintCommandOrder, 'fd3', 'stdout', false);54+test('Prints command, verbose custom, fd-specific stdout+ipc', testPrintCommandOrder, 'stdout', 'ipc', true);55+test('Prints command, verbose custom, fd-specific ipc+stdout', testPrintCommandOrder, 'ipc', 'stdout', false);56+test('Prints command, verbose custom, fd-specific stderr+fd3', testPrintCommandOrder, 'stderr', 'fd3', true);57+test('Prints command, verbose custom, fd-specific fd3+stderr', testPrintCommandOrder, 'fd3', 'stderr', false);58+test('Prints command, verbose custom, fd-specific stderr+ipc', testPrintCommandOrder, 'stderr', 'ipc', true);59+test('Prints command, verbose custom, fd-specific ipc+stderr', testPrintCommandOrder, 'ipc', 'stderr', false);60+test('Prints command, verbose custom, fd-specific fd3+ipc', testPrintCommandOrder, 'fd3', 'ipc', true);61+test('Prints command, verbose custom, fd-specific ipc+fd3', testPrintCommandOrder, 'ipc', 'fd3', false);62+63+const testPrintCommandFunction = async (t, fdNumber, secondFdNumber) => {64+ const {stderr} = await runVerboseSubprocess({65+ optionsFixture: 'custom-print-function.js',66+ type: 'command',67+ fdNumber,68+ secondFdNumber,69+ ...fullStdio,70+ });71+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] $ noop-verbose.js ${QUOTE}. .${QUOTE}`);72+};73+74+test('Prints command, verbose custom, fd-specific stdout+stderr, single function', testPrintCommandFunction, 'stdout', 'stderr');75+test('Prints command, verbose custom, fd-specific stderr+stdout, single function', testPrintCommandFunction, 'stderr', 'stdout');76+test('Prints command, verbose custom, fd-specific stdout+fd3, single function', testPrintCommandFunction, 'stdout', 'fd3');77+test('Prints command, verbose custom, fd-specific fd3+stdout, single function', testPrintCommandFunction, 'fd3', 'stdout');78+test('Prints command, verbose custom, fd-specific stdout+ipc, single function', testPrintCommandFunction, 'stdout', 'ipc');79+test('Prints command, verbose custom, fd-specific ipc+stdout, single function', testPrintCommandFunction, 'ipc', 'stdout');80+test('Prints command, verbose custom, fd-specific stderr+fd3, single function', testPrintCommandFunction, 'stderr', 'fd3');81+test('Prints command, verbose custom, fd-specific fd3+stderr, single function', testPrintCommandFunction, 'fd3', 'stderr');82+test('Prints command, verbose custom, fd-specific stderr+ipc, single function', testPrintCommandFunction, 'stderr', 'ipc');83+test('Prints command, verbose custom, fd-specific ipc+stderr, single function', testPrintCommandFunction, 'ipc', 'stderr');84+test('Prints command, verbose custom, fd-specific fd3+ipc, single function', testPrintCommandFunction, 'fd3', 'ipc');85+test('Prints command, verbose custom, fd-specific ipc+fd3, single function', testPrintCommandFunction, 'ipc', 'fd3');86+87+const testVerboseMessage = async (t, isSync) => {88+ const {stderr} = await runVerboseSubprocess({89+ isSync,90+ type: 'command',91+ eventProperty: 'message',92+ });93+ t.is(getNormalizedLine(stderr), `noop-verbose.js ${QUOTE}. .${QUOTE}`);94+};95+96+test('"verbose" function receives verboseObject.message', testVerboseMessage, false);97+test('"verbose" function receives verboseObject.message, sync', testVerboseMessage, true);added:test/verbose/custom-common.js+48 added
1+import test from 'ava';2+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';3+import {foobarString} from '../helpers/input.js';4+import {nestedSubprocess} from '../helpers/nested.js';5+import {QUOTE, getCommandLine, testTimestamp} from '../helpers/verbose.js';6+7+setFixtureDirectory();8+9+const testCustomReturn = async (t, verboseOutput, expectedOutput) => {10+ const {stderr} = await nestedSubprocess(11+ 'empty.js',12+ {optionsFixture: 'custom-return.js', optionsInput: {verboseOutput}},13+ {stripFinalNewline: false},14+ );15+ t.is(stderr, expectedOutput);16+};17+18+test('"verbose" returning a string prints it', testCustomReturn, `${foobarString}\n`, `${foobarString}\n`);19+test('"verbose" returning a string without a newline adds it', testCustomReturn, foobarString, `${foobarString}\n`);20+test('"verbose" returning a string with multiple newlines keeps them', testCustomReturn, `${foobarString}\n\n`, `${foobarString}\n\n`);21+test('"verbose" returning an empty string prints an empty line', testCustomReturn, '', '\n');22+test('"verbose" returning undefined ignores it', testCustomReturn, undefined, '');23+test('"verbose" returning a number ignores it', testCustomReturn, 0, '');24+test('"verbose" returning a bigint ignores it', testCustomReturn, 0n, '');25+test('"verbose" returning a boolean ignores it', testCustomReturn, true, '');26+test('"verbose" returning an object ignores it', testCustomReturn, {}, '');27+test('"verbose" returning an array ignores it', testCustomReturn, [], '');28+29+test('"verbose" receives verboseLine string as first argument', async t => {30+ const {stderr} = await nestedSubprocess('noop.js', [foobarString], {optionsFixture: 'custom-uppercase.js'});31+ t.is(getCommandLine(stderr), `${testTimestamp} [0] $ NOOP.js ${foobarString}`);32+});33+34+test('"verbose" can print as JSON', async t => {35+ const {stderr} = await nestedSubprocess('noop.js', ['. .'], {optionsFixture: 'custom-json.js', type: 'duration', reject: false});36+ const {type, message, escapedCommand, commandId, timestamp, piped, result, options} = JSON.parse(stderr);37+ t.is(type, 'duration');38+ t.true(message.includes('done in'));39+ t.is(escapedCommand, `noop.js ${QUOTE}. .${QUOTE}`);40+ t.is(commandId, '0');41+ t.true(Number.isInteger(new Date(timestamp).getTime()));42+ t.false(piped);43+ t.false(result.failed);44+ t.is(result.exitCode, 0);45+ t.is(result.stdout, '. .');46+ t.is(result.stderr, '');47+ t.false(options.reject);48+});added:test/verbose/custom-complete.js+92 added
1+import test from 'ava';2+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';3+import {fullStdio} from '../helpers/stdio.js';4+import {getNormalizedLine, testTimestamp, runVerboseSubprocess} from '../helpers/verbose.js';5+6+setFixtureDirectory();7+8+const testPrintCompletionCustom = async (t, fdNumber, isSync) => {9+ const {stderr} = await runVerboseSubprocess({10+ optionsFixture: 'custom-print.js',11+ isSync,12+ type: 'duration',13+ fdNumber,14+ });15+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] × (done in 0ms)`);16+};17+18+test('Prints completion, verbose custom', testPrintCompletionCustom, undefined, false);19+test('Prints completion, verbose custom, fd-specific stdout', testPrintCompletionCustom, 'stdout', false);20+test('Prints completion, verbose custom, fd-specific stderr', testPrintCompletionCustom, 'stderr', false);21+test('Prints completion, verbose custom, fd-specific fd3', testPrintCompletionCustom, 'fd3', false);22+test('Prints completion, verbose custom, fd-specific ipc', testPrintCompletionCustom, 'ipc', false);23+test('Prints completion, verbose custom, sync', testPrintCompletionCustom, undefined, true);24+test('Prints completion, verbose custom, fd-specific stdout, sync', testPrintCompletionCustom, 'stdout', true);25+test('Prints completion, verbose custom, fd-specific stderr, sync', testPrintCompletionCustom, 'stderr', true);26+test('Prints completion, verbose custom, fd-specific fd3, sync', testPrintCompletionCustom, 'fd3', true);27+test('Prints completion, verbose custom, fd-specific ipc, sync', testPrintCompletionCustom, 'ipc', true);28+29+const testPrintCompletionOrder = async (t, fdNumber, secondFdNumber, hasOutput) => {30+ const {stderr} = await runVerboseSubprocess({31+ optionsFixture: 'custom-print-multiple.js',32+ type: 'duration',33+ fdNumber,34+ secondFdNumber,35+ ...fullStdio,36+ });37+38+ if (hasOutput) {39+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] × (done in 0ms)`);40+ } else {41+ t.is(stderr, '');42+ }43+};44+45+test('Prints completion, verbose custom, fd-specific stdout+stderr', testPrintCompletionOrder, 'stdout', 'stderr', true);46+test('Prints completion, verbose custom, fd-specific stderr+stdout', testPrintCompletionOrder, 'stderr', 'stdout', false);47+test('Prints completion, verbose custom, fd-specific stdout+fd3', testPrintCompletionOrder, 'stdout', 'fd3', true);48+test('Prints completion, verbose custom, fd-specific fd3+stdout', testPrintCompletionOrder, 'fd3', 'stdout', false);49+test('Prints completion, verbose custom, fd-specific stdout+ipc', testPrintCompletionOrder, 'stdout', 'ipc', true);50+test('Prints completion, verbose custom, fd-specific ipc+stdout', testPrintCompletionOrder, 'ipc', 'stdout', false);51+test('Prints completion, verbose custom, fd-specific stderr+fd3', testPrintCompletionOrder, 'stderr', 'fd3', true);52+test('Prints completion, verbose custom, fd-specific fd3+stderr', testPrintCompletionOrder, 'fd3', 'stderr', false);53+test('Prints completion, verbose custom, fd-specific stderr+ipc', testPrintCompletionOrder, 'stderr', 'ipc', true);54+test('Prints completion, verbose custom, fd-specific ipc+stderr', testPrintCompletionOrder, 'ipc', 'stderr', false);55+test('Prints completion, verbose custom, fd-specific fd3+ipc', testPrintCompletionOrder, 'fd3', 'ipc', true);56+test('Prints completion, verbose custom, fd-specific ipc+fd3', testPrintCompletionOrder, 'ipc', 'fd3', false);57+58+const testPrintCompletionFunction = async (t, fdNumber, secondFdNumber) => {59+ const {stderr} = await runVerboseSubprocess({60+ optionsFixture: 'custom-print-function.js',61+ type: 'duration',62+ fdNumber,63+ secondFdNumber,64+ ...fullStdio,65+ });66+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] × (done in 0ms)`);67+};68+69+test('Prints completion, verbose custom, fd-specific stdout+stderr, single function', testPrintCompletionFunction, 'stdout', 'stderr');70+test('Prints completion, verbose custom, fd-specific stderr+stdout, single function', testPrintCompletionFunction, 'stderr', 'stdout');71+test('Prints completion, verbose custom, fd-specific stdout+fd3, single function', testPrintCompletionFunction, 'stdout', 'fd3');72+test('Prints completion, verbose custom, fd-specific fd3+stdout, single function', testPrintCompletionFunction, 'fd3', 'stdout');73+test('Prints completion, verbose custom, fd-specific stdout+ipc, single function', testPrintCompletionFunction, 'stdout', 'ipc');74+test('Prints completion, verbose custom, fd-specific ipc+stdout, single function', testPrintCompletionFunction, 'ipc', 'stdout');75+test('Prints completion, verbose custom, fd-specific stderr+fd3, single function', testPrintCompletionFunction, 'stderr', 'fd3');76+test('Prints completion, verbose custom, fd-specific fd3+stderr, single function', testPrintCompletionFunction, 'fd3', 'stderr');77+test('Prints completion, verbose custom, fd-specific stderr+ipc, single function', testPrintCompletionFunction, 'stderr', 'ipc');78+test('Prints completion, verbose custom, fd-specific ipc+stderr, single function', testPrintCompletionFunction, 'ipc', 'stderr');79+test('Prints completion, verbose custom, fd-specific fd3+ipc, single function', testPrintCompletionFunction, 'fd3', 'ipc');80+test('Prints completion, verbose custom, fd-specific ipc+fd3, single function', testPrintCompletionFunction, 'ipc', 'fd3');81+82+const testVerboseMessage = async (t, isSync) => {83+ const {stderr} = await runVerboseSubprocess({84+ isSync,85+ type: 'duration',86+ eventProperty: 'message',87+ });88+ t.is(getNormalizedLine(stderr), '(done in 0ms)');89+};90+91+test('"verbose" function receives verboseObject.message', testVerboseMessage, false);92+test('"verbose" function receives verboseObject.message, sync', testVerboseMessage, true);added:test/verbose/custom-error.js+97 added
1+import test from 'ava';2+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';3+import {fullStdio} from '../helpers/stdio.js';4+import {5+ QUOTE,6+ getNormalizedLine,7+ testTimestamp,8+ runVerboseSubprocess,9+} from '../helpers/verbose.js';10+11+setFixtureDirectory();12+13+const testPrintErrorCustom = async (t, fdNumber, isSync) => {14+ const {stderr} = await runVerboseSubprocess({15+ optionsFixture: 'custom-print.js',16+ isSync,17+ type: 'error',18+ fdNumber,19+ });20+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] × Command failed with exit code 2: noop-verbose.js ${QUOTE}. .${QUOTE}`);21+};22+23+test('Prints error, verbose custom', testPrintErrorCustom, undefined, false);24+test('Prints error, verbose custom, fd-specific stdout', testPrintErrorCustom, 'stdout', false);25+test('Prints error, verbose custom, fd-specific stderr', testPrintErrorCustom, 'stderr', false);26+test('Prints error, verbose custom, fd-specific fd3', testPrintErrorCustom, 'fd3', false);27+test('Prints error, verbose custom, fd-specific ipc', testPrintErrorCustom, 'ipc', false);28+test('Prints error, verbose custom, sync', testPrintErrorCustom, undefined, true);29+test('Prints error, verbose custom, fd-specific stdout, sync', testPrintErrorCustom, 'stdout', true);30+test('Prints error, verbose custom, fd-specific stderr, sync', testPrintErrorCustom, 'stderr', true);31+test('Prints error, verbose custom, fd-specific fd3, sync', testPrintErrorCustom, 'fd3', true);32+test('Prints error, verbose custom, fd-specific ipc, sync', testPrintErrorCustom, 'ipc', true);33+34+const testPrintErrorOrder = async (t, fdNumber, secondFdNumber, hasOutput) => {35+ const {stderr} = await runVerboseSubprocess({36+ optionsFixture: 'custom-print-multiple.js',37+ type: 'error',38+ fdNumber,39+ secondFdNumber,40+ ...fullStdio,41+ });42+43+ if (hasOutput) {44+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] × Command failed with exit code 2: noop-verbose.js ${QUOTE}. .${QUOTE}`);45+ } else {46+ t.is(stderr, '');47+ }48+};49+50+test('Prints error, verbose custom, fd-specific stdout+stderr', testPrintErrorOrder, 'stdout', 'stderr', true);51+test('Prints error, verbose custom, fd-specific stderr+stdout', testPrintErrorOrder, 'stderr', 'stdout', false);52+test('Prints error, verbose custom, fd-specific stdout+fd3', testPrintErrorOrder, 'stdout', 'fd3', true);53+test('Prints error, verbose custom, fd-specific fd3+stdout', testPrintErrorOrder, 'fd3', 'stdout', false);54+test('Prints error, verbose custom, fd-specific stdout+ipc', testPrintErrorOrder, 'stdout', 'ipc', true);55+test('Prints error, verbose custom, fd-specific ipc+stdout', testPrintErrorOrder, 'ipc', 'stdout', false);56+test('Prints error, verbose custom, fd-specific stderr+fd3', testPrintErrorOrder, 'stderr', 'fd3', true);57+test('Prints error, verbose custom, fd-specific fd3+stderr', testPrintErrorOrder, 'fd3', 'stderr', false);58+test('Prints error, verbose custom, fd-specific stderr+ipc', testPrintErrorOrder, 'stderr', 'ipc', true);59+test('Prints error, verbose custom, fd-specific ipc+stderr', testPrintErrorOrder, 'ipc', 'stderr', false);60+test('Prints error, verbose custom, fd-specific fd3+ipc', testPrintErrorOrder, 'fd3', 'ipc', true);61+test('Prints error, verbose custom, fd-specific ipc+fd3', testPrintErrorOrder, 'ipc', 'fd3', false);62+63+const testPrintErrorFunction = async (t, fdNumber, secondFdNumber) => {64+ const {stderr} = await runVerboseSubprocess({65+ optionsFixture: 'custom-print-function.js',66+ type: 'error',67+ fdNumber,68+ secondFdNumber,69+ ...fullStdio,70+ });71+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] × Command failed with exit code 2: noop-verbose.js ${QUOTE}. .${QUOTE}`);72+};73+74+test('Prints error, verbose custom, fd-specific stdout+stderr, single function', testPrintErrorFunction, 'stdout', 'stderr');75+test('Prints error, verbose custom, fd-specific stderr+stdout, single function', testPrintErrorFunction, 'stderr', 'stdout');76+test('Prints error, verbose custom, fd-specific stdout+fd3, single function', testPrintErrorFunction, 'stdout', 'fd3');77+test('Prints error, verbose custom, fd-specific fd3+stdout, single function', testPrintErrorFunction, 'fd3', 'stdout');78+test('Prints error, verbose custom, fd-specific stdout+ipc, single function', testPrintErrorFunction, 'stdout', 'ipc');79+test('Prints error, verbose custom, fd-specific ipc+stdout, single function', testPrintErrorFunction, 'ipc', 'stdout');80+test('Prints error, verbose custom, fd-specific stderr+fd3, single function', testPrintErrorFunction, 'stderr', 'fd3');81+test('Prints error, verbose custom, fd-specific fd3+stderr, single function', testPrintErrorFunction, 'fd3', 'stderr');82+test('Prints error, verbose custom, fd-specific stderr+ipc, single function', testPrintErrorFunction, 'stderr', 'ipc');83+test('Prints error, verbose custom, fd-specific ipc+stderr, single function', testPrintErrorFunction, 'ipc', 'stderr');84+test('Prints error, verbose custom, fd-specific fd3+ipc, single function', testPrintErrorFunction, 'fd3', 'ipc');85+test('Prints error, verbose custom, fd-specific ipc+fd3, single function', testPrintErrorFunction, 'ipc', 'fd3');86+87+const testVerboseMessage = async (t, isSync) => {88+ const {stderr} = await runVerboseSubprocess({89+ isSync,90+ type: 'error',91+ eventProperty: 'message',92+ });93+ t.is(stderr, `Command failed with exit code 2: noop-verbose.js ${QUOTE}. .${QUOTE}`);94+};95+96+test('"verbose" function receives verboseObject.message', testVerboseMessage, false);97+test('"verbose" function receives verboseObject.message, sync', testVerboseMessage, true);added:test/verbose/custom-event.js+57 added
1+import test from 'ava';2+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';3+import {runVerboseSubprocess} from '../helpers/verbose.js';4+5+setFixtureDirectory();6+7+const testVerboseType = async (t, type, isSync) => {8+ const {stderr} = await runVerboseSubprocess({isSync, type, eventProperty: 'type'});9+ t.is(stderr, type);10+};11+12+test('"verbose" function receives verboseObject.type "command"', testVerboseType, 'command', false);13+test('"verbose" function receives verboseObject.type "output"', testVerboseType, 'output', false);14+test('"verbose" function receives verboseObject.type "ipc"', testVerboseType, 'ipc', false);15+test('"verbose" function receives verboseObject.type "error"', testVerboseType, 'error', false);16+test('"verbose" function receives verboseObject.type "duration"', testVerboseType, 'duration', false);17+test('"verbose" function receives verboseObject.type "command", sync', testVerboseType, 'command', true);18+test('"verbose" function receives verboseObject.type "output", sync', testVerboseType, 'output', true);19+test('"verbose" function receives verboseObject.type "error", sync', testVerboseType, 'error', true);20+test('"verbose" function receives verboseObject.type "duration", sync', testVerboseType, 'duration', true);21+22+const testVerboseTimestamp = async (t, type, isSync) => {23+ const {stderr} = await runVerboseSubprocess({isSync, type, eventProperty: 'timestamp'});24+ t.true(Number.isInteger(new Date(stderr).getTime()));25+};26+27+test('"verbose" function receives verboseObject.timestamp, "command"', testVerboseTimestamp, 'command', false);28+test('"verbose" function receives verboseObject.timestamp, "output"', testVerboseTimestamp, 'output', false);29+test('"verbose" function receives verboseObject.timestamp, "ipc"', testVerboseTimestamp, 'ipc', false);30+test('"verbose" function receives verboseObject.timestamp, "error"', testVerboseTimestamp, 'error', false);31+test('"verbose" function receives verboseObject.timestamp, "duration"', testVerboseTimestamp, 'duration', false);32+test('"verbose" function receives verboseObject.timestamp, "command", sync', testVerboseTimestamp, 'command', true);33+test('"verbose" function receives verboseObject.timestamp, "output", sync', testVerboseTimestamp, 'output', true);34+test('"verbose" function receives verboseObject.timestamp, "error", sync', testVerboseTimestamp, 'error', true);35+test('"verbose" function receives verboseObject.timestamp, "duration", sync', testVerboseTimestamp, 'duration', true);36+37+const testVerbosePiped = async (t, type, isSync, expectedOutputs) => {38+ const {stderr} = await runVerboseSubprocess({39+ isSync,40+ type,41+ parentFixture: 'nested-pipe-verbose.js',42+ destinationFile: 'noop-verbose.js',43+ destinationArguments: ['. . .'],44+ eventProperty: 'piped',45+ });46+ t.true(expectedOutputs.map(expectedOutput => expectedOutput.join('\n')).includes(stderr));47+};48+49+test('"verbose" function receives verboseObject.piped, "command"', testVerbosePiped, 'command', false, [[false, true]]);50+test('"verbose" function receives verboseObject.piped, "output"', testVerbosePiped, 'output', false, [[true]]);51+test('"verbose" function receives verboseObject.piped, "ipc"', testVerbosePiped, 'ipc', false, [[false, true], [true, false]]);52+test('"verbose" function receives verboseObject.piped, "error"', testVerbosePiped, 'error', false, [[false, true], [true, false]]);53+test('"verbose" function receives verboseObject.piped, "duration"', testVerbosePiped, 'duration', false, [[false, true], [true, false]]);54+test('"verbose" function receives verboseObject.piped, "command", sync', testVerbosePiped, 'command', true, [[false, true]]);55+test('"verbose" function receives verboseObject.piped, "output", sync', testVerbosePiped, 'output', true, [[true]]);56+test('"verbose" function receives verboseObject.piped, "error", sync', testVerbosePiped, 'error', true, [[false, true], [true, false]]);57+test('"verbose" function receives verboseObject.piped, "duration", sync', testVerbosePiped, 'duration', true, [[false, true], [true, false]]);added:test/verbose/custom-id.js+35 added
1+import test from 'ava';2+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';3+import {QUOTE, runVerboseSubprocess} from '../helpers/verbose.js';4+5+setFixtureDirectory();6+7+const testVerboseCommandId = async (t, type, isSync) => {8+ const {stderr} = await runVerboseSubprocess({isSync, type, eventProperty: 'commandId'});9+ t.is(stderr, '0');10+};11+12+test('"verbose" function receives verboseObject.commandId, "command"', testVerboseCommandId, 'command', false);13+test('"verbose" function receives verboseObject.commandId, "output"', testVerboseCommandId, 'output', false);14+test('"verbose" function receives verboseObject.commandId, "ipc"', testVerboseCommandId, 'ipc', false);15+test('"verbose" function receives verboseObject.commandId, "error"', testVerboseCommandId, 'error', false);16+test('"verbose" function receives verboseObject.commandId, "duration"', testVerboseCommandId, 'duration', false);17+test('"verbose" function receives verboseObject.commandId, "command", sync', testVerboseCommandId, 'command', true);18+test('"verbose" function receives verboseObject.commandId, "output", sync', testVerboseCommandId, 'output', true);19+test('"verbose" function receives verboseObject.commandId, "error", sync', testVerboseCommandId, 'error', true);20+test('"verbose" function receives verboseObject.commandId, "duration", sync', testVerboseCommandId, 'duration', true);21+22+const testVerboseEscapedCommand = async (t, type, isSync) => {23+ const {stderr} = await runVerboseSubprocess({isSync, type, eventProperty: 'escapedCommand'});24+ t.is(stderr, `noop-verbose.js ${QUOTE}. .${QUOTE}`);25+};26+27+test('"verbose" function receives verboseObject.escapedCommand, "command"', testVerboseEscapedCommand, 'command', false);28+test('"verbose" function receives verboseObject.escapedCommand, "output"', testVerboseEscapedCommand, 'output', false);29+test('"verbose" function receives verboseObject.escapedCommand, "ipc"', testVerboseEscapedCommand, 'ipc', false);30+test('"verbose" function receives verboseObject.escapedCommand, "error"', testVerboseEscapedCommand, 'error', false);31+test('"verbose" function receives verboseObject.escapedCommand, "duration"', testVerboseEscapedCommand, 'duration', false);32+test('"verbose" function receives verboseObject.escapedCommand, "command", sync', testVerboseEscapedCommand, 'command', true);33+test('"verbose" function receives verboseObject.escapedCommand, "output", sync', testVerboseEscapedCommand, 'output', true);34+test('"verbose" function receives verboseObject.escapedCommand, "error", sync', testVerboseEscapedCommand, 'error', true);35+test('"verbose" function receives verboseObject.escapedCommand, "duration", sync', testVerboseEscapedCommand, 'duration', true);added:test/verbose/custom-ipc.js+119 added
1+import {inspect} from 'node:util';2+import test from 'ava';3+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4+import {fullStdio} from '../helpers/stdio.js';5+import {6+ getNormalizedLine,7+ getNormalizedLines,8+ testTimestamp,9+ runVerboseSubprocess,10+} from '../helpers/verbose.js';11+import {nestedSubprocess} from '../helpers/nested.js';12+import {foobarObject} from '../helpers/input.js';13+14+setFixtureDirectory();15+16+const testPrintIpcCustom = async (t, fdNumber, hasOutput) => {17+ const {stderr} = await runVerboseSubprocess({18+ optionsFixture: 'custom-print.js',19+ type: 'ipc',20+ fdNumber,21+ ...fullStdio,22+ });23+24+ if (hasOutput) {25+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] * . .`);26+ } else {27+ t.is(stderr, '');28+ }29+};30+31+test('Prints IPC, verbose custom', testPrintIpcCustom, undefined, true);32+test('Prints IPC, verbose custom, fd-specific stdout', testPrintIpcCustom, 'stdout', false);33+test('Prints IPC, verbose custom, fd-specific stderr', testPrintIpcCustom, 'stderr', false);34+test('Prints IPC, verbose custom, fd-specific fd3', testPrintIpcCustom, 'fd3', false);35+test('Prints IPC, verbose custom, fd-specific ipc', testPrintIpcCustom, 'ipc', true);36+37+const testPrintIpcOrder = async (t, fdNumber, secondFdNumber, hasOutput) => {38+ const {stderr} = await runVerboseSubprocess({39+ optionsFixture: 'custom-print-multiple.js',40+ type: 'ipc',41+ fdNumber,42+ secondFdNumber,43+ ...fullStdio,44+ });45+46+ if (hasOutput) {47+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] * . .`);48+ } else {49+ t.is(stderr, '');50+ }51+};52+53+test('Prints IPC, verbose custom, fd-specific stdout+stderr', testPrintIpcOrder, 'stdout', 'stderr', false);54+test('Prints IPC, verbose custom, fd-specific stderr+stdout', testPrintIpcOrder, 'stderr', 'stdout', false);55+test('Prints IPC, verbose custom, fd-specific stdout+fd3', testPrintIpcOrder, 'stdout', 'fd3', false);56+test('Prints IPC, verbose custom, fd-specific fd3+stdout', testPrintIpcOrder, 'fd3', 'stdout', false);57+test('Prints IPC, verbose custom, fd-specific stdout+ipc', testPrintIpcOrder, 'stdout', 'ipc', false);58+test('Prints IPC, verbose custom, fd-specific ipc+stdout', testPrintIpcOrder, 'ipc', 'stdout', true);59+test('Prints IPC, verbose custom, fd-specific stderr+fd3', testPrintIpcOrder, 'stderr', 'fd3', false);60+test('Prints IPC, verbose custom, fd-specific fd3+stderr', testPrintIpcOrder, 'fd3', 'stderr', false);61+test('Prints IPC, verbose custom, fd-specific stderr+ipc', testPrintIpcOrder, 'stderr', 'ipc', false);62+test('Prints IPC, verbose custom, fd-specific ipc+stderr', testPrintIpcOrder, 'ipc', 'stderr', true);63+test('Prints IPC, verbose custom, fd-specific fd3+ipc', testPrintIpcOrder, 'fd3', 'ipc', false);64+test('Prints IPC, verbose custom, fd-specific ipc+fd3', testPrintIpcOrder, 'ipc', 'fd3', true);65+66+const testPrintIpcFunction = async (t, fdNumber, secondFdNumber, hasOutput) => {67+ const {stderr} = await runVerboseSubprocess({68+ optionsFixture: 'custom-print-function.js',69+ type: 'ipc',70+ fdNumber,71+ secondFdNumber,72+ ...fullStdio,73+ });74+75+ if (hasOutput) {76+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] * . .`);77+ } else {78+ t.is(stderr, '');79+ }80+};81+82+test('Prints IPC, verbose custom, fd-specific stdout+stderr, single function', testPrintIpcFunction, 'stdout', 'stderr', false);83+test('Prints IPC, verbose custom, fd-specific stderr+stdout, single function', testPrintIpcFunction, 'stderr', 'stdout', false);84+test('Prints IPC, verbose custom, fd-specific stdout+fd3, single function', testPrintIpcFunction, 'stdout', 'fd3', false);85+test('Prints IPC, verbose custom, fd-specific fd3+stdout, single function', testPrintIpcFunction, 'fd3', 'stdout', false);86+test('Prints IPC, verbose custom, fd-specific stdout+ipc, single function', testPrintIpcFunction, 'stdout', 'ipc', false);87+test('Prints IPC, verbose custom, fd-specific ipc+stdout, single function', testPrintIpcFunction, 'ipc', 'stdout', true);88+test('Prints IPC, verbose custom, fd-specific stderr+fd3, single function', testPrintIpcFunction, 'stderr', 'fd3', false);89+test('Prints IPC, verbose custom, fd-specific fd3+stderr, single function', testPrintIpcFunction, 'fd3', 'stderr', false);90+test('Prints IPC, verbose custom, fd-specific stderr+ipc, single function', testPrintIpcFunction, 'stderr', 'ipc', false);91+test('Prints IPC, verbose custom, fd-specific ipc+stderr, single function', testPrintIpcFunction, 'ipc', 'stderr', true);92+test('Prints IPC, verbose custom, fd-specific fd3+ipc, single function', testPrintIpcFunction, 'fd3', 'ipc', false);93+test('Prints IPC, verbose custom, fd-specific ipc+fd3, single function', testPrintIpcFunction, 'ipc', 'fd3', true);94+95+test('"verbose" function receives verboseObject.message', async t => {96+ const {stderr} = await runVerboseSubprocess({97+ type: 'ipc',98+ eventProperty: 'message',99+ });100+ t.is(stderr, '. .');101+});102+103+test('"verbose" function receives verboseObject.message line-wise', async t => {104+ const {stderr} = await runVerboseSubprocess({105+ optionsFixture: 'custom-print.js',106+ type: 'ipc',107+ output: '.\n.',108+ });109+ t.deepEqual(getNormalizedLines(stderr), [`${testTimestamp} [0] * .`, `${testTimestamp} [0] * .`]);110+});111+112+test('"verbose" function receives verboseObject.message serialized', async t => {113+ const {stderr} = await nestedSubprocess('ipc-echo.js', {114+ ipcInput: foobarObject,115+ optionsFixture: 'custom-print.js',116+ optionsInput: {type: 'ipc'},117+ });118+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] * ${inspect(foobarObject)}`);119+});added:test/verbose/custom-options.js+47 added
1+import test from 'ava';2+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';3+import {runVerboseSubprocess} from '../helpers/verbose.js';4+5+setFixtureDirectory();6+7+const testVerboseOptionsExplicit = async (t, type, isSync) => {8+ const maxBuffer = 1000;9+ const {stderr} = await runVerboseSubprocess({10+ isSync,11+ type,12+ optionsFixture: 'custom-option.js',13+ optionName: 'maxBuffer',14+ maxBuffer,15+ });16+ t.is(stderr, `${maxBuffer}`);17+};18+19+test('"verbose" function receives verboseObject.options explicitly set, "command"', testVerboseOptionsExplicit, 'command', false);20+test('"verbose" function receives verboseObject.options explicitly set, "output"', testVerboseOptionsExplicit, 'output', false);21+test('"verbose" function receives verboseObject.options explicitly set, "ipc"', testVerboseOptionsExplicit, 'ipc', false);22+test('"verbose" function receives verboseObject.options explicitly set, "error"', testVerboseOptionsExplicit, 'error', false);23+test('"verbose" function receives verboseObject.options explicitly set, "duration"', testVerboseOptionsExplicit, 'duration', false);24+test('"verbose" function receives verboseObject.options explicitly set, "command", sync', testVerboseOptionsExplicit, 'command', true);25+test('"verbose" function receives verboseObject.options explicitly set, "output", sync', testVerboseOptionsExplicit, 'output', true);26+test('"verbose" function receives verboseObject.options explicitly set, "error", sync', testVerboseOptionsExplicit, 'error', true);27+test('"verbose" function receives verboseObject.options explicitly set, "duration", sync', testVerboseOptionsExplicit, 'duration', true);28+29+const testVerboseOptionsDefault = async (t, type, isSync) => {30+ const {stderr} = await runVerboseSubprocess({31+ isSync,32+ type,33+ optionsFixture: 'custom-option.js',34+ optionName: 'maxBuffer',35+ });36+ t.is(stderr, 'undefined');37+};38+39+test('"verbose" function receives verboseObject.options before default values and normalization, "command"', testVerboseOptionsDefault, 'command', false);40+test('"verbose" function receives verboseObject.options before default values and normalization, "output"', testVerboseOptionsDefault, 'output', false);41+test('"verbose" function receives verboseObject.options before default values and normalization, "ipc"', testVerboseOptionsDefault, 'ipc', false);42+test('"verbose" function receives verboseObject.options before default values and normalization, "error"', testVerboseOptionsDefault, 'error', false);43+test('"verbose" function receives verboseObject.options before default values and normalization, "duration"', testVerboseOptionsDefault, 'duration', false);44+test('"verbose" function receives verboseObject.options before default values and normalization, "command", sync', testVerboseOptionsDefault, 'command', true);45+test('"verbose" function receives verboseObject.options before default values and normalization, "output", sync', testVerboseOptionsDefault, 'output', true);46+test('"verbose" function receives verboseObject.options before default values and normalization, "error", sync', testVerboseOptionsDefault, 'error', true);47+test('"verbose" function receives verboseObject.options before default values and normalization, "duration", sync', testVerboseOptionsDefault, 'duration', true);added:test/verbose/custom-output.js+128 added
1+import {inspect} from 'node:util';2+import test from 'ava';3+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';4+import {fullStdio} from '../helpers/stdio.js';5+import {6+ getNormalizedLine,7+ getNormalizedLines,8+ testTimestamp,9+ runVerboseSubprocess,10+} from '../helpers/verbose.js';11+import {nestedSubprocess} from '../helpers/nested.js';12+import {foobarObject} from '../helpers/input.js';13+14+setFixtureDirectory();15+16+const testPrintOutputCustom = async (t, fdNumber, isSync, hasOutput) => {17+ const {stderr} = await runVerboseSubprocess({18+ optionsFixture: 'custom-print.js',19+ isSync,20+ type: 'output',21+ fdNumber,22+ });23+24+ if (hasOutput) {25+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] . .`);26+ } else {27+ t.is(stderr, '');28+ }29+};30+31+test('Prints stdout, verbose custom', testPrintOutputCustom, undefined, false, true);32+test('Prints stdout, verbose custom, fd-specific stdout', testPrintOutputCustom, 'stdout', false, true);33+test('Prints stdout, verbose custom, fd-specific stderr', testPrintOutputCustom, 'stderr', false, false);34+test('Prints stdout, verbose custom, fd-specific fd3', testPrintOutputCustom, 'fd3', false, false);35+test('Prints stdout, verbose custom, fd-specific ipc', testPrintOutputCustom, 'ipc', false, false);36+test('Prints stdout, verbose custom, sync', testPrintOutputCustom, undefined, true, true);37+test('Prints stdout, verbose custom, fd-specific stdout, sync', testPrintOutputCustom, 'stdout', true, true);38+test('Prints stdout, verbose custom, fd-specific stderr, sync', testPrintOutputCustom, 'stderr', true, false);39+test('Prints stdout, verbose custom, fd-specific fd3, sync', testPrintOutputCustom, 'fd3', true, false);40+test('Prints stdout, verbose custom, fd-specific ipc, sync', testPrintOutputCustom, 'ipc', true, false);41+42+const testPrintOutputOrder = async (t, fdNumber, secondFdNumber, hasOutput) => {43+ const {stderr} = await runVerboseSubprocess({44+ optionsFixture: 'custom-print-multiple.js',45+ type: 'output',46+ fdNumber,47+ secondFdNumber,48+ ...fullStdio,49+ });50+51+ if (hasOutput) {52+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] . .`);53+ } else {54+ t.is(stderr, '');55+ }56+};57+58+test('Prints stdout, verbose custom, fd-specific stdout+stderr', testPrintOutputOrder, 'stdout', 'stderr', true);59+test('Prints stdout, verbose custom, fd-specific stderr+stdout', testPrintOutputOrder, 'stderr', 'stdout', false);60+test('Prints stdout, verbose custom, fd-specific stdout+fd3', testPrintOutputOrder, 'stdout', 'fd3', true);61+test('Prints stdout, verbose custom, fd-specific fd3+stdout', testPrintOutputOrder, 'fd3', 'stdout', false);62+test('Prints stdout, verbose custom, fd-specific stdout+ipc', testPrintOutputOrder, 'stdout', 'ipc', true);63+test('Prints stdout, verbose custom, fd-specific ipc+stdout', testPrintOutputOrder, 'ipc', 'stdout', false);64+test('Prints stdout, verbose custom, fd-specific stderr+fd3', testPrintOutputOrder, 'stderr', 'fd3', false);65+test('Prints stdout, verbose custom, fd-specific fd3+stderr', testPrintOutputOrder, 'fd3', 'stderr', false);66+test('Prints stdout, verbose custom, fd-specific stderr+ipc', testPrintOutputOrder, 'stderr', 'ipc', false);67+test('Prints stdout, verbose custom, fd-specific ipc+stderr', testPrintOutputOrder, 'ipc', 'stderr', false);68+test('Prints stdout, verbose custom, fd-specific fd3+ipc', testPrintOutputOrder, 'fd3', 'ipc', false);69+test('Prints stdout, verbose custom, fd-specific ipc+fd3', testPrintOutputOrder, 'ipc', 'fd3', false);70+71+const testPrintOutputFunction = async (t, fdNumber, secondFdNumber, hasOutput) => {72+ const {stderr} = await runVerboseSubprocess({73+ optionsFixture: 'custom-print-function.js',74+ type: 'output',75+ fdNumber,76+ secondFdNumber,77+ ...fullStdio,78+ });79+80+ if (hasOutput) {81+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] . .`);82+ } else {83+ t.is(stderr, '');84+ }85+};86+87+test('Prints stdout, verbose custom, fd-specific stdout+stderr, single function', testPrintOutputFunction, 'stdout', 'stderr', true);88+test('Prints stdout, verbose custom, fd-specific stderr+stdout, single function', testPrintOutputFunction, 'stderr', 'stdout', false);89+test('Prints stdout, verbose custom, fd-specific stdout+fd3, single function', testPrintOutputFunction, 'stdout', 'fd3', true);90+test('Prints stdout, verbose custom, fd-specific fd3+stdout, single function', testPrintOutputFunction, 'fd3', 'stdout', false);91+test('Prints stdout, verbose custom, fd-specific stdout+ipc, single function', testPrintOutputFunction, 'stdout', 'ipc', true);92+test('Prints stdout, verbose custom, fd-specific ipc+stdout, single function', testPrintOutputFunction, 'ipc', 'stdout', false);93+test('Prints stdout, verbose custom, fd-specific stderr+fd3, single function', testPrintOutputFunction, 'stderr', 'fd3', false);94+test('Prints stdout, verbose custom, fd-specific fd3+stderr, single function', testPrintOutputFunction, 'fd3', 'stderr', false);95+test('Prints stdout, verbose custom, fd-specific stderr+ipc, single function', testPrintOutputFunction, 'stderr', 'ipc', false);96+test('Prints stdout, verbose custom, fd-specific ipc+stderr, single function', testPrintOutputFunction, 'ipc', 'stderr', false);97+test('Prints stdout, verbose custom, fd-specific fd3+ipc, single function', testPrintOutputFunction, 'fd3', 'ipc', false);98+test('Prints stdout, verbose custom, fd-specific ipc+fd3, single function', testPrintOutputFunction, 'ipc', 'fd3', false);99+100+const testVerboseMessage = async (t, isSync) => {101+ const {stderr} = await runVerboseSubprocess({102+ isSync,103+ type: 'output',104+ eventProperty: 'message',105+ });106+ t.is(stderr, '. .');107+};108+109+test('"verbose" function receives verboseObject.message', testVerboseMessage, false);110+test('"verbose" function receives verboseObject.message, sync', testVerboseMessage, true);111+112+const testPrintOutputMultiline = async (t, isSync) => {113+ const {stderr} = await runVerboseSubprocess({114+ optionsFixture: 'custom-print.js',115+ isSync,116+ type: 'output',117+ output: '.\n.',118+ });119+ t.deepEqual(getNormalizedLines(stderr), [`${testTimestamp} [0] .`, `${testTimestamp} [0] .`]);120+};121+122+test('"verbose" function receives verboseObject.message line-wise', testPrintOutputMultiline, false);123+test('"verbose" function receives verboseObject.message line-wise, sync', testPrintOutputMultiline, true);124+125+test('"verbose" function receives verboseObject.message serialized', async t => {126+ const {stderr} = await nestedSubprocess('noop.js', {optionsFixture: 'custom-object-stdout.js'});127+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] ${inspect(foobarObject)}`);128+});added:test/verbose/custom-reject.js+37 added
1+import test from 'ava';2+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';3+import {runVerboseSubprocess} from '../helpers/verbose.js';4+import {earlyErrorOptions, earlyErrorOptionsSync} from '../helpers/early-error.js';5+6+setFixtureDirectory();7+8+// eslint-disable-next-line max-params9+const testVerboseReject = async (t, type, options, isSync, expectedOutput) => {10+ const {stderr} = await runVerboseSubprocess({11+ isSync,12+ type,13+ optionsFixture: 'custom-option.js',14+ optionName: 'reject',15+ ...options,16+ });17+ t.is(stderr, expectedOutput.map(String).join('\n'));18+};19+20+test('"verbose" function receives verboseObject.options.reject, "command"', testVerboseReject, 'command', {}, false, [undefined]);21+test('"verbose" function receives verboseObject.options.reject, "output"', testVerboseReject, 'output', {}, false, [undefined]);22+test('"verbose" function receives verboseObject.options.reject, "ipc"', testVerboseReject, 'ipc', {}, false, [undefined]);23+test('"verbose" function receives verboseObject.options.reject, "error"', testVerboseReject, 'error', {}, false, [undefined]);24+test('"verbose" function receives verboseObject.options.reject, "duration"', testVerboseReject, 'duration', {}, false, [undefined]);25+test('"verbose" function receives verboseObject.options.reject, "command", spawn error', testVerboseReject, 'command', earlyErrorOptions, false, [undefined]);26+test('"verbose" function receives verboseObject.options.reject, "output", spawn error', testVerboseReject, 'output', earlyErrorOptions, false, []);27+test('"verbose" function receives verboseObject.options.reject, "ipc", spawn error', testVerboseReject, 'ipc', earlyErrorOptions, false, []);28+test('"verbose" function receives verboseObject.options.reject, "error", spawn error', testVerboseReject, 'error', earlyErrorOptions, false, [undefined, undefined]);29+test('"verbose" function receives verboseObject.options.reject, "duration", spawn error', testVerboseReject, 'duration', earlyErrorOptions, false, [undefined]);30+test('"verbose" function receives verboseObject.options.reject, "command", sync', testVerboseReject, 'command', {}, true, [undefined]);31+test('"verbose" function receives verboseObject.options.reject, "output", sync', testVerboseReject, 'output', {}, true, [undefined]);32+test('"verbose" function receives verboseObject.options.reject, "error", sync', testVerboseReject, 'error', {}, true, [undefined]);33+test('"verbose" function receives verboseObject.options.reject, "duration", sync', testVerboseReject, 'duration', {}, true, [undefined]);34+test('"verbose" function receives verboseObject.options.reject, "command", spawn error, sync', testVerboseReject, 'command', earlyErrorOptionsSync, true, [undefined]);35+test('"verbose" function receives verboseObject.options.reject, "output", spawn error, sync', testVerboseReject, 'output', earlyErrorOptionsSync, true, []);36+test('"verbose" function receives verboseObject.options.reject, "error", spawn error, sync', testVerboseReject, 'error', earlyErrorOptionsSync, true, [undefined, undefined]);37+test('"verbose" function receives verboseObject.options.reject, "duration", spawn error, sync', testVerboseReject, 'duration', earlyErrorOptionsSync, true, [undefined]);added:test/verbose/custom-result.js+76 added
1+import test from 'ava';2+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';3+import {runVerboseSubprocess} from '../helpers/verbose.js';4+import {5+ earlyErrorOptions,6+ earlyErrorOptionsSync,7+ expectedEarlyError,8+ expectedEarlyErrorSync,9+} from '../helpers/early-error.js';10+11+setFixtureDirectory();12+13+const testVerboseResultEnd = async (t, type, isSync) => {14+ const {stderr: parentStderr} = await runVerboseSubprocess({15+ isSync,16+ type,17+ optionsFixture: 'custom-result.js',18+ });19+ const {failed, exitCode, stdout, stderr, ipcOutput, durationMs} = JSON.parse(parentStderr);20+ t.true(failed);21+ t.is(exitCode, 2);22+ t.is(stdout, '. .');23+ t.is(stderr, '');24+ t.is(typeof durationMs, 'number');25+ t.deepEqual(ipcOutput, isSync ? [] : ['. .']);26+};27+28+test('"verbose" function receives verboseObject.result, "error"', testVerboseResultEnd, 'error', false);29+test('"verbose" function receives verboseObject.result, "duration"', testVerboseResultEnd, 'duration', false);30+test('"verbose" function receives verboseObject.result, "error", sync', testVerboseResultEnd, 'error', true);31+test('"verbose" function receives verboseObject.result, "duration", sync', testVerboseResultEnd, 'duration', true);32+33+// eslint-disable-next-line max-params34+const testVerboseResultEndSpawn = async (t, type, options, expectedOutput, isSync) => {35+ const {stderr: parentStderr} = await runVerboseSubprocess({36+ isSync,37+ type,38+ optionsFixture: 'custom-result.js',39+ ...options,40+ });41+ const lastLine = parentStderr.split('\n').at(-1);42+ const result = JSON.parse(lastLine);43+ t.like(result, expectedOutput);44+ t.true(result.failed);45+ t.is(result.exitCode, undefined);46+ t.is(result.stdout, undefined);47+ t.is(result.stderr, undefined);48+ t.is(typeof result.durationMs, 'number');49+ t.deepEqual(result.ipcOutput, []);50+};51+52+test('"verbose" function receives verboseObject.result, "error", spawn error', testVerboseResultEndSpawn, 'error', earlyErrorOptions, expectedEarlyError, false);53+test('"verbose" function receives verboseObject.result, "duration", spawn error', testVerboseResultEndSpawn, 'duration', earlyErrorOptions, expectedEarlyError, false);54+test('"verbose" function receives verboseObject.result, "error", spawn error, sync', testVerboseResultEndSpawn, 'error', earlyErrorOptionsSync, expectedEarlyErrorSync, true);55+test('"verbose" function receives verboseObject.result, "duration", spawn error, sync', testVerboseResultEndSpawn, 'duration', earlyErrorOptionsSync, expectedEarlyErrorSync, true);56+57+const testVerboseResultStart = async (t, type, options, isSync) => {58+ const {stderr: parentStderr} = await runVerboseSubprocess({59+ isSync,60+ type,61+ optionsFixture: 'custom-result.js',62+ ...options,63+ });64+ t.is(parentStderr, '');65+};66+67+test('"verbose" function does not receive verboseObject.result, "command"', testVerboseResultStart, 'command', {}, false);68+test('"verbose" function does not receive verboseObject.result, "output"', testVerboseResultStart, 'output', {}, false);69+test('"verbose" function does not receive verboseObject.result, "ipc"', testVerboseResultStart, 'ipc', {}, false);70+test('"verbose" function does not receive verboseObject.result, "command", spawn error', testVerboseResultStart, 'command', earlyErrorOptions, false);71+test('"verbose" function does not receive verboseObject.result, "output", spawn error', testVerboseResultStart, 'output', earlyErrorOptions, false);72+test('"verbose" function does not receive verboseObject.result, "ipc", spawn error', testVerboseResultStart, 'ipc', earlyErrorOptions, false);73+test('"verbose" function does not receive verboseObject.result, "command", sync', testVerboseResultStart, 'command', {}, true);74+test('"verbose" function does not receive verboseObject.result, "output", sync', testVerboseResultStart, 'output', {}, true);75+test('"verbose" function does not receive verboseObject.result, "command", spawn error, sync', testVerboseResultStart, 'command', earlyErrorOptionsSync, true);76+test('"verbose" function does not receive verboseObject.result, "output", spawn error, sync', testVerboseResultStart, 'output', earlyErrorOptionsSync, true);added:test/verbose/custom-start.js+84 added
1+import test from 'ava';2+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';3+import {fullStdio} from '../helpers/stdio.js';4+import {5+ QUOTE,6+ getNormalizedLine,7+ testTimestamp,8+ runVerboseSubprocess,9+} from '../helpers/verbose.js';10+11+setFixtureDirectory();12+13+const testPrintCommandCustom = async (t, fdNumber, worker, isSync) => {14+ const {stderr} = await runVerboseSubprocess({15+ optionsFixture: 'custom-print.js',16+ worker,17+ isSync,18+ type: 'command',19+ fdNumber,20+ });21+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] $ noop-verbose.js ${QUOTE}. .${QUOTE}`);22+};23+24+test('Prints command, verbose custom', testPrintCommandCustom, undefined, false, false);25+test('Prints command, verbose custom, fd-specific stdout', testPrintCommandCustom, 'stdout', false, false);26+test('Prints command, verbose custom, fd-specific stderr', testPrintCommandCustom, 'stderr', false, false);27+test('Prints command, verbose custom, fd-specific fd3', testPrintCommandCustom, 'fd3', false, false);28+test('Prints command, verbose custom, fd-specific ipc', testPrintCommandCustom, 'ipc', false, false);29+test('Prints command, verbose custom, sync', testPrintCommandCustom, undefined, false, true);30+test('Prints command, verbose custom, fd-specific stdout, sync', testPrintCommandCustom, 'stdout', false, true);31+test('Prints command, verbose custom, fd-specific stderr, sync', testPrintCommandCustom, 'stderr', false, true);32+test('Prints command, verbose custom, fd-specific fd3, sync', testPrintCommandCustom, 'fd3', false, true);33+test('Prints command, verbose custom, fd-specific ipc, sync', testPrintCommandCustom, 'ipc', false, true);34+test('Prints command, verbose custom, worker', testPrintCommandCustom, undefined, true, false);35+test('Prints command, verbose custom, fd-specific stdout, worker', testPrintCommandCustom, 'stdout', true, false);36+test('Prints command, verbose custom, fd-specific stderr, worker', testPrintCommandCustom, 'stderr', true, false);37+test('Prints command, verbose custom, fd-specific fd3, worker', testPrintCommandCustom, 'fd3', true, false);38+test('Prints command, verbose custom, fd-specific ipc, worker', testPrintCommandCustom, 'ipc', true, false);39+test('Prints command, verbose custom, worker, sync', testPrintCommandCustom, undefined, true, true);40+test('Prints command, verbose custom, fd-specific stdout, worker, sync', testPrintCommandCustom, 'stdout', true, true);41+test('Prints command, verbose custom, fd-specific stderr, worker, sync', testPrintCommandCustom, 'stderr', true, true);42+test('Prints command, verbose custom, fd-specific fd3, worker, sync', testPrintCommandCustom, 'fd3', true, true);43+test('Prints command, verbose custom, fd-specific ipc, worker, sync', testPrintCommandCustom, 'ipc', true, true);44+45+const testPrintCommandOrder = async (t, fdNumber, secondFdNumber, hasOutput) => {46+ const {stderr} = await runVerboseSubprocess({47+ optionsFixture: 'custom-print-multiple.js',48+ type: 'command',49+ fdNumber,50+ secondFdNumber,51+ ...fullStdio,52+ });53+54+ if (hasOutput) {55+ t.is(getNormalizedLine(stderr), `${testTimestamp} [0] $ noop-verbose.js ${QUOTE}. .${QUOTE}`);56+ } else {57+ t.is(stderr, '');58+ }59+};60+61+test('Prints command, verbose custom, fd-specific stdout+stderr', testPrintCommandOrder, 'stdout', 'stderr', true);62+test('Prints command, verbose custom, fd-specific stderr+stdout', testPrintCommandOrder, 'stderr', 'stdout', false);63+test('Prints command, verbose custom, fd-specific stdout+fd3', testPrintCommandOrder, 'stdout', 'fd3', true);64+test('Prints command, verbose custom, fd-specific fd3+stdout', testPrintCommandOrder, 'fd3', 'stdout', false);65+test('Prints command, verbose custom, fd-specific stdout+ipc', testPrintCommandOrder, 'stdout', 'ipc', true);66+test('Prints command, verbose custom, fd-specific ipc+stdout', testPrintCommandOrder, 'ipc', 'stdout', false);67+test('Prints command, verbose custom, fd-specific stderr+fd3', testPrintCommandOrder, 'stderr', 'fd3', true);68+test('Prints command, verbose custom, fd-specific fd3+stderr', testPrintCommandOrder, 'fd3', 'stderr', false);69+test('Prints command, verbose custom, fd-specific stderr+ipc', testPrintCommandOrder, 'stderr', 'ipc', true);70+test('Prints command, verbose custom, fd-specific ipc+stderr', testPrintCommandOrder, 'ipc', 'stderr', false);71+test('Prints command, verbose custom, fd-specific fd3+ipc', testPrintCommandOrder, 'fd3', 'ipc', true);72+test('Prints command, verbose custom, fd-specific ipc+fd3', testPrintCommandOrder, 'ipc', 'fd3', false);73+74+const testVerboseMessage = async (t, isSync) => {75+ const {stderr} = await runVerboseSubprocess({76+ isSync,77+ type: 'command',78+ eventProperty: 'message',79+ });80+ t.is(stderr, `noop-verbose.js ${QUOTE}. .${QUOTE}`);81+};82+83+test('"verbose" function receives verboseObject.message', testVerboseMessage, false);84+test('"verbose" function receives verboseObject.message, sync', testVerboseMessage, true);added:test/verbose/custom-throw.js+67 added
1+import test from 'ava';2+import {setFixtureDirectory} from '../helpers/fixtures-directory.js';3+import {foobarString} from '../helpers/input.js';4+import {runVerboseSubprocess} from '../helpers/verbose.js';5+import {earlyErrorOptions, earlyErrorOptionsSync} from '../helpers/early-error.js';6+7+setFixtureDirectory();8+9+const testCommandThrowPropagate = async (t, type, options, isSync) => {10+ const {nestedResult} = await runVerboseSubprocess({11+ isSync,12+ type,13+ optionsFixture: 'custom-throw.js',14+ errorMessage: foobarString,15+ ...options,16+ });17+ t.true(nestedResult instanceof Error);18+ t.is(nestedResult.message, foobarString);19+};20+21+test('Propagate verbose exception in "verbose" function, "command"', testCommandThrowPropagate, 'command', {}, false);22+test('Propagate verbose exception in "verbose" function, "error"', testCommandThrowPropagate, 'error', {}, false);23+test('Propagate verbose exception in "verbose" function, "duration"', testCommandThrowPropagate, 'duration', {}, false);24+test('Propagate verbose exception in "verbose" function, "command", spawn error', testCommandThrowPropagate, 'command', earlyErrorOptions, false);25+test('Propagate verbose exception in "verbose" function, "error", spawn error', testCommandThrowPropagate, 'error', earlyErrorOptions, false);26+test('Propagate verbose exception in "verbose" function, "duration", spawn error', testCommandThrowPropagate, 'duration', earlyErrorOptions, false);27+test('Propagate verbose exception in "verbose" function, "command", sync', testCommandThrowPropagate, 'command', {}, true);28+test('Propagate verbose exception in "verbose" function, "error", sync', testCommandThrowPropagate, 'error', {}, true);29+test('Propagate verbose exception in "verbose" function, "duration", sync', testCommandThrowPropagate, 'duration', {}, true);30+test('Propagate verbose exception in "verbose" function, "command", spawn error, sync', testCommandThrowPropagate, 'command', earlyErrorOptionsSync, true);31+test('Propagate verbose exception in "verbose" function, "error", spawn error, sync', testCommandThrowPropagate, 'error', earlyErrorOptionsSync, true);32+test('Propagate verbose exception in "verbose" function, "duration", spawn error, sync', testCommandThrowPropagate, 'duration', earlyErrorOptionsSync, true);33+34+const testCommandThrowHandle = async (t, type, isSync) => {35+ const {nestedResult} = await runVerboseSubprocess({36+ isSync,37+ type,38+ optionsFixture: 'custom-throw.js',39+ errorMessage: foobarString,40+ });41+ t.true(nestedResult instanceof Error);42+ t.true(nestedResult.stack.startsWith(isSync ? 'ExecaSyncError' : 'ExecaError'));43+ t.true(nestedResult.cause instanceof Error);44+ t.is(nestedResult.cause.message, foobarString);45+};46+47+test('Handle exceptions in "verbose" function, "output"', testCommandThrowHandle, 'output', false);48+test('Handle exceptions in "verbose" function, "ipc"', testCommandThrowHandle, 'ipc', false);49+test('Handle exceptions in "verbose" function, "output", sync', testCommandThrowHandle, 'output', true);50+51+const testCommandThrowWrap = async (t, type, options, isSync) => {52+ const {nestedResult} = await runVerboseSubprocess({53+ isSync,54+ type,55+ optionsFixture: 'custom-throw.js',56+ errorMessage: foobarString,57+ ...options,58+ });59+ t.true(nestedResult instanceof Error);60+ t.true(nestedResult.stack.startsWith(isSync ? 'ExecaSyncError' : 'ExecaError'));61+ t.true(nestedResult.cause instanceof Error);62+ t.not(nestedResult.cause.message, foobarString);63+};64+65+test('Propagate wrapped exception in "verbose" function, "output", spawn error', testCommandThrowWrap, 'output', earlyErrorOptions, false);66+test('Propagate wrapped exception in "verbose" function, "ipc", spawn error', testCommandThrowWrap, 'ipc', earlyErrorOptions, false);67+test('Propagate wrapped exception in "verbose" function, "output", spawn error, sync', testCommandThrowWrap, 'output', earlyErrorOptionsSync, true);modified:test/verbose/error.js+1 added-1 removed
81 unmodified lines82 test('Does not print error if none, sync', testPrintNoError, true);83 84 const testPrintErrorEarly = async (t, isSync) => {85 const stderr = await runEarlyErrorSubprocess(t, isSync);86- t.is(getErrorLine(stderr), `${testTimestamp} [0] × TypeError: The "cwd" option must be a string or a file URL: true.`);86+ t.is(getErrorLine(stderr), undefined);87 };88 89 test('Prints early validation error', testPrintErrorEarly, false);90 test('Prints early validation error, sync', testPrintErrorEarly, true);76 unmodified linesmodified:test/verbose/info.js+30 added
8 unmodified lines9 getOutputLine,10 getNormalizedLines,11 testTimestamp,12 } from '../helpers/verbose.js';13+import {earlyErrorOptions, earlyErrorOptionsSync} from '../helpers/early-error.js';14 15 setFixtureDirectory();16 17 const testVerboseGeneral = async (t, execaMethod) => {42 unmodified lines60 test('Does not allow "verbose: true"', testInvalidVerbose, true, invalidTrueMessage, execa);61 test('Does not allow "verbose: true", sync', testInvalidVerbose, true, invalidTrueMessage, execaSync);62 test('Does not allow "verbose: \'unknown\'"', testInvalidVerbose, 'unknown', invalidUnknownMessage, execa);63 test('Does not allow "verbose: \'unknown\'", sync', testInvalidVerbose, 'unknown', invalidUnknownMessage, execaSync);64+65+const testValidationError = async (t, isSync) => {66+ const {stderr, nestedResult} = await nestedSubprocess('empty.js', {verbose: 'full', isSync, timeout: []});67+ t.deepEqual(getNormalizedLines(stderr), [`${testTimestamp} [0] $ empty.js`]);68+ t.true(nestedResult instanceof Error);69+};70+71+test('Prints validation errors', testValidationError, false);72+test('Prints validation errors, sync', testValidationError, true);73+74+test('Prints early spawn errors', async t => {75+ const {stderr} = await nestedSubprocess('empty.js', {...earlyErrorOptions, verbose: 'full'});76+ t.deepEqual(getNormalizedLines(stderr), [77+ `${testTimestamp} [0] $ empty.js`,78+ `${testTimestamp} [0] × Command failed with ERR_INVALID_ARG_TYPE: empty.js`,79+ `${testTimestamp} [0] × The "options.detached" property must be of type boolean. Received type string ('true')`,80+ `${testTimestamp} [0] × (done in 0ms)`,81+ ]);82+});83+84+test('Prints early spawn errors, sync', async t => {85+ const {stderr} = await nestedSubprocess('empty.js', {...earlyErrorOptionsSync, verbose: 'full', isSync: true});86+ t.deepEqual(getNormalizedLines(stderr), [87+ `${testTimestamp} [0] $ empty.js`,88+ `${testTimestamp} [0] × Command failed with ERR_OUT_OF_RANGE: empty.js`,89+ `${testTimestamp} [0] × The value of "options.maxBuffer" is out of range. It must be a positive number. Received false`,90+ `${testTimestamp} [0] × (done in 0ms)`,91+ ]);92+});modified:test-d/arguments/options.test-d.ts-11 removed
218 unmodified lines219 execaSync('unicorns', {windowsHide: false as boolean});220 expectError(await execa('unicorns', {windowsHide: 'false'}));221 expectError(execaSync('unicorns', {windowsHide: 'false'}));222 223-await execa('unicorns', {verbose: 'none'});224-execaSync('unicorns', {verbose: 'none'});225-await execa('unicorns', {verbose: 'short'});226-execaSync('unicorns', {verbose: 'short'});227-await execa('unicorns', {verbose: 'full'});228-execaSync('unicorns', {verbose: 'full'});229-expectError(await execa('unicorns', {verbose: 'full' as string}));230-expectError(execaSync('unicorns', {verbose: 'full' as string}));231-expectError(await execa('unicorns', {verbose: 'other'}));232-expectError(execaSync('unicorns', {verbose: 'other'}));233-223 await execa('unicorns', {cleanup: false});224 expectError(execaSync('unicorns', {cleanup: false}));225 await execa('unicorns', {cleanup: false as boolean});226 expectError(execaSync('unicorns', {cleanup: false as boolean}));62 unmodified linesadded:test-d/verbose.test-d.ts+97 added
1+import {2+ expectType,3+ expectNotType,4+ expectAssignable,5+ expectNotAssignable,6+ expectError,7+} from 'tsd';8+import {9+ execa,10+ execaSync,11+ type VerboseObject,12+ type SyncVerboseObject,13+ type Options,14+ type SyncOptions,15+ type Result,16+ type SyncResult,17+} from '../index.js';18+19+await execa('unicorns', {verbose: 'none'});20+execaSync('unicorns', {verbose: 'none'});21+await execa('unicorns', {verbose: 'short'});22+execaSync('unicorns', {verbose: 'short'});23+await execa('unicorns', {verbose: 'full'});24+execaSync('unicorns', {verbose: 'full'});25+expectError(await execa('unicorns', {verbose: 'full' as string}));26+expectError(execaSync('unicorns', {verbose: 'full' as string}));27+expectError(await execa('unicorns', {verbose: 'other'}));28+expectError(execaSync('unicorns', {verbose: 'other'}));29+30+const voidVerbose = () => {31+ console.log('');32+};33+34+await execa('unicorns', {verbose: voidVerbose});35+execaSync('unicorns', {verbose: voidVerbose});36+await execa('unicorns', {verbose: () => ''});37+execaSync('unicorns', {verbose: () => ''});38+await execa('unicorns', {verbose: voidVerbose as () => never});39+execaSync('unicorns', {verbose: voidVerbose as () => never});40+expectError(await execa('unicorns', {verbose: () => true}));41+expectError(execaSync('unicorns', {verbose: () => true}));42+expectError(await execa('unicorns', {verbose: () => '' as unknown}));43+expectError(execaSync('unicorns', {verbose: () => '' as unknown}));44+45+await execa('unicorns', {verbose: (verboseLine: string) => ''});46+execaSync('unicorns', {verbose: (verboseLine: string) => ''});47+await execa('unicorns', {verbose: (verboseLine: unknown) => ''});48+execaSync('unicorns', {verbose: (verboseLine: unknown) => ''});49+expectError(await execa('unicorns', {verbose: (verboseLine: boolean) => ''}));50+expectError(execaSync('unicorns', {verbose: (verboseLine: boolean) => ''}));51+expectError(await execa('unicorns', {verbose: (verboseLine: never) => ''}));52+expectError(execaSync('unicorns', {verbose: (verboseLine: never) => ''}));53+54+await execa('unicorns', {verbose: (verboseLine: string, verboseObject: object) => ''});55+execaSync('unicorns', {verbose: (verboseLine: string, verboseObject: object) => ''});56+await execa('unicorns', {verbose: (verboseLine: string, verboseObject: VerboseObject) => ''});57+execaSync('unicorns', {verbose: (verboseLine: string, verboseObject: VerboseObject) => ''});58+await execa('unicorns', {verbose: (verboseLine: string, verboseObject: unknown) => ''});59+execaSync('unicorns', {verbose: (verboseLine: string, verboseObject: unknown) => ''});60+expectError(await execa('unicorns', {verbose: (verboseLine: string, verboseObject: string) => ''}));61+expectError(execaSync('unicorns', {verbose: (verboseLine: string, verboseObject: string) => ''}));62+expectError(await execa('unicorns', {verbose: (verboseLine: string, verboseObject: never) => ''}));63+expectError(execaSync('unicorns', {verbose: (verboseLine: string, verboseObject: never) => ''}));64+65+expectError(await execa('unicorns', {verbose: (verboseLine: string, verboseObject: object, other: string) => ''}));66+expectError(execaSync('unicorns', {verbose: (verboseLine: string, verboseObject: object, other: string) => ''}));67+68+await execa('unicorns', {69+ verbose(verboseLine: string, verboseObject: VerboseObject) {70+ expectNotType<string>(verboseObject.type);71+ expectAssignable<string>(verboseObject.type);72+ expectNotAssignable<boolean>(verboseObject.type);73+ expectType<string>(verboseObject.message);74+ expectType<string>(verboseObject.escapedCommand);75+ expectType<string>(verboseObject.commandId);76+ expectType<Date>(verboseObject.timestamp);77+ expectType<Result | undefined>(verboseObject.result);78+ expectType<boolean>(verboseObject.piped);79+ expectType<Options>(verboseObject.options);80+ expectError(verboseObject.other);81+ },82+});83+execaSync('unicorns', {84+ verbose(verboseLine: string, verboseObject: SyncVerboseObject) {85+ expectNotType<string>(verboseObject.type);86+ expectAssignable<string>(verboseObject.type);87+ expectNotAssignable<boolean>(verboseObject.type);88+ expectType<string>(verboseObject.message);89+ expectType<string>(verboseObject.escapedCommand);90+ expectType<string>(verboseObject.commandId);91+ expectType<Date>(verboseObject.timestamp);92+ expectType<SyncResult | undefined>(verboseObject.result);93+ expectType<boolean>(verboseObject.piped);94+ expectType<SyncOptions>(verboseObject.options);95+ expectError(verboseObject.other);96+ },97+});modified:types/arguments/options.d.ts+5 added-2 removed
2 unmodified lines3 import type {Readable} from 'node:stream';4 import type {Unless} from '../utils.js';5 import type {Message} from '../ipc.js';6 import type {StdinOptionCommon, StdoutStderrOptionCommon, StdioOptionsProperty} from '../stdio/type.js';7+import type {VerboseOption} from '../verbose.js';8 import type {FdGenericOption} from './specific.js';9 import type {EncodingOption} from './encoding-option.js';10 11 export type CommonOptions<IsSync extends boolean = boolean> = {214 unmodified lines226 227 /**228 If `verbose` is `'short'`, prints the command on [`stderr`](https://en.wikipedia.org/wiki/Standard_streams#Standard_error_(stderr)): its file, arguments, duration and (if it failed) error message.229 229- If `verbose` is `'full'`, the command's [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)), `stderr` and IPC messages are also printed.230+ If `verbose` is `'full'` or a function, the command's [`stdout`](https://en.wikipedia.org/wiki/Standard_streams#Standard_output_(stdout)), `stderr` and IPC messages are also printed.231 232+ A function can be passed to customize logging.233+234 By default, this applies to both `stdout` and `stderr`, but different values can also be passed.235 236 @default 'none'237 */235- readonly verbose?: FdGenericOption<'none' | 'short' | 'full'>;238+ readonly verbose?: VerboseOption;239 240 /**241 Setting this to `false` resolves the result's promise with the error instead of rejecting it.242 159 unmodified linesmodified:types/return/result.d.ts+3 added-3 removed
177 unmodified lines178 readonly name?: Error['name'];179 stack?: Error['stack'];180 }181 182-type SuccessResult<183- IsSync extends boolean,184- OptionsType extends CommonOptions,182+export type SuccessResult<183+ IsSync extends boolean = boolean,184+ OptionsType extends CommonOptions = CommonOptions,185 > = InstanceType<typeof CommonResult<IsSync, OptionsType>> & OmitErrorIfReject<OptionsType['reject']>;186 187 type OmitErrorIfReject<RejectOption extends CommonOptions['reject']> = {188 [ErrorProperty in ErrorProperties]: RejectOption extends false ? unknown : never15 unmodified linesadded:types/verbose.d.ts+98 added
1+import type {FdGenericOption} from './arguments/specific.js';2+import type {Options, SyncOptions} from './arguments/options.js';3+import type {Result, SyncResult} from './return/result.js';4+5+type VerboseOption = FdGenericOption<6+| 'none'7+| 'short'8+| 'full'9+| VerboseFunction10+>;11+12+type VerboseFunction = (verboseLine: string, verboseObject: MinimalVerboseObject) => string | void;13+14+type GenericVerboseObject = {15+ /**16+ Event type. This can be:17+ - `'command'`: subprocess start18+ - `'output'`: `stdout`/`stderr` output19+ - `'ipc'`: IPC output20+ - `'error'`: subprocess failure21+ - `'duration'`: subprocess success or failure22+ */23+ type: 'command' | 'output' | 'ipc' | 'error' | 'duration';24+25+ /**26+ Depending on `verboseObject.type`, this is:27+ - `'command'`: the `result.escapedCommand`28+ - `'output'`: one line from `result.stdout` or `result.stderr`29+ - `'ipc'`: one IPC message from `result.ipcOutput`30+ - `'error'`: the `error.shortMessage`31+ - `'duration'`: the `result.durationMs`32+ */33+ message: string;34+35+ /**36+ The file and arguments that were run. This is the same as `result.escapedCommand`.37+ */38+ escapedCommand: string;39+40+ /**41+ Serial number identifying the subprocess within the current process. It is incremented from `'0'`.42+43+ This is helpful when multiple subprocesses are running at the same time.44+45+ This is similar to a [PID](https://en.wikipedia.org/wiki/Process_identifier) except it has no maximum limit, which means it never repeats. Also, it is usually shorter.46+ */47+ commandId: string;48+49+ /**50+ Event date/time.51+ */52+ timestamp: Date;53+54+ /**55+ Whether another subprocess is piped into this subprocess. This is `false` when `result.pipedFrom` is empty.56+ */57+ piped: boolean;58+};59+60+type MinimalVerboseObject = GenericVerboseObject & {61+ // We cannot use the `CommonOptions` type because it would make this type recursive62+ options: object;63+ result?: never;64+};65+66+/**67+Subprocess event object, for logging purpose, using the `verbose` option and `execa()`.68+*/69+export type VerboseObject = GenericVerboseObject & {70+ /**71+ The options passed to the subprocess.72+ */73+ options: Options;74+75+ /**76+ Subprocess result.77+78+ This is `undefined` if `verboseObject.type` is `'command'`, `'output'` or `'ipc'`.79+ */80+ result?: Result;81+};82+83+/**84+Subprocess event object, for logging purpose, using the `verbose` option and `execaSync()`.85+*/86+export type SyncVerboseObject = GenericVerboseObject & {87+ /**88+ The options passed to the subprocess.89+ */90+ options: SyncOptions;91+92+ /**93+ Subprocess result.94+95+ This is `undefined` if `verboseObject.type` is `'command'`, `'output'` or `'ipc'`.96+ */97+ result?: SyncResult;98+};modified:index.d.ts+1 added
22 unmodified lines23 getEachMessage,24 getCancelSignal,25 type Message,26 } from './types/ipc.js';27+export type {VerboseObject, SyncVerboseObject} from './types/verbose.js';