Add `parseCommandString()` (#1054)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 62d02af · Browse files · 11 files·+203 added−60 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+203 added−60 removed
- tests:+121 added−31 removed
- other:+82 added−29 removed
Provenance
- Commit
b9474c3- Tree
c674976- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
62d02af
11 files changed+203 added−60 removed
modified:docs/api.md+3 added-8 removed
81 unmodified lines82 This is the preferred method when executing Node.js files.83 84 [More info.](node.md)85 86-### execaCommand(command, options?)86+### parseCommandString(command)87 88 `command`: `string`\89-`options`: [`Options`](#options)\90-_Returns_: [`ResultPromise`](#return-value)89+_Returns_: `string[]`90 92-Executes a command. `command` is a string that includes both the `file` and its `arguments`.91+Split a `command` string into an array. For example, `'npm run build'` returns `['npm', 'run', 'build']` and `'argument otherArgument'` returns `['argument', 'otherArgument']`.92 94-This is only intended for very specific cases, such as a [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop). This should be avoided otherwise.95-96-Just like `execa()`, this can [bind options](execution.md#globalshared-options). It can also be [run synchronously](#execasyncfile-arguments-options) using `execaCommandSync()`.97-93 [More info.](escaping.md#user-defined-input)94 95 ## Return value96 951 unmodified linesmodified:docs/debugging.md+1 added-1 removed
10 unmodified lines1112131415151617181994 unmodified lines10 unmodified lines[`error.command`](api.md#resultcommand) contains the file and [arguments](input.md#command-arguments) that were run. It is intended for logging or debugging.
[`error.escapedCommand`](api.md#resultescapedcommand) is the same, except control characters are escaped. This makes it safe to either print or copy and paste in a terminal, for debugging purposes.
Since the escaping is fairly basic, neither `error.command` nor `error.escapedCommand` should be executed directly, including using [`execa()`](api.md#execafile-arguments-options) or [`execaCommand()`](api.md#execacommandcommand-options).Since the escaping is fairly basic, neither `error.command` nor `error.escapedCommand` should be executed directly, including using [`execa()`](api.md#execafile-arguments-options) or [`parseCommandString()`](api.md#parsecommandstringcommand).
```jsimport {execa} from 'execa';
94 unmodified linesmodified:docs/escaping.md+15 added-14 removed
27 unmodified lines28 29 The above syntaxes allow the file and its arguments to be user-defined by passing a variable.30 31 ```js32+import {execa} from 'execa';33+32-const command = 'npm';34+const file = 'npm';35 const commandArguments = ['run', 'task with space'];36+await execa`${file} ${commandArguments}`;37 35-await execa(command, commandArguments);36-await execa`${command} ${commandArguments}`;38+await execa(file, commandArguments);39 ```40 39-However, [`execaCommand()`](api.md#execacommandcommand-options) must be used instead if:40-- _Both_ the file and its arguments are user-defined41-- _And_ those are supplied as a single string41+If the file and/or multiple arguments are supplied as a single string, [`parseCommandString()`](api.md#parsecommandstringcommand) can split it into an array.42 43-This is only intended for very specific cases, such as a [REPL](https://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop). This should be avoided otherwise.44-43 ```js46-import {execaCommand} from 'execa';44+import {execa, parseCommandString} from 'execa';45 48-for await (const commandAndArguments of getReplLine()) {49- await execaCommand(commandAndArguments);50-}46+const commandString = 'npm run task';47+const commandArray = parseCommandString(commandString);48+await execa`${commandArray}`;49+50+const [file, ...commandArguments] = commandArray;51+await execa(file, commandArguments);52 ```53 53-Arguments passed to `execaCommand()` are automatically escaped. They can contain any character (except [null bytes](https://en.wikipedia.org/wiki/Null_character)), but spaces must be escaped with a backslash.54+Spaces are used as delimiters. They can be escaped with a backslash.55 56 ```js56-await execaCommand('npm run task\\ with\\ space');57+await execa`${parseCommandString('npm run task\\ with\\ space')}`;58 ```59 60 ## Shells61 29 unmodified linesmodified:lib/methods/command.js+17 added-3 removed
8 unmodified lines9101112131415161718192021222324252627281429303132332 unmodified lines363738392526404142438 unmodified lines if (unusedArguments.length > 0) { throw new TypeError(`The command and its arguments must be passed as a single string: ${command} ${unusedArguments}.`); }
const [file, ...commandArguments] = parseCommandString(command); return {file, commandArguments};};
// Convert `command` string into an array of file or arguments to pass to $`${...fileOrCommandArguments}`export const parseCommandString = command => { if (typeof command !== 'string') { throw new TypeError(`The command must be a string: ${String(command)}.`); }
const trimmedCommand = command.trim(); if (trimmedCommand === '') { return []; }
const tokens = []; for (const token of command.trim().split(SPACES_REGEXP)) { for (const token of trimmedCommand.split(SPACES_REGEXP)) { // Allow spaces to be escaped by a backslash if not meant as a delimiter const previousToken = tokens.at(-1); if (previousToken && previousToken.endsWith('\\')) { // Merge previous token with current one2 unmodified lines tokens.push(token); } }
const [file, ...commandArguments] = tokens; return {file, commandArguments}; return tokens;};
const SPACES_REGEXP = / +/g;modified:lib/methods/main-async.js+1 added-1 removed
18 unmodified lines19 import {addConvertedStreams} from '../convert/add.js';20 import {createDeferred} from '../utils/deferred.js';21 import {mergePromise} from './promise.js';22 23-// Main shared logic for all async methods: `execa()`, `execaCommand()`, `$`, `execaNode()`23+// Main shared logic for all async methods: `execa()`, `$`, `execaNode()`24 export const execaCoreAsync = (rawFile, rawArguments, rawOptions, createNested) => {25 const {file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleAsyncArguments(rawFile, rawArguments, rawOptions);26 const {subprocess, promise} = spawnSubprocessAsync({27 file,159 unmodified linesmodified:lib/methods/main-sync.js+1 added-1 removed
10 unmodified lines11 import {logEarlyResult} from '../verbose/complete.js';12 import {getAllSync} from '../resolve/all-sync.js';13 import {getExitResultSync} from '../resolve/exit-sync.js';14 15-// Main shared logic for all sync methods: `execaSync()`, `execaCommandSync()`, `$.sync()`15+// Main shared logic for all sync methods: `execaSync()`, `$.sync()`16 export const execaCoreSync = (rawFile, rawArguments, rawOptions) => {17 const {file, commandArguments, command, escapedCommand, startTime, verboseInfo, options, fileDescriptors} = handleSyncArguments(rawFile, rawArguments, rawOptions);18 const result = spawnSubprocessSync({19 file,142 unmodified linesmodified:test/methods/command.js+121 added-31 removed
1 import {join} from 'node:path';2 import test from 'ava';3-import {execaCommand, execaCommandSync} from '../../index.js';4-import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';3+import {4+ execa,5+ execaSync,6+ $,7+ execaNode,8+ execaCommand,9+ execaCommandSync,10+ parseCommandString,11+} from '../../index.js';12+import {13+ setFixtureDirectory,14+ FIXTURES_DIRECTORY,15+ FIXTURES_DIRECTORY_URL,16+} from '../helpers/fixtures-directory.js';17 import {QUOTE} from '../helpers/verbose.js';18 19 setFixtureDirectory();20 const STDIN_FIXTURE = join(FIXTURES_DIRECTORY, 'stdin.js');21+const ECHO_FIXTURE_URL = new URL('echo.js', FIXTURES_DIRECTORY_URL);22 23+const parseAndRunCommand = command => execa`${parseCommandString(command)}`;24+25 test('execaCommand()', async t => {26 const {stdout} = await execaCommand('echo.js foo bar');27 t.is(stdout, 'foo\nbar');28 });29 30+test('parseCommandString() + execa()', async t => {31+ const {stdout} = await execa('echo.js', parseCommandString('foo bar'));32+ t.is(stdout, 'foo\nbar');33+});34+35 test('execaCommandSync()', t => {36 const {stdout} = execaCommandSync('echo.js foo bar');37 t.is(stdout, 'foo\nbar');38 });39 40+test('parseCommandString() + execaSync()', t => {41+ const {stdout} = execaSync('echo.js', parseCommandString('foo bar'));42+ t.is(stdout, 'foo\nbar');43+});44+45 test('execaCommand`...`', async t => {46 const {stdout} = await execaCommand`${'echo.js foo bar'}`;47 t.is(stdout, 'foo\nbar');48 });49 50+test('parseCommandString() + execa`...`', async t => {51+ const {stdout} = await execa`${parseCommandString('echo.js foo bar')}`;52+ t.is(stdout, 'foo\nbar');53+});54+55+test('parseCommandString() + execa`...`, only arguments', async t => {56+ const {stdout} = await execa`echo.js ${parseCommandString('foo bar')}`;57+ t.is(stdout, 'foo\nbar');58+});59+60+test('parseCommandString() + execa`...`, only some arguments', async t => {61+ const {stdout} = await execa`echo.js ${'foo bar'} ${parseCommandString('foo bar')}`;62+ t.is(stdout, 'foo bar\nfoo\nbar');63+});64+65 test('execaCommandSync`...`', t => {66 const {stdout} = execaCommandSync`${'echo.js foo bar'}`;67 t.is(stdout, 'foo\nbar');68 });69 70+test('parseCommandString() + execaSync`...`', t => {71+ const {stdout} = execaSync`${parseCommandString('echo.js foo bar')}`;72+ t.is(stdout, 'foo\nbar');73+});74+75+test('parseCommandString() + execaSync`...`, only arguments', t => {76+ const {stdout} = execaSync`echo.js ${parseCommandString('foo bar')}`;77+ t.is(stdout, 'foo\nbar');78+});79+80+test('parseCommandString() + execaSync`...`, only some arguments', t => {81+ const {stdout} = execaSync`echo.js ${'foo bar'} ${parseCommandString('foo bar')}`;82+ t.is(stdout, 'foo bar\nfoo\nbar');83+});84+85+test('parseCommandString() + $', async t => {86+ const {stdout} = await $`${parseCommandString('echo.js foo bar')}`;87+ t.is(stdout, 'foo\nbar');88+});89+90+test('parseCommandString() + $.sync', t => {91+ const {stdout} = $.sync`${parseCommandString('echo.js foo bar')}`;92+ t.is(stdout, 'foo\nbar');93+});94+95+test('parseCommandString() + execaNode', async t => {96+ const {stdout} = await execaNode(ECHO_FIXTURE_URL, parseCommandString('foo bar'));97+ t.is(stdout, 'foo\nbar');98+});99+100 test('execaCommand(options)`...`', async t => {101 const {stdout} = await execaCommand({stripFinalNewline: false})`${'echo.js foo bar'}`;102 t.is(stdout, 'foo\nbar\n');103 });32 unmodified lines136 const {stdout} = execaCommandSync({stripFinalNewline: false})('echo.js foo bar', {stripFinalNewline: true});137 t.is(stdout, 'foo\nbar');138 });139 70-test('execaCommand() allows escaping spaces in commands', async t => {71- const {stdout} = await execaCommand('command\\ with\\ space.js foo bar');72- t.is(stdout, 'foo\nbar');73-});74-75-test('execaCommand() trims', async t => {76- const {stdout} = await execaCommand(' echo.js foo bar ');77- t.is(stdout, 'foo\nbar');78-});79-80-const testExecaCommandOutput = async (t, commandArguments, expectedOutput) => {81- const {stdout} = await execaCommand(`echo.js ${commandArguments}`);82- t.is(stdout, expectedOutput);83-};84-85-test('execaCommand() ignores consecutive spaces', testExecaCommandOutput, 'foo bar', 'foo\nbar');86-test('execaCommand() escapes other whitespaces', testExecaCommandOutput, 'foo\tbar', 'foo\tbar');87-test('execaCommand() allows escaping spaces', testExecaCommandOutput, 'foo\\ bar', 'foo bar');88-test('execaCommand() allows escaping backslashes before spaces', testExecaCommandOutput, 'foo\\\\ bar', 'foo\\ bar');89-test('execaCommand() allows escaping multiple backslashes before spaces', testExecaCommandOutput, 'foo\\\\\\\\ bar', 'foo\\\\\\ bar');90-test('execaCommand() allows escaping backslashes not before spaces', testExecaCommandOutput, 'foo\\bar baz', 'foo\\bar\nbaz');91-140 const testInvalidArgumentsArray = (t, execaMethod) => {93- t.throws(() => {94- execaMethod('echo', ['foo']);95- }, {message: /The command and its arguments must be passed as a single string/});141+ t.throws(() => execaMethod('echo', ['foo']), {142+ message: /The command and its arguments must be passed as a single string/,143+ });144 };145 146 test('execaCommand() must not pass an array of arguments', testInvalidArgumentsArray, execaCommand);147 test('execaCommandSync() must not pass an array of arguments', testInvalidArgumentsArray, execaCommandSync);148 149 const testInvalidArgumentsTemplate = (t, execaMethod) => {102- t.throws(() => {103- // eslint-disable-next-line no-unused-expressions104- execaMethod`echo foo`;105- }, {message: /The command and its arguments must be passed as a single string/});150+ t.throws(() => execaMethod`echo foo`, {151+ message: /The command and its arguments must be passed as a single string/,152+ });153 };154 155 test('execaCommand() must not pass an array of arguments with a template string', testInvalidArgumentsTemplate, execaCommand);156 test('execaCommandSync() must not pass an array of arguments with a template string', testInvalidArgumentsTemplate, execaCommandSync);157+158+const testInvalidArgumentsParse = (t, command) => {159+ t.throws(() => parseCommandString(command), {160+ message: /The command must be a string/,161+ });162+};163+164+test('execaCommand() must not pass a number', testInvalidArgumentsParse, 0);165+test('execaCommand() must not pass undefined', testInvalidArgumentsParse, undefined);166+test('execaCommand() must not pass null', testInvalidArgumentsParse, null);167+test('execaCommand() must not pass a symbol', testInvalidArgumentsParse, Symbol('test'));168+test('execaCommand() must not pass an object', testInvalidArgumentsParse, {});169+test('execaCommand() must not pass an array', testInvalidArgumentsParse, []);170+171+const testExecaCommandOutput = async (t, command, expectedOutput, execaMethod) => {172+ const {stdout} = await execaMethod(command);173+ t.is(stdout, expectedOutput);174+};175+176+test('execaCommand() allows escaping spaces in commands', testExecaCommandOutput, 'command\\ with\\ space.js foo bar', 'foo\nbar', execaCommand);177+test('execaCommand() trims', testExecaCommandOutput, ' echo.js foo bar ', 'foo\nbar', execaCommand);178+test('execaCommand() ignores consecutive spaces', testExecaCommandOutput, 'echo.js foo bar', 'foo\nbar', execaCommand);179+test('execaCommand() escapes other whitespaces', testExecaCommandOutput, 'echo.js foo\tbar', 'foo\tbar', execaCommand);180+test('execaCommand() allows escaping spaces', testExecaCommandOutput, 'echo.js foo\\ bar', 'foo bar', execaCommand);181+test('execaCommand() allows escaping backslashes before spaces', testExecaCommandOutput, 'echo.js foo\\\\ bar', 'foo\\ bar', execaCommand);182+test('execaCommand() allows escaping multiple backslashes before spaces', testExecaCommandOutput, 'echo.js foo\\\\\\\\ bar', 'foo\\\\\\ bar', execaCommand);183+test('execaCommand() allows escaping backslashes not before spaces', testExecaCommandOutput, 'echo.js foo\\bar baz', 'foo\\bar\nbaz', execaCommand);184+test('parseCommandString() allows escaping spaces in commands', testExecaCommandOutput, 'command\\ with\\ space.js foo bar', 'foo\nbar', parseAndRunCommand);185+test('parseCommandString() trims', testExecaCommandOutput, ' echo.js foo bar ', 'foo\nbar', parseAndRunCommand);186+test('parseCommandString() ignores consecutive spaces', testExecaCommandOutput, 'echo.js foo bar', 'foo\nbar', parseAndRunCommand);187+test('parseCommandString() escapes other whitespaces', testExecaCommandOutput, 'echo.js foo\tbar', 'foo\tbar', parseAndRunCommand);188+test('parseCommandString() allows escaping spaces', testExecaCommandOutput, 'echo.js foo\\ bar', 'foo bar', parseAndRunCommand);189+test('parseCommandString() allows escaping backslashes before spaces', testExecaCommandOutput, 'echo.js foo\\\\ bar', 'foo\\ bar', parseAndRunCommand);190+test('parseCommandString() allows escaping multiple backslashes before spaces', testExecaCommandOutput, 'echo.js foo\\\\\\\\ bar', 'foo\\\\\\ bar', parseAndRunCommand);191+test('parseCommandString() allows escaping backslashes not before spaces', testExecaCommandOutput, 'echo.js foo\\bar baz', 'foo\\bar\nbaz', parseAndRunCommand);192+193+test('parseCommandString() can get empty strings', t => {194+ t.deepEqual(parseCommandString(''), []);195+});196+197+test('parseCommandString() can get only whitespaces', t => {198+ t.deepEqual(parseCommandString(' '), []);199+});modified:test-d/methods/command.test-d.ts+22 added
1 import {expectType, expectError, expectAssignable} from 'tsd';2 import {3+ execa,4+ execaSync,5+ $,6+ execaNode,7 execaCommand,8 execaCommandSync,9+ parseCommandString,10 type Result,11 type ResultPromise,12 type SyncResult,13 } from '../../index.js';14 15 const fileUrl = new URL('file:///test');16 const stringArray = ['foo', 'bar'] as const;17 18+expectError(parseCommandString());19+expectError(parseCommandString(true));20+expectError(parseCommandString(['unicorns', 'arg']));21+22+expectType<string[]>(parseCommandString(''));23+expectType<string[]>(parseCommandString('unicorns foo bar'));24+25+expectType<Result<{}>>(await execa`${parseCommandString('unicorns foo bar')}`);26+expectType<SyncResult<{}>>(execaSync`${parseCommandString('unicorns foo bar')}`);27+expectType<Result<{}>>(await $`${parseCommandString('unicorns foo bar')}`);28+expectType<SyncResult<{}>>($.sync`${parseCommandString('unicorns foo bar')}`);29+expectType<Result<{}>>(await execaNode`${parseCommandString('foo bar')}`);30+31+expectType<Result<{}>>(await execa`unicorns ${parseCommandString('foo bar')}`);32+expectType<Result<{}>>(await execa('unicorns', parseCommandString('foo bar')));33+expectType<Result<{}>>(await execa('unicorns', ['foo', ...parseCommandString('bar')]));34+35 expectError(execaCommand());36 expectError(execaCommand(true));37 expectError(execaCommand(['unicorns', 'arg']));38 expectAssignable<ResultPromise>(execaCommand('unicorns'));85 unmodified linesmodified:types/methods/command.d.ts+20 added
66 unmodified lines67 }68 ```69 */70 export declare const execaCommandSync: ExecaCommandSync<{}>;71+72+/**73+Split a `command` string into an array. For example, `'npm run build'` returns `['npm', 'run', 'build']` and `'argument otherArgument'` returns `['argument', 'otherArgument']`.74+75+@param command - The file to execute and/or its arguments.76+@returns fileOrArgument[]77+78+@example79+```80+import {execa, parseCommandString} from 'execa';81+82+const commandString = 'npm run task';83+const commandArray = parseCommandString(commandString);84+await execa`${commandArray}`;85+86+const [file, ...commandArguments] = commandArray;87+await execa(file, commandArguments);88+```89+*/90+export function parseCommandString(command: string): string[];modified:index.d.ts+1 added-1 removed
9 unmodified lines10 export {ExecaError, ExecaSyncError} from './types/return/final-error.js';11 export type {TemplateExpression} from './types/methods/template.js';12 export {execa} from './types/methods/main-async.js';13 export {execaSync} from './types/methods/main-sync.js';14-export {execaCommand, execaCommandSync} from './types/methods/command.js';14+export {execaCommand, execaCommandSync, parseCommandString} from './types/methods/command.js';15 export {$} from './types/methods/script.js';16 export {execaNode} from './types/methods/node.js';modified:index.js+1 added
1 unmodified line2 import {mapCommandAsync, mapCommandSync} from './lib/methods/command.js';3 import {mapNode} from './lib/methods/node.js';4 import {mapScriptAsync, setScriptSync, deepScriptOptions} from './lib/methods/script.js';5 6+export {parseCommandString} from './lib/methods/command.js';7 export {ExecaError, ExecaSyncError} from './lib/return/final-error.js';8 9 export const execa = createExeca(() => ({}));10 export const execaSync = createExeca(() => ({isSync: true}));4 unmodified lines