Skip to content
Myr

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

11 files+203 added−60 removed

modified:docs/api.md+3 added-8 removed
81 unmodified lines
82This is the preferred method when executing Node.js files.8384[More info.](node.md)8586### execaCommand(command, options?)86### parseCommandString(command)8788`command`: `string`\89`options`: [`Options`](#options)\90_Returns_: [`ResultPromise`](#return-value)89_Returns_: `string[]`9092Executes a command. `command` is a string that includes both the `file` and its `arguments`.91Split a `command` string into an array. For example, `'npm run build'` returns `['npm', 'run', 'build']` and `'argument otherArgument'` returns `['argument', 'otherArgument']`.9294This 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.9596Just like `execa()`, this can [bind options](execution.md#globalshared-options). It can also be [run synchronously](#execasyncfile-arguments-options) using `execaCommandSync()`.9793[More info.](escaping.md#user-defined-input)9495## Return value96
951 unmodified lines
modified:docs/debugging.md+1 added-1 removed
modified:docs/escaping.md+15 added-14 removed
27 unmodified lines
2829The above syntaxes allow the file and its arguments to be user-defined by passing a variable.3031```js32import {execa} from 'execa';3332const command = 'npm';34const file = 'npm';35const commandArguments = ['run', 'task with space'];36await execa`${file} ${commandArguments}`;3735await execa(command, commandArguments);36await execa`${command} ${commandArguments}`;38await execa(file, commandArguments);39```4039However, [`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 string41If the file and/or multiple arguments are supplied as a single string, [`parseCommandString()`](api.md#parsecommandstringcommand) can split it into an array.4243This 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.4443```js46import {execaCommand} from 'execa';44import {execa, parseCommandString} from 'execa';4548for await (const commandAndArguments of getReplLine()) {49 await execaCommand(commandAndArguments);50}46const commandString = 'npm run task';47const commandArray = parseCommandString(commandString);48await execa`${commandArray}`;4950const [file, ...commandArguments] = commandArray;51await execa(file, commandArguments);52```5353Arguments 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.54Spaces are used as delimiters. They can be escaped with a backslash.5556```js56await execaCommand('npm run task\\ with\\ space');57await execa`${parseCommandString('npm run task\\ with\\ space')}`;58```5960## Shells61
29 unmodified lines
modified:lib/methods/command.js+17 added-3 removed
modified:lib/methods/main-async.js+1 added-1 removed
18 unmodified lines
19import {addConvertedStreams} from '../convert/add.js';20import {createDeferred} from '../utils/deferred.js';21import {mergePromise} from './promise.js';2223// Main shared logic for all async methods: `execa()`, `execaCommand()`, `$`, `execaNode()`23// Main shared logic for all async methods: `execa()`, `$`, `execaNode()`24export 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 lines
modified:lib/methods/main-sync.js+1 added-1 removed
10 unmodified lines
11import {logEarlyResult} from '../verbose/complete.js';12import {getAllSync} from '../resolve/all-sync.js';13import {getExitResultSync} from '../resolve/exit-sync.js';1415// Main shared logic for all sync methods: `execaSync()`, `execaCommandSync()`, `$.sync()`15// Main shared logic for all sync methods: `execaSync()`, `$.sync()`16export 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 lines
modified:test/methods/command.js+121 added-31 removed
1import {join} from 'node:path';2import test from 'ava';3import {execaCommand, execaCommandSync} from '../../index.js';4import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';3import {4 execa,5 execaSync,6 $,7 execaNode,8 execaCommand,9 execaCommandSync,10 parseCommandString,11} from '../../index.js';12import {13 setFixtureDirectory,14 FIXTURES_DIRECTORY,15 FIXTURES_DIRECTORY_URL,16} from '../helpers/fixtures-directory.js';17import {QUOTE} from '../helpers/verbose.js';1819setFixtureDirectory();20const STDIN_FIXTURE = join(FIXTURES_DIRECTORY, 'stdin.js');21const ECHO_FIXTURE_URL = new URL('echo.js', FIXTURES_DIRECTORY_URL);2223const parseAndRunCommand = command => execa`${parseCommandString(command)}`;2425test('execaCommand()', async t => {26 const {stdout} = await execaCommand('echo.js foo bar');27 t.is(stdout, 'foo\nbar');28});2930test('parseCommandString() + execa()', async t => {31 const {stdout} = await execa('echo.js', parseCommandString('foo bar'));32 t.is(stdout, 'foo\nbar');33});3435test('execaCommandSync()', t => {36 const {stdout} = execaCommandSync('echo.js foo bar');37 t.is(stdout, 'foo\nbar');38});3940test('parseCommandString() + execaSync()', t => {41 const {stdout} = execaSync('echo.js', parseCommandString('foo bar'));42 t.is(stdout, 'foo\nbar');43});4445test('execaCommand`...`', async t => {46 const {stdout} = await execaCommand`${'echo.js foo bar'}`;47 t.is(stdout, 'foo\nbar');48});4950test('parseCommandString() + execa`...`', async t => {51 const {stdout} = await execa`${parseCommandString('echo.js foo bar')}`;52 t.is(stdout, 'foo\nbar');53});5455test('parseCommandString() + execa`...`, only arguments', async t => {56 const {stdout} = await execa`echo.js ${parseCommandString('foo bar')}`;57 t.is(stdout, 'foo\nbar');58});5960test('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});6465test('execaCommandSync`...`', t => {66 const {stdout} = execaCommandSync`${'echo.js foo bar'}`;67 t.is(stdout, 'foo\nbar');68});6970test('parseCommandString() + execaSync`...`', t => {71 const {stdout} = execaSync`${parseCommandString('echo.js foo bar')}`;72 t.is(stdout, 'foo\nbar');73});7475test('parseCommandString() + execaSync`...`, only arguments', t => {76 const {stdout} = execaSync`echo.js ${parseCommandString('foo bar')}`;77 t.is(stdout, 'foo\nbar');78});7980test('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});8485test('parseCommandString() + $', async t => {86 const {stdout} = await $`${parseCommandString('echo.js foo bar')}`;87 t.is(stdout, 'foo\nbar');88});8990test('parseCommandString() + $.sync', t => {91 const {stdout} = $.sync`${parseCommandString('echo.js foo bar')}`;92 t.is(stdout, 'foo\nbar');93});9495test('parseCommandString() + execaNode', async t => {96 const {stdout} = await execaNode(ECHO_FIXTURE_URL, parseCommandString('foo bar'));97 t.is(stdout, 'foo\nbar');98});99100test('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 lines
136 const {stdout} = execaCommandSync({stripFinalNewline: false})('echo.js foo bar', {stripFinalNewline: true});137 t.is(stdout, 'foo\nbar');138});13970test('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});7475test('execaCommand() trims', async t => {76 const {stdout} = await execaCommand(' echo.js foo bar ');77 t.is(stdout, 'foo\nbar');78});7980const testExecaCommandOutput = async (t, commandArguments, expectedOutput) => {81 const {stdout} = await execaCommand(`echo.js ${commandArguments}`);82 t.is(stdout, expectedOutput);83};8485test('execaCommand() ignores consecutive spaces', testExecaCommandOutput, 'foo bar', 'foo\nbar');86test('execaCommand() escapes other whitespaces', testExecaCommandOutput, 'foo\tbar', 'foo\tbar');87test('execaCommand() allows escaping spaces', testExecaCommandOutput, 'foo\\ bar', 'foo bar');88test('execaCommand() allows escaping backslashes before spaces', testExecaCommandOutput, 'foo\\\\ bar', 'foo\\ bar');89test('execaCommand() allows escaping multiple backslashes before spaces', testExecaCommandOutput, 'foo\\\\\\\\ bar', 'foo\\\\\\ bar');90test('execaCommand() allows escaping backslashes not before spaces', testExecaCommandOutput, 'foo\\bar baz', 'foo\\bar\nbaz');91140const 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};145146test('execaCommand() must not pass an array of arguments', testInvalidArgumentsArray, execaCommand);147test('execaCommandSync() must not pass an array of arguments', testInvalidArgumentsArray, execaCommandSync);148149const 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};154155test('execaCommand() must not pass an array of arguments with a template string', testInvalidArgumentsTemplate, execaCommand);156test('execaCommandSync() must not pass an array of arguments with a template string', testInvalidArgumentsTemplate, execaCommandSync);157158const testInvalidArgumentsParse = (t, command) => {159 t.throws(() => parseCommandString(command), {160 message: /The command must be a string/,161 });162};163164test('execaCommand() must not pass a number', testInvalidArgumentsParse, 0);165test('execaCommand() must not pass undefined', testInvalidArgumentsParse, undefined);166test('execaCommand() must not pass null', testInvalidArgumentsParse, null);167test('execaCommand() must not pass a symbol', testInvalidArgumentsParse, Symbol('test'));168test('execaCommand() must not pass an object', testInvalidArgumentsParse, {});169test('execaCommand() must not pass an array', testInvalidArgumentsParse, []);170171const testExecaCommandOutput = async (t, command, expectedOutput, execaMethod) => {172 const {stdout} = await execaMethod(command);173 t.is(stdout, expectedOutput);174};175176test('execaCommand() allows escaping spaces in commands', testExecaCommandOutput, 'command\\ with\\ space.js foo bar', 'foo\nbar', execaCommand);177test('execaCommand() trims', testExecaCommandOutput, ' echo.js foo bar ', 'foo\nbar', execaCommand);178test('execaCommand() ignores consecutive spaces', testExecaCommandOutput, 'echo.js foo bar', 'foo\nbar', execaCommand);179test('execaCommand() escapes other whitespaces', testExecaCommandOutput, 'echo.js foo\tbar', 'foo\tbar', execaCommand);180test('execaCommand() allows escaping spaces', testExecaCommandOutput, 'echo.js foo\\ bar', 'foo bar', execaCommand);181test('execaCommand() allows escaping backslashes before spaces', testExecaCommandOutput, 'echo.js foo\\\\ bar', 'foo\\ bar', execaCommand);182test('execaCommand() allows escaping multiple backslashes before spaces', testExecaCommandOutput, 'echo.js foo\\\\\\\\ bar', 'foo\\\\\\ bar', execaCommand);183test('execaCommand() allows escaping backslashes not before spaces', testExecaCommandOutput, 'echo.js foo\\bar baz', 'foo\\bar\nbaz', execaCommand);184test('parseCommandString() allows escaping spaces in commands', testExecaCommandOutput, 'command\\ with\\ space.js foo bar', 'foo\nbar', parseAndRunCommand);185test('parseCommandString() trims', testExecaCommandOutput, ' echo.js foo bar ', 'foo\nbar', parseAndRunCommand);186test('parseCommandString() ignores consecutive spaces', testExecaCommandOutput, 'echo.js foo bar', 'foo\nbar', parseAndRunCommand);187test('parseCommandString() escapes other whitespaces', testExecaCommandOutput, 'echo.js foo\tbar', 'foo\tbar', parseAndRunCommand);188test('parseCommandString() allows escaping spaces', testExecaCommandOutput, 'echo.js foo\\ bar', 'foo bar', parseAndRunCommand);189test('parseCommandString() allows escaping backslashes before spaces', testExecaCommandOutput, 'echo.js foo\\\\ bar', 'foo\\ bar', parseAndRunCommand);190test('parseCommandString() allows escaping multiple backslashes before spaces', testExecaCommandOutput, 'echo.js foo\\\\\\\\ bar', 'foo\\\\\\ bar', parseAndRunCommand);191test('parseCommandString() allows escaping backslashes not before spaces', testExecaCommandOutput, 'echo.js foo\\bar baz', 'foo\\bar\nbaz', parseAndRunCommand);192193test('parseCommandString() can get empty strings', t => {194 t.deepEqual(parseCommandString(''), []);195});196197test('parseCommandString() can get only whitespaces', t => {198 t.deepEqual(parseCommandString(' '), []);199});
modified:test-d/methods/command.test-d.ts+22 added
1import {expectType, expectError, expectAssignable} from 'tsd';2import {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';1415const fileUrl = new URL('file:///test');16const stringArray = ['foo', 'bar'] as const;1718expectError(parseCommandString());19expectError(parseCommandString(true));20expectError(parseCommandString(['unicorns', 'arg']));2122expectType<string[]>(parseCommandString(''));23expectType<string[]>(parseCommandString('unicorns foo bar'));2425expectType<Result<{}>>(await execa`${parseCommandString('unicorns foo bar')}`);26expectType<SyncResult<{}>>(execaSync`${parseCommandString('unicorns foo bar')}`);27expectType<Result<{}>>(await $`${parseCommandString('unicorns foo bar')}`);28expectType<SyncResult<{}>>($.sync`${parseCommandString('unicorns foo bar')}`);29expectType<Result<{}>>(await execaNode`${parseCommandString('foo bar')}`);3031expectType<Result<{}>>(await execa`unicorns ${parseCommandString('foo bar')}`);32expectType<Result<{}>>(await execa('unicorns', parseCommandString('foo bar')));33expectType<Result<{}>>(await execa('unicorns', ['foo', ...parseCommandString('bar')]));3435expectError(execaCommand());36expectError(execaCommand(true));37expectError(execaCommand(['unicorns', 'arg']));38expectAssignable<ResultPromise>(execaCommand('unicorns'));
85 unmodified lines
modified:types/methods/command.d.ts+20 added
66 unmodified lines
67}68```69*/70export declare const execaCommandSync: ExecaCommandSync<{}>;7172/**73Split a `command` string into an array. For example, `'npm run build'` returns `['npm', 'run', 'build']` and `'argument otherArgument'` returns `['argument', 'otherArgument']`.7475@param command - The file to execute and/or its arguments.76@returns fileOrArgument[]7778@example79```80import {execa, parseCommandString} from 'execa';8182const commandString = 'npm run task';83const commandArray = parseCommandString(commandString);84await execa`${commandArray}`;8586const [file, ...commandArguments] = commandArray;87await execa(file, commandArguments);88```89*/90export function parseCommandString(command: string): string[];
modified:index.d.ts+1 added-1 removed
9 unmodified lines
10export {ExecaError, ExecaSyncError} from './types/return/final-error.js';11export type {TemplateExpression} from './types/methods/template.js';12export {execa} from './types/methods/main-async.js';13export {execaSync} from './types/methods/main-sync.js';14export {execaCommand, execaCommandSync} from './types/methods/command.js';14export {execaCommand, execaCommandSync, parseCommandString} from './types/methods/command.js';15export {$} from './types/methods/script.js';16export {execaNode} from './types/methods/node.js';
modified:index.js+1 added
1 unmodified line
2import {mapCommandAsync, mapCommandSync} from './lib/methods/command.js';3import {mapNode} from './lib/methods/node.js';4import {mapScriptAsync, setScriptSync, deepScriptOptions} from './lib/methods/script.js';56export {parseCommandString} from './lib/methods/command.js';7export {ExecaError, ExecaSyncError} from './lib/return/final-error.js';89export const execa = createExeca(() => ({}));10export const execaSync = createExeca(() => ({isSync: true}));
4 unmodified lines