Skip to content
Myr

Improve `verbose` option (#883)

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

authored by ehmicky · committed by GitHub · parent de32969 · Browse files · 21 files+292 added−86 removed
This commit

State

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

Diff stats

21 files+292 added−86 removed

  • tests:+219 added−38 removed
  • other:+73 added−48 removed

21 files+292 added−86 removed

modified:docs/scripts.md+6 added
413 unmodified lines
414```415NODE_DEBUG=execa node file.js416```417418Which prints:419420```421[19:49:00.360] $ echo example422```423424### Piping stdout to another command425426```sh427# Bash
288 unmodified lines
modified:lib/arguments/options.js+7 added-7 removed
deleted:lib/arguments/verbose.js-22 removed
modified:lib/pipe/validate.js+4 added-2 removed
39 unmodified lines
40};4142const getDestination = (destinationOptions, firstArgument, ...args) => {43 if (Array.isArray(firstArgument)) {44 const destination = create$({...destinationOptions, stdin: 'pipe'})(firstArgument, ...args);44 const destination = create$({...destinationOptions, ...PIPED_PROCESS_OPTIONS})(firstArgument, ...args);45 return {destination, pipeOptions: destinationOptions};46 }4748 if (typeof firstArgument === 'string' || firstArgument instanceof URL) {
1 unmodified line
50 throw new TypeError('Please use .pipe("file", ..., options) or .pipe(execa("file", ..., options)) instead of .pipe(options)(execa("file", ...)).');51 }5253 const [rawFile, rawArgs, rawOptions] = normalizeArguments(firstArgument, ...args);54 const destination = execa(rawFile, rawArgs, {...rawOptions, stdin: 'pipe'});54 const destination = execa(rawFile, rawArgs, {...rawOptions, ...PIPED_PROCESS_OPTIONS});55 return {destination, pipeOptions: rawOptions};56 }5758 if (PROCESS_OPTIONS.has(firstArgument)) {
6 unmodified lines
6566 throw new TypeError(`The first argument must be a template string, an options object, or an Execa child process: ${firstArgument}`);67};6869const PIPED_PROCESS_OPTIONS = {stdin: 'pipe', piped: true};7071export const PROCESS_OPTIONS = new WeakMap();7273const getSourceStream = (source, stdioStreamsGroups, from, sourceOptions) => {74 try {
77 unmodified lines
added:lib/verbose/log.js+20 added
added:lib/verbose/start.js+14 added
modified:lib/async.js+8 added-7 removed
1import {setMaxListeners} from 'node:events';2import {spawn} from 'node:child_process';3import {normalizeArguments, handleArguments} from './arguments/options.js';3import {normalizeArguments, handleCommand, handleArguments} from './arguments/options.js';4import {makeError, makeSuccessResult} from './return/error.js';5import {handleOutput, handleResult} from './return/output.js';6import {handleEarlyError} from './return/early-error.js';7import {handleInputAsync, pipeOutputAsync} from './stdio/async.js';
5 unmodified lines
13import {getSpawnedResult} from './stream/resolve.js';14import {mergePromise} from './promise.js';1516export const execa = (rawFile, rawArgs, rawOptions) => {17 const {file, args, command, escapedCommand, options} = handleAsyncArguments(rawFile, rawArgs, rawOptions);18 const stdioStreamsGroups = handleInputAsync(options);19 const {spawned, promise} = runExeca({file, args, options, command, escapedCommand, stdioStreamsGroups});17 const {file, args, command, escapedCommand, options, stdioStreamsGroups} = handleAsyncArguments(rawFile, rawArgs, rawOptions);18 const {spawned, promise} = spawnProcessAsync({file, args, options, command, escapedCommand, stdioStreamsGroups});19 spawned.pipe = pipeToProcess.bind(undefined, {source: spawned, sourcePromise: promise, stdioStreamsGroups, destinationOptions: {}});20 mergePromise(spawned, promise);21 PROCESS_OPTIONS.set(spawned, options);22 return spawned;23};2425const handleAsyncArguments = (rawFile, rawArgs, rawOptions) => {26 [rawFile, rawArgs, rawOptions] = normalizeArguments(rawFile, rawArgs, rawOptions);28 const {file, args, command, escapedCommand, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);27 const {command, escapedCommand} = handleCommand(rawFile, rawArgs, rawOptions);28 const {file, args, options: normalizedOptions} = handleArguments(rawFile, rawArgs, rawOptions);29 const options = handleAsyncOptions(normalizedOptions);30 const stdioStreamsGroups = handleInputAsync(options);30 return {file, args, command, escapedCommand, options};31 return {file, args, command, escapedCommand, options, stdioStreamsGroups};32};3334// Prevent passing the `timeout` option directly to `child_process.spawn()`35const handleAsyncOptions = ({timeout, ...options}) => ({...options, timeoutDuration: timeout});3636const runExeca = ({file, args, options, command, escapedCommand, stdioStreamsGroups}) => {37const spawnProcessAsync = ({file, args, options, command, escapedCommand, stdioStreamsGroups}) => {38 let spawned;39 try {40 spawned = spawn(file, args, options);41 } catch (error) {
48 unmodified lines
modified:lib/sync.js+8 added-7 removed
1import {spawnSync} from 'node:child_process';2import {normalizeArguments, handleArguments} from './arguments/options.js';2import {normalizeArguments, handleCommand, handleArguments} from './arguments/options.js';3import {makeError, makeEarlyError, makeSuccessResult} from './return/error.js';4import {handleOutput, handleResult} from './return/output.js';5import {handleInputSync, pipeOutputSync} from './stdio/sync.js';6import {isFailedExit} from './exit/code.js';78export const execaSync = (rawFile, rawArgs, rawOptions) => {9 const {file, args, command, escapedCommand, options} = handleSyncArguments(rawFile, rawArgs, rawOptions);10 const stdioStreamsGroups = handleInputSync(options);11 const result = runExecaSync({file, args, options, command, escapedCommand, stdioStreamsGroups});9 const {file, args, command, escapedCommand, options, stdioStreamsGroups} = handleSyncArguments(rawFile, rawArgs, rawOptions);10 const result = spawnProcessSync({file, args, options, command, escapedCommand, stdioStreamsGroups});11 return handleResult(result, options);12};1314const handleSyncArguments = (rawFile, rawArgs, rawOptions) => {15 [rawFile, rawArgs, rawOptions] = normalizeArguments(rawFile, rawArgs, rawOptions);16 const {command, escapedCommand} = handleCommand(rawFile, rawArgs, rawOptions);17 const syncOptions = normalizeSyncOptions(rawOptions);18 const {file, args, command, escapedCommand, options} = handleArguments(rawFile, rawArgs, syncOptions);18 const {file, args, options} = handleArguments(rawFile, rawArgs, syncOptions);19 validateSyncOptions(options);20 const stdioStreamsGroups = handleInputSync(options);20 return {file, args, command, escapedCommand, options};21 return {file, args, command, escapedCommand, options, stdioStreamsGroups};22};2324const normalizeSyncOptions = options => options.node && !options.ipc ? {...options, ipc: false} : options;25
2 unmodified lines
28 throw new TypeError('The "ipc: true" option cannot be used with synchronous methods.');29 }30};3131const runExecaSync = ({file, args, options, command, escapedCommand, stdioStreamsGroups}) => {32const spawnProcessSync = ({file, args, options, command, escapedCommand, stdioStreamsGroups}) => {33 let syncResult;34 try {35 syncResult = spawnSync(file, args, options);36 } catch (error) {
23 unmodified lines
deleted:test/arguments/verbose.js-37 removed
1import {platform} from 'node:process';2import test from 'ava';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';56setFixtureDir();78const isWindows = platform === 'win32';910const normalizeTimestamp = stderr => stderr.replaceAll(/^\[\d{2}:\d{2}:\d{2}.\d{3}]/gm, testTimestamp);11const testTimestamp = '[00:00:00.000]';1213test('Prints command when "verbose" is true', async t => {14 const {stdout, stderr} = await execa('nested.js', [JSON.stringify({verbose: true, stdio: 'inherit'}), 'noop.js', 'test'], {all: true});15 t.is(stdout, 'test');16 t.is(normalizeTimestamp(stderr), `${testTimestamp} noop.js test`);17});1819test('Prints command with NODE_DEBUG=execa', async t => {20 const {stdout, stderr} = await execa('nested.js', [JSON.stringify({stdio: 'inherit'}), 'noop.js', 'test'], {all: true, env: {NODE_DEBUG: 'execa'}});21 t.is(stdout, 'test');22 t.is(normalizeTimestamp(stderr), `${testTimestamp} noop.js test`);23});2425test('Escape verbose command', async t => {26 const {stderr} = await execa('nested.js', [JSON.stringify({verbose: true, stdio: 'inherit'}), 'noop.js', 'one two', '"'], {all: true});27 t.true(stderr.endsWith(isWindows ? '"one two" """"' : '\'one two\' \'"\''));28});2930test('Verbose option works with inherit', async t => {31 const {all} = await execa('verbose-script.js', {all: true, env: {NODE_DEBUG: 'execa'}});32 const quote = isWindows ? '"' : '\'';33 t.is(normalizeTimestamp(all), `${testTimestamp} node -e ${quote}console.error(1)${quote}34135${testTimestamp} node -e ${quote}console.error(2)${quote}362`);37});
added:test/fixtures/nested-pipe-file.js+7 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const [sourceOptions, sourceFile, sourceArg, destinationOptions, destinationFile, destinationArg] = process.argv.slice(2);6await execa(sourceFile, [sourceArg], JSON.parse(sourceOptions))7 .pipe(destinationFile, destinationArg === undefined ? [] : [destinationArg], JSON.parse(destinationOptions));
added:test/fixtures/nested-pipe-process.js+7 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa} from '../../index.js';45const [sourceOptions, sourceFile, sourceArg, destinationOptions, destinationFile, destinationArg] = process.argv.slice(2);6await execa(sourceFile, [sourceArg], JSON.parse(sourceOptions))7 .pipe(execa(destinationFile, destinationArg === undefined ? [] : [destinationArg], JSON.parse(destinationOptions)));
added:test/fixtures/nested-pipe-script.js+7 added
1#!/usr/bin/env node2import process from 'node:process';3import {$} from '../../index.js';45const [sourceOptions, sourceFile, sourceArg, destinationOptions, destinationFile, destinationArg] = process.argv.slice(2);6await $(JSON.parse(sourceOptions))`${sourceFile} ${sourceArg}`7 .pipe(JSON.parse(destinationOptions))`${destinationFile} ${destinationArg === undefined ? [] : [destinationArg]}`;
added:test/fixtures/nested-sync.js+6 added
1#!/usr/bin/env node2import process from 'node:process';3import {execaSync} from '../../index.js';45const [options, file, ...args] = process.argv.slice(2);6execaSync(file, args, JSON.parse(options));
modified:test/fixtures/verbose-script.js+1 added-1 removed
1 unmodified line
2import {$} from '../../index.js';34const $$ = $({stdio: 'inherit'});5await $$`node -e console.error(1)`;6await $$`node -e console.error(2)`;6await $$({reject: false})`node -e process.exit(2)`;
added:test/helpers/verbose.js+38 added
1import {platform} from 'node:process';2import {stripVTControlCharacters} from 'node:util';3import {execa} from '../../index.js';4import {foobarString} from './input.js';56const isWindows = platform === 'win32';7export const QUOTE = isWindows ? '"' : '\'';89// eslint-disable-next-line max-params10const nestedExeca = (fixtureName, file, args, options, parentOptions) => {11 [args, options = {}, parentOptions = {}] = Array.isArray(args) ? [args, options, parentOptions] : [[], args, options];12 return execa(fixtureName, [JSON.stringify(options), file, ...args], parentOptions);13};1415export const nestedExecaAsync = nestedExeca.bind(undefined, 'nested.js');16export const nestedExecaSync = nestedExeca.bind(undefined, 'nested-sync.js');1718export const runErrorProcess = async (t, verbose, execaMethod) => {19 const {stderr} = await t.throwsAsync(execaMethod('noop-fail.js', ['1', foobarString], {verbose}));20 t.true(stderr.includes('exit code 2'));21 return stderr;22};2324export const runEarlyErrorProcess = async (t, execaMethod) => {25 const {stderr} = await t.throwsAsync(execaMethod('noop.js', [foobarString], {verbose: true, cwd: true}));26 t.true(stderr.includes('The "cwd" option must'));27 return stderr;28};2930export const getCommandLine = stderr => getCommandLines(stderr)[0];31export const getCommandLines = stderr => getNormalizedLines(stderr).filter(line => isCommandLine(line));32const isCommandLine = line => line.includes(' $ ') || line.includes(' | ');33export const getNormalizedLines = stderr => splitLines(normalizeStderr(stderr));34const splitLines = stderr => stderr.split('\n');3536const normalizeStderr = stderr => normalizeTimestamp(stripVTControlCharacters(stderr));37export const testTimestamp = '[00:00:00.000]';38const normalizeTimestamp = stderr => stderr.replaceAll(/^\[\d{2}:\d{2}:\d{2}.\d{3}]/gm, testTimestamp);
added:test/verbose/info.js+36 added
1import test from 'ava';2import {setFixtureDir} from '../helpers/fixtures-dir.js';3import {execa} from '../../index.js';4import {foobarString} from '../helpers/input.js';5import {6 QUOTE,7 nestedExecaAsync,8 nestedExecaSync,9 getCommandLine,10 getNormalizedLines,11 testTimestamp,12} from '../helpers/verbose.js';1314setFixtureDir();1516test('Prints command, NODE_DEBUG=execa + "inherit"', async t => {17 const {all} = await execa('verbose-script.js', {env: {NODE_DEBUG: 'execa'}, all: true});18 t.deepEqual(getNormalizedLines(all), [19 `${testTimestamp} $ node -e ${QUOTE}console.error(1)${QUOTE}`,20 '1',21 `${testTimestamp} $ node -e ${QUOTE}process.exit(2)${QUOTE}`,22 ]);23});2425test('NODE_DEBUG=execa changes verbose default value to true', async t => {26 const {stderr} = await nestedExecaAsync('noop.js', [foobarString], {}, {env: {NODE_DEBUG: 'execa'}});27 t.is(getCommandLine(stderr), `${testTimestamp} $ noop.js ${foobarString}`);28});2930const testDebugEnvPriority = async (t, execaMethod) => {31 const {stderr} = await execaMethod('noop.js', [foobarString], {verbose: false}, {env: {NODE_DEBUG: 'execa'}});32 t.is(getCommandLine(stderr), undefined);33};3435test('NODE_DEBUG=execa has lower priority', testDebugEnvPriority, nestedExecaAsync);36test('NODE_DEBUG=execa has lower priority, sync', testDebugEnvPriority, nestedExecaSync);
added:test/verbose/log.js+16 added
1import test from 'ava';2import {setFixtureDir} from '../helpers/fixtures-dir.js';3import {foobarString} from '../helpers/input.js';4import {nestedExecaAsync, nestedExecaSync} from '../helpers/verbose.js';56setFixtureDir();78const testNoStdout = async (t, verbose, execaMethod) => {9 const {stdout} = await execaMethod('noop.js', [foobarString], {verbose, stdio: 'inherit'});10 t.is(stdout, foobarString);11};1213test('Logs on stderr not stdout, verbose false', testNoStdout, false, nestedExecaAsync);14test('Logs on stderr not stdout, verbose true', testNoStdout, true, nestedExecaAsync);15test('Logs on stderr not stdout, verbose false, sync', testNoStdout, false, nestedExecaSync);16test('Logs on stderr not stdout, verbose true, sync', testNoStdout, true, nestedExecaSync);
added:test/verbose/start.js+101 added
1import test from 'ava';2import {red} from 'yoctocolors';3import {execa} from '../../index.js';4import {setFixtureDir} from '../helpers/fixtures-dir.js';5import {foobarString} from '../helpers/input.js';6import {7 QUOTE,8 nestedExecaAsync,9 nestedExecaSync,10 runErrorProcess,11 runEarlyErrorProcess,12 getCommandLine,13 getCommandLines,14 testTimestamp,15} from '../helpers/verbose.js';1617setFixtureDir();1819const testPrintCommand = async (t, execaMethod) => {20 const {stderr} = await execaMethod('noop.js', [foobarString], {verbose: true});21 t.is(getCommandLine(stderr), `${testTimestamp} $ noop.js ${foobarString}`);22};2324test('Prints command', testPrintCommand, nestedExecaAsync);25test('Prints command, sync', testPrintCommand, nestedExecaSync);2627const testNoPrintCommand = async (t, execaMethod) => {28 const {stderr} = await execaMethod('noop.js', [foobarString], {verbose: false});29 t.is(stderr, '');30};3132test('Does not print command', testNoPrintCommand, nestedExecaAsync);33test('Does not print command, sync', testNoPrintCommand, nestedExecaSync);3435const testPrintCommandError = async (t, execaMethod) => {36 const stderr = await runErrorProcess(t, true, execaMethod);37 t.is(getCommandLine(stderr), `${testTimestamp} $ noop-fail.js 1 ${foobarString}`);38};3940test('Prints command after errors', testPrintCommandError, nestedExecaAsync);41test('Prints command after errors, sync', testPrintCommandError, nestedExecaSync);4243const testPrintCommandEarly = async (t, execaMethod) => {44 const stderr = await runEarlyErrorProcess(t, execaMethod);45 t.is(getCommandLine(stderr), `${testTimestamp} $ noop.js ${foobarString}`);46};4748test('Prints command before early validation errors', testPrintCommandEarly, nestedExecaAsync);49test('Prints command before early validation errors, sync', testPrintCommandEarly, nestedExecaSync);5051const testPipeCommand = async (t, fixtureName, sourceVerbose, destinationVerbose) => {52 const {stderr} = await execa(`nested-pipe-${fixtureName}.js`, [53 JSON.stringify({verbose: sourceVerbose}),54 'noop.js',55 foobarString,56 JSON.stringify({verbose: destinationVerbose}),57 'stdin.js',58 ]);59 const pipeSymbol = fixtureName === 'process' ? '$' : '|';60 const lines = getCommandLines(stderr);61 t.is(lines.includes(`${testTimestamp} $ noop.js ${foobarString}`), sourceVerbose);62 t.is(lines.includes(`${testTimestamp} ${pipeSymbol} stdin.js`), destinationVerbose);63};6465test('Prints both commands piped with .pipe("file")', testPipeCommand, 'file', true, true);66test('Prints both commands piped with .pipe`command`', testPipeCommand, 'script', true, true);67test('Prints both commands piped with .pipe(childProcess)', testPipeCommand, 'process', true, true);68test('Prints first command piped with .pipe("file")', testPipeCommand, 'file', true, false);69test('Prints first command piped with .pipe`command`', testPipeCommand, 'script', true, false);70test('Prints first command piped with .pipe(childProcess)', testPipeCommand, 'process', true, false);71test('Prints second command piped with .pipe("file")', testPipeCommand, 'file', false, true);72test('Prints second command piped with .pipe`command`', testPipeCommand, 'script', false, true);73test('Prints second command piped with .pipe(childProcess)', testPipeCommand, 'process', false, true);74test('Prints neither commands piped with .pipe("file")', testPipeCommand, 'file', false, false);75test('Prints neither commands piped with .pipe`command`', testPipeCommand, 'script', false, false);76test('Prints neither commands piped with .pipe(childProcess)', testPipeCommand, 'process', false, false);7778test('Quotes spaces from command', async t => {79 const {stderr} = await nestedExecaAsync('noop.js', ['foo bar'], {verbose: true});80 t.is(getCommandLine(stderr), `${testTimestamp} $ noop.js ${QUOTE}foo bar${QUOTE}`);81});8283test('Quotes special punctuation from command', async t => {84 const {stderr} = await nestedExecaAsync('noop.js', ['%'], {verbose: true});85 t.is(getCommandLine(stderr), `${testTimestamp} $ noop.js ${QUOTE}%${QUOTE}`);86});8788test('Does not escape internal characters from command', async t => {89 const {stderr} = await nestedExecaAsync('noop.js', ['ã'], {verbose: true});90 t.is(getCommandLine(stderr), `${testTimestamp} $ noop.js ${QUOTE}ã${QUOTE}`);91});9293test('Escapes color sequences from command', async t => {94 const {stderr} = await nestedExecaAsync('noop.js', [red(foobarString)], {verbose: true}, {env: {FORCE_COLOR: '1'}});95 t.true(getCommandLine(stderr).includes(`${QUOTE}\\u001b[31m${foobarString}\\u001b[39m${QUOTE}`));96});9798test('Escapes control characters from command', async t => {99 const {stderr} = await nestedExecaAsync('noop.js', ['\u0001'], {verbose: true});100 t.is(getCommandLine(stderr), `${testTimestamp} $ noop.js ${QUOTE}\\u0001${QUOTE}`);101});
modified:index.test-d.ts+2 added
1440 unmodified lines
1441execa('unicorns', {windowsHide: false});1442execaSync('unicorns', {windowsHide: false});1443execa('unicorns', {verbose: false});1444execaSync('unicorns', {verbose: false});1445expectError(execa('unicorns', {verbose: 'other'}));1446expectError(execaSync('unicorns', {verbose: 'other'}));1447/* eslint-enable @typescript-eslint/no-floating-promises */1448expectType<boolean>(execa('unicorns').kill());1449execa('unicorns').kill('SIGKILL');1450execa('unicorns').kill(undefined);
113 unmodified lines
modified:package.json+2 added-1 removed
64 unmodified lines
65 "path-key": "^4.0.0",66 "tempfile": "^5.0.0",67 "tsd": "^0.29.0",68 "which": "^4.0.0",69 "xo": "^0.56.0"69 "xo": "^0.56.0",70 "yoctocolors": "^2.0.0"71 },72 "c8": {73 "reporter": [74 "text",
20 unmodified lines
modified:readme.md+2 added-2 removed
140 unmodified lines
141unicorns142rainbows143144> NODE_DEBUG=execa node file.js145[16:50:03.305] echo unicorns145[19:49:00.360] $ echo unicorns146unicorns147[16:50:03.308] echo rainbows147[19:49:00.383] $ echo rainbows148rainbows149```150151### Input/output
891 unmodified lines