Print process completion with verbose option (#887)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 5abc429 · Browse files · 16 files·+211 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+211 added−26 removed
- tests:+121 added−1 removed
- other:+90 added−25 removed
Provenance
- Commit
7264bcf- Tree
da1ddfa- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
5abc429
16 files changed+211 added−26 removed
modified:docs/scripts.md+1 added
419 unmodified lines420 421 ```422 [19:49:00.360] [0] $ echo example423 example424+[19:49:00.383] [0] √ (done in 23ms)425 ```426 427 ### Piping stdout to another command428 290 unmodified linesmodified:lib/return/early-error.js+3 added-3 removed
4 unmodified lines56789910111213141516161718192010 unmodified lines3132333435354 unmodified linesimport {handleResult} from './output.js';
// When the child process fails to spawn.// We ensure the returned error is always both a promise and a child process.export const handleEarlyError = ({error, command, escapedCommand, stdioStreamsGroups, options}) => {export const handleEarlyError = ({error, command, escapedCommand, stdioStreamsGroups, options, verboseInfo}) => { cleanupStdioStreams(stdioStreamsGroups);
const spawned = new ChildProcess(); createDummyStreams(spawned);
const earlyError = makeEarlyError({error, command, escapedCommand, stdioStreamsGroups, options}); const promise = handleDummyPromise(earlyError, options); const promise = handleDummyPromise(earlyError, verboseInfo, options); return {spawned, promise};};
const createDummyStreams = spawned => {10 unmodified lines stream.end(); return stream;};
const handleDummyPromise = async (error, options) => handleResult(error, options);const handleDummyPromise = async (error, verboseInfo, options) => handleResult(error, verboseInfo, options);modified:lib/return/output.js+4 added-1 removed
123456789 unmodified lines1819202121222324252627282 unmodified linesimport {Buffer} from 'node:buffer';import stripFinalNewline from 'strip-final-newline';import {bufferToUint8Array} from '../utils.js';import {logFinalResult} from '../verbose/complete.js';
export const handleOutput = (options, value) => { if (value === undefined || value === null) { return;9 unmodified lines
return options.stripFinalNewline ? stripFinalNewline(value) : value;};
export const handleResult = (result, {reject}) => {export const handleResult = (result, verboseInfo, {reject}) => { logFinalResult(result, reject, verboseInfo);
if (result.failed && reject) { throw result; }
2 unmodified linesadded:lib/verbose/complete.js+37 added
12345678910111213141516171819202122232425262728293031323334353637import prettyMs from 'pretty-ms';import {escapeLines} from '../arguments/escape.js';import {verboseLog} from './log.js';import {getCommandDuration} from './info.js';
// When `verbose` is `short|full`, print each command's completion, duration and errorexport const logFinalResult = ({shortMessage, failed}, reject, verboseInfo) => { logResult(shortMessage, failed, reject, verboseInfo);};
// Same but for early validation errorsexport const logEarlyResult = (error, verboseInfo) => { logResult(escapeLines(String(error)), true, true, verboseInfo);};
const logResult = (message, failed, reject, {verbose, verboseId, startTime}) => { if (verbose === 'none') { return; }
const icon = getIcon(failed, reject); logDuration(startTime, verboseId, icon);};
const logDuration = (startTime, verboseId, icon) => { const durationMs = getCommandDuration(startTime); const durationMessage = `(done in ${prettyMs(durationMs)})`; verboseLog(durationMessage, verboseId, icon);};
const getIcon = (failed, reject) => { if (!failed) { return 'success'; }
return reject ? 'error' : 'warning';};modified:lib/verbose/info.js+5 added-1 removed
12345678910911121314151617181920212 unmodified linesimport {hrtime} from 'node:process';import {debuglog} from 'node:util';
export const getVerboseInfo = ({verbose = verboseDefault}) => { if (verbose === 'none') { return {verbose}; }
const verboseId = VERBOSE_ID++; const startTime = hrtime.bigint(); return {verbose, verboseId}; return {verbose, verboseId, startTime};};
const verboseDefault = debuglog('execa').enabled ? 'full' : 'none';
export const getCommandDuration = startTime => Number(hrtime.bigint() - startTime) / 1e6;
// Prepending the `pid` is useful when multiple commands print their output at the same time.// However, we cannot use the real PID since this is not available with `child_process.spawnSync()`.// Also, we cannot use the real PID if we want to print it before `child_process.spawn()` is run.// As a pro, it is shorter than a normal PID and never re-uses the same id.2 unmodified linesmodified:lib/verbose/log.js+3 added
31 unmodified lines323334353637383931 unmodified linesconst ICONS = { command: '$', pipedCommand: '|', output: ' ', error: '×', warning: '‼', success: '√',};modified:lib/async.js+18 added-11 removed
7 unmodified lines8 import {spawnedKill} from './exit/kill.js';9 import {cleanupOnExit} from './exit/cleanup.js';10 import {pipeToProcess} from './pipe/setup.js';11 import {PROCESS_OPTIONS} from './pipe/validate.js';12+import {logEarlyResult} from './verbose/complete.js';13 import {makeAllStream} from './stream/all.js';14 import {getSpawnedResult} from './stream/resolve.js';15 import {mergePromise} from './promise.js';16 17 export const execa = (rawFile, rawArgs, rawOptions) => {17- const {file, args, command, escapedCommand, options, stdioStreamsGroups, stdioState} = handleAsyncArguments(rawFile, rawArgs, rawOptions);18- const {spawned, promise} = spawnProcessAsync({file, args, options, command, escapedCommand, stdioStreamsGroups, stdioState});18+ const {file, args, command, escapedCommand, verboseInfo, options, stdioStreamsGroups, stdioState} = handleAsyncArguments(rawFile, rawArgs, rawOptions);19+ const {spawned, promise} = spawnProcessAsync({file, args, options, verboseInfo, command, escapedCommand, stdioStreamsGroups, stdioState});20 spawned.pipe = pipeToProcess.bind(undefined, {source: spawned, sourcePromise: promise, stdioStreamsGroups, destinationOptions: {}});21 mergePromise(spawned, promise);22 PROCESS_OPTIONS.set(spawned, options);23 return spawned;1 unmodified line25 26 const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {27 [rawFile, rawArgs, rawOptions] = normalizeArguments(rawFile, rawArgs, rawOptions);28 const {command, escapedCommand, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);29+30+ try {28- const {file, args, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);29- const options = handleAsyncOptions(normalizedOptions);30- const {stdioStreamsGroups, stdioState} = handleInputAsync(options, verboseInfo);31- return {file, args, command, escapedCommand, options, stdioStreamsGroups, stdioState};31+ const {file, args, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);32+ const options = handleAsyncOptions(normalizedOptions);33+ const {stdioStreamsGroups, stdioState} = handleInputAsync(options, verboseInfo);34+ return {file, args, command, escapedCommand, verboseInfo, options, stdioStreamsGroups, stdioState};35+ } catch (error) {36+ logEarlyResult(error, verboseInfo);37+ throw error;38+ }39 };40 41 // Prevent passing the `timeout` option directly to `child_process.spawn()`42 const handleAsyncOptions = ({timeout, signal, cancelSignal, ...options}) => {3 unmodified lines46 47 return {...options, timeoutDuration: timeout, signal: cancelSignal};48 };49 43-const spawnProcessAsync = ({file, args, options, command, escapedCommand, stdioStreamsGroups, stdioState}) => {50+const spawnProcessAsync = ({file, args, options, verboseInfo, command, escapedCommand, stdioStreamsGroups, stdioState}) => {51 let spawned;52 try {53 spawned = spawn(file, args, options);54 } catch (error) {48- return handleEarlyError({error, command, escapedCommand, stdioStreamsGroups, options});55+ return handleEarlyError({error, command, escapedCommand, stdioStreamsGroups, options, verboseInfo});56 }57 58 const controller = new AbortController();59 setMaxListeners(Number.POSITIVE_INFINITY, controller.signal);4 unmodified lines64 65 spawned.kill = spawnedKill.bind(undefined, {kill: spawned.kill.bind(spawned), spawned, options, controller});66 spawned.all = makeAllStream(spawned, options);67 61- const promise = handlePromise({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});68+ const promise = handlePromise({spawned, options, verboseInfo, stdioStreamsGroups, originalStreams, command, escapedCommand, controller});69 return {spawned, promise};70 };71 65-const handlePromise = async ({spawned, options, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {72+const handlePromise = async ({spawned, options, verboseInfo, stdioStreamsGroups, originalStreams, command, escapedCommand, controller}) => {73 const context = {timedOut: false};74 75 const [76 errorInfo,5 unmodified lines82 83 const stdio = stdioResults.map(stdioResult => handleOutput(options, stdioResult));84 const all = handleOutput(options, allResult);85 const result = getAsyncResult({errorInfo, exitCode, signal, stdio, all, context, options, command, escapedCommand});79- return handleResult(result, options);86+ return handleResult(result, verboseInfo, options);87 };88 89 const getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, context, options, command, escapedCommand}) => 'error' in errorInfo90 ? makeError({12 unmodified linesmodified:lib/sync.js+14 added-7 removed
1 unmodified line2 import {normalizeArguments, handleCommand, handleArguments} from './arguments/options.js';3 import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';4 import {handleOutput, handleResult} from './return/output.js';5 import {handleInputSync, pipeOutputSync} from './stdio/sync.js';6+import {logEarlyResult} from './verbose/complete.js';7 import {isFailedExit} from './exit/code.js';8 9 export const execaSync = (rawFile, rawArgs, rawOptions) => {9- const {file, args, command, escapedCommand, options, stdioStreamsGroups} = handleSyncArguments(rawFile, rawArgs, rawOptions);10+ const {file, args, command, escapedCommand, verboseInfo, options, stdioStreamsGroups} = handleSyncArguments(rawFile, rawArgs, rawOptions);11 const result = spawnProcessSync({file, args, options, command, escapedCommand, stdioStreamsGroups});11- return handleResult(result, options);12+ return handleResult(result, verboseInfo, options);13 };14 15 const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {16 [rawFile, rawArgs, rawOptions] = normalizeArguments(rawFile, rawArgs, rawOptions);17 const {command, escapedCommand, verboseInfo} = handleCommand(rawFile, rawArgs, rawOptions);18+19+ try {17- const syncOptions = normalizeSyncOptions(rawOptions);18- const {file, args, options} = handleArguments(rawFile, rawArgs, syncOptions);19- validateSyncOptions(options);20- const stdioStreamsGroups = handleInputSync(options, verboseInfo);21- return {file, args, command, escapedCommand, options, stdioStreamsGroups};20+ const syncOptions = normalizeSyncOptions(rawOptions);21+ const {file, args, options} = handleArguments(rawFile, rawArgs, syncOptions);22+ validateSyncOptions(options);23+ const stdioStreamsGroups = handleInputSync(options, verboseInfo);24+ return {file, args, command, escapedCommand, verboseInfo, options, stdioStreamsGroups};25+ } catch (error) {26+ logEarlyResult(error, verboseInfo);27+ throw error;28+ }29 };30 31 const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;32 34 unmodified linesadded:test/fixtures/nested-fail.js+8 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {execa} from '../../index.js';4+5+const [options, file, ...args] = process.argv.slice(2);6+const childProcess = execa(file, args, JSON.parse(options));7+childProcess.kill(new Error(args[0]));8+await childProcess;added:test/fixtures/noop-continuous.js+9 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {setTimeout} from 'node:timers/promises';4+5+for (const character of process.argv[2]) {6+ console.log(character);7+ // eslint-disable-next-line no-await-in-loop8+ await setTimeout(100);9+}modified:test/helpers/verbose.js+10 added-1 removed
19 unmodified lines20 t.true(stderr.includes('exit code 2'));21 return stderr;22 };23 24+export const runWarningProcess = async (t, execaMethod) => {25+ const {stderr} = await execaMethod('noop-fail.js', ['1', foobarString], {verbose: 'short', reject: false});26+ return stderr;27+};28+29 export const runEarlyErrorProcess = async (t, execaMethod) => {30 const {stderr} = await t.throwsAsync(execaMethod('noop.js', [foobarString], {verbose: 'short', cwd: true}));31 t.true(stderr.includes('The "cwd" option must'));32 return stderr;4 unmodified lines37 const isCommandLine = line => line.includes(' $ ') || line.includes(' | ');38 export const getOutputLine = stderr => getOutputLines(stderr)[0];39 export const getOutputLines = stderr => getNormalizedLines(stderr).filter(line => isOutputLine(line));40 const isOutputLine = line => line.includes('] ');41+export const getCompletionLine = stderr => getCompletionLines(stderr)[0];42+export const getCompletionLines = stderr => getNormalizedLines(stderr).filter(line => isCompletionLine(line));43+const isCompletionLine = line => line.includes('(done in');44 export const getNormalizedLines = stderr => splitLines(normalizeStderr(stderr));45 const splitLines = stderr => stderr.split('\n');46 39-const normalizeStderr = stderr => normalizeTimestamp(stripVTControlCharacters(stderr));47+const normalizeStderr = stderr => normalizeDuration(normalizeTimestamp(stripVTControlCharacters(stderr)));48 export const testTimestamp = '[00:00:00.000]';49 const normalizeTimestamp = stderr => stderr.replaceAll(/^\[\d{2}:\d{2}:\d{2}.\d{3}]/gm, testTimestamp);50+const normalizeDuration = stderr => stderr.replaceAll(/\(done in [^)]+\)/g, '(done in 0ms)');51 52 export const getVerboseOption = (isVerbose, verbose = 'short') => ({verbose: isVerbose ? verbose : 'none'});added:test/verbose/complete.js+92 added
1+import {stripVTControlCharacters} from 'node:util';2+import test from 'ava';3+import {execa} from '../../index.js';4+import {setFixtureDir} from '../helpers/fixtures-dir.js';5+import {foobarString} from '../helpers/input.js';6+import {7+ nestedExecaAsync,8+ nestedExecaSync,9+ runErrorProcess,10+ runWarningProcess,11+ runEarlyErrorProcess,12+ getCompletionLine,13+ getCompletionLines,14+ testTimestamp,15+ getVerboseOption,16+} from '../helpers/verbose.js';17+18+setFixtureDir();19+20+const testPrintCompletion = async (t, verbose, execaMethod) => {21+ const {stderr} = await execaMethod('noop.js', [foobarString], {verbose});22+ t.is(getCompletionLine(stderr), `${testTimestamp} [0] √ (done in 0ms)`);23+};24+25+test('Prints completion, verbose "short"', testPrintCompletion, 'short', nestedExecaAsync);26+test('Prints completion, verbose "full"', testPrintCompletion, 'full', nestedExecaAsync);27+test('Prints completion, verbose "short", sync', testPrintCompletion, 'short', nestedExecaSync);28+test('Prints completion, verbose "full", sync', testPrintCompletion, 'full', nestedExecaSync);29+30+const testNoPrintCompletion = async (t, execaMethod) => {31+ const {stderr} = await execaMethod('noop.js', [foobarString], {verbose: 'none'});32+ t.is(stderr, '');33+};34+35+test('Does not print completion, verbose "none"', testNoPrintCompletion, nestedExecaAsync);36+test('Does not print completion, verbose "none", sync', testNoPrintCompletion, nestedExecaSync);37+38+const testPrintCompletionError = async (t, execaMethod) => {39+ const stderr = await runErrorProcess(t, 'short', execaMethod);40+ t.is(getCompletionLine(stderr), `${testTimestamp} [0] × (done in 0ms)`);41+};42+43+test('Prints completion after errors', testPrintCompletionError, nestedExecaAsync);44+test('Prints completion after errors, sync', testPrintCompletionError, nestedExecaSync);45+46+const testPrintCompletionWarning = async (t, execaMethod) => {47+ const stderr = await runWarningProcess(t, execaMethod);48+ t.is(getCompletionLine(stderr), `${testTimestamp} [0] ‼ (done in 0ms)`);49+};50+51+test('Prints completion after errors, "reject" false', testPrintCompletionWarning, nestedExecaAsync);52+test('Prints completion after errors, "reject" false, sync', testPrintCompletionWarning, nestedExecaSync);53+54+const testPrintCompletionEarly = async (t, execaMethod) => {55+ const stderr = await runEarlyErrorProcess(t, execaMethod);56+ t.is(getCompletionLine(stderr), `${testTimestamp} [0] × (done in 0ms)`);57+};58+59+test('Prints completion after early validation errors', testPrintCompletionEarly, nestedExecaAsync);60+test('Prints completion after early validation errors, sync', testPrintCompletionEarly, nestedExecaSync);61+62+test.serial('Prints duration', async t => {63+ const {stderr} = await nestedExecaAsync('delay.js', ['1000'], {verbose: 'short'});64+ t.regex(stripVTControlCharacters(stderr).split('\n').at(-1), /\(done in [\d.]+s\)/);65+});66+67+const testPipeDuration = async (t, fixtureName, sourceVerbose, destinationVerbose) => {68+ const {stderr} = await execa(`nested-pipe-${fixtureName}.js`, [69+ JSON.stringify(getVerboseOption(sourceVerbose)),70+ 'noop.js',71+ foobarString,72+ JSON.stringify(getVerboseOption(destinationVerbose)),73+ 'stdin.js',74+ ]);75+76+ const lines = getCompletionLines(stderr);77+ t.is(lines.includes(`${testTimestamp} [0] √ (done in 0ms)`), sourceVerbose || destinationVerbose);78+ t.is(lines.includes(`${testTimestamp} [1] √ (done in 0ms)`), sourceVerbose && destinationVerbose);79+};80+81+test('Prints both durations piped with .pipe("file")', testPipeDuration, 'file', true, true);82+test('Prints both durations piped with .pipe`command`', testPipeDuration, 'script', true, true);83+test('Prints both durations piped with .pipe(childProcess)', testPipeDuration, 'process', true, true);84+test('Prints first duration piped with .pipe("file")', testPipeDuration, 'file', true, false);85+test('Prints first duration piped with .pipe`command`', testPipeDuration, 'script', true, false);86+test('Prints first duration piped with .pipe(childProcess)', testPipeDuration, 'process', true, false);87+test('Prints second duration piped with .pipe("file")', testPipeDuration, 'file', false, true);88+test('Prints second duration piped with .pipe`command`', testPipeDuration, 'script', false, true);89+test('Prints second duration piped with .pipe(childProcess)', testPipeDuration, 'process', false, true);90+test('Prints neither durations piped with .pipe("file")', testPipeDuration, 'file', false, false);91+test('Prints neither durations piped with .pipe`command`', testPipeDuration, 'script', false, false);92+test('Prints neither durations piped with .pipe(childProcess)', testPipeDuration, 'process', false, false);modified:test/verbose/info.js+2 added
17 unmodified lines18 const {all} = await execa('verbose-script.js', {env: {NODE_DEBUG: 'execa'}, all: true});19 t.deepEqual(getNormalizedLines(all), [20 `${testTimestamp} [0] $ node -e ${QUOTE}console.error(1)${QUOTE}`,21 '1',22+ `${testTimestamp} [0] √ (done in 0ms)`,23 `${testTimestamp} [1] $ node -e ${QUOTE}process.exit(2)${QUOTE}`,24+ `${testTimestamp} [1] ‼ (done in 0ms)`,25 ]);26 });27 28 test('NODE_DEBUG=execa changes verbose default value to "full"', async t => {13 unmodified linesmodified:index.d.ts+1 added-1 removed
541 unmodified lines542 */543 readonly windowsHide?: boolean;544 545 /**546- If `verbose` is `'short'` or `'full'`, prints each command on `stderr` before executing it.546+ If `verbose` is `'short'` or `'full'`, prints each command on `stderr` before executing it. When the command completes, prints its duration.547 548 If `verbose` is `'full'`, the command's `stdout` and `stderr` are printed too, unless either:549 - the `stdout`/`stderr` option is `ignore` or `inherit`.550 - the `stdout`/`stderr` is redirected to [a stream](https://nodejs.org/api/stream.html#readablepipedestination-options), a file, a file descriptor, or another child process.835 unmodified linesmodified:package.json+1 added
50 unmodified lines51 "human-signals": "^6.0.0",52 "is-plain-obj": "^4.1.0",53 "is-stream": "^4.0.1",54 "npm-run-path": "^5.2.0",55+ "pretty-ms": "^9.0.0",56 "signal-exit": "^4.1.0",57 "strip-final-newline": "^4.0.0"58 },59 "devDependencies": {36 unmodified linesmodified:readme.md+3 added-1 removed
142 unmodified lines143 144 > NODE_DEBUG=execa node file.js145 [19:49:00.360] [0] $ echo unicorns146 unicorns147+[19:49:00.383] [0] √ (done in 23ms)148 [19:49:00.383] [1] $ echo rainbows149 rainbows150+[19:49:00.404] [1] √ (done in 21ms)151 ```152 153 ### Input/output154 513 unmodified lines668 669 Type: `'none' | 'short' | 'full'`\670 Default: `'none'`671 670-If `verbose` is `'short'` or `'full'`, [prints each command](#verbose-mode) on `stderr` before executing it.672+If `verbose` is `'short'` or `'full'`, [prints each command](#verbose-mode) on `stderr` before executing it. When the command completes, prints its duration.673 674 If `verbose` is `'full'`, the command's `stdout` and `stderr` are printed too, unless either:675 - the [`stdout`](#stdout-1)/[`stderr`](#stderr-1) option is `ignore` or `inherit`.676 - the `stdout`/`stderr` is redirected to [a stream](https://nodejs.org/api/stream.html#readablepipedestination-options), [a file](#stdout-1), a file descriptor, or [another child process](#pipefile-arguments-options).373 unmodified lines