Add `execa.command()` (#261)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by Sindre Sorhus · parent cf0e164 · Browse files · 5 files·+156 added−106 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+156 added−106 removed
- other:+156 added−106 removed
Provenance
- Commit
6853316- Tree
f2475c1- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
cf0e164
5 files changed+156 added−106 removed
modified:index.d.ts+31 added
366 unmodified lines367 sync(368 file: string,369 options?: execa.SyncOptions<null>370 ): execa.ExecaSyncReturnValue<Buffer>;371+372+ /**373+ Same as `execa()` except both file and arguments are specified in a single `command` string. For example, `execa('echo', ['unicorns'])` is the same as `execa.command('echo unicorns')`.374+375+ If the file or an argument contains spaces, they must be escaped with backslashes. This matters especially if `command` is not a constant but a variable, for example with `__dirname` or `process.cwd()`. Except for spaces, no escaping/quoting is needed.376+377+ @param command - The program/script to execute and its arguments.378+ @returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.379+380+ @example381+ ```382+ import execa from 'execa';383+384+ (async () => {385+ const {stdout} = await execa.command('echo unicorns');386+ console.log(stdout);387+ //=> 'unicorns'388+ })();389+ ```390+ */391+ command(command: string, options?: execa.Options): execa.ExecaChildProcess;392+ command(command: string, options?: execa.Options<null>): execa.ExecaChildProcess<Buffer>;393+394+ /**395+ Same as `execa.command()` but synchronous.396+397+ @param command - The program/script to execute and its arguments.398+ @returns A result `Object` with `stdout` and `stderr` properties.399+ */400+ commandSync(command: string, options?: execa.SyncOptions): execa.ExecaSyncReturnValue;401+ commandSync(command: string, options?: execa.SyncOptions<null>): execa.ExecaSyncReturnValue<Buffer>;402 };403 404 export = execa;modified:index.js+48 added-52 removed
15 unmodified lines16 const TEN_MEGABYTES = 1000 * 1000 * 10;17 18 const SPACES_REGEXP = / +/g;19 20-// Allow spaces to be escaped by a backslash if not meant as a delimiter21-function handleEscaping(tokens, token, index) {22- if (index === 0) {23- return [token];24- }25-26- const previousToken = tokens[tokens.length - 1];27-28- if (previousToken.endsWith('\\')) {29- return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`];30- }31-32- return [...tokens, token];33-}34-35-function parseCommand(command, args = []) {36- if (args.length !== 0) {37- throw new Error('Arguments cannot be inside `command` when also specified as an array of strings');38- }39-40- const [file, ...extraArgs] = command41- .trim()42- .split(SPACES_REGEXP)43- .reduce(handleEscaping, []);44- return [file, extraArgs];45-}46-47-function handleArgs(command, args, options = {}) {48- if (args && !Array.isArray(args)) {49- options = args;50- args = [];51- }52-53- if (!options.shell && command.includes(' ')) {54- [command, args] = parseCommand(command, args);55- }56-57- const parsed = crossSpawn._parse(command, args, options);58- command = parsed.command;20+function handleArgs(file, args, options = {}) {21+ const parsed = crossSpawn._parse(file, args, options);22+ file = parsed.command;23 args = parsed.args;24 options = parsed.options;25 26 options = {24 unmodified lines51 }52 53 options.stdio = stdio(options);54 91- if (process.platform === 'win32' && path.basename(command, '.exe') === 'cmd') {55+ if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {56 // #11657 args.unshift('/q');58 }59 96- return {command, args, options, parsed};60+ return {file, args, options, parsed};61 }62 63 function handleInput(spawned, input) {64 // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852135 unmodified lines200 201 return `failed with exit code ${exitCode} (${exitCodeName})`;202 }203 240-function joinCommand(command, args = []) {204+function joinCommand(file, args = []) {205 if (!Array.isArray(args)) {242- return command;206+ return file;207 }208 245- return [command, ...args].join(' ');209+ return [file, ...args].join(' ');210 }211 248-const execa = (command, args, options) => {249- const parsed = handleArgs(command, args, options);212+const execa = (file, args, options) => {213+ const parsed = handleArgs(file, args, options);214 const {encoding, buffer, maxBuffer} = parsed.options;251- const joinedCommand = joinCommand(command, args);215+ const joinedCommand = joinCommand(file, args);216 217 let spawned;218 try {255- spawned = childProcess.spawn(parsed.command, parsed.args, parsed.options);219+ spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);220 } catch (error) {221 return Promise.reject(error);222 }223 159 unmodified lines383 };384 385 module.exports = execa;386 423-module.exports.sync = (command, args, options) => {424- const parsed = handleArgs(command, args, options);425- const joinedCommand = joinCommand(command, args);387+module.exports.sync = (file, args, options) => {388+ const parsed = handleArgs(file, args, options);389+ const joinedCommand = joinCommand(file, args);390 391 if (isStream(parsed.options.input)) {392 throw new TypeError('The `input` option cannot be a stream in sync mode');393 }394 431- const result = childProcess.spawnSync(parsed.command, parsed.args, parsed.options);395+ const result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);396 result.stdout = handleOutput(parsed.options, result.stdout, result.error);397 result.stderr = handleOutput(parsed.options, result.stderr, result.error);398 399 if (result.error || result.status !== 0 || result.signal !== null) {24 unmodified lines424 isCanceled: false,425 killed: false426 };427 };428+429+// Allow spaces to be escaped by a backslash if not meant as a delimiter430+function handleEscaping(tokens, token, index) {431+ if (index === 0) {432+ return [token];433+ }434+435+ const previousToken = tokens[tokens.length - 1];436+437+ if (previousToken.endsWith('\\')) {438+ return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`];439+ }440+441+ return [...tokens, token];442+}443+444+function parseCommand(command) {445+ return command446+ .trim()447+ .split(SPACES_REGEXP)448+ .reduce(handleEscaping, []);449+}450+451+module.exports.command = (command, options) => {452+ const [file, ...args] = parseCommand(command);453+ return execa(file, args, options);454+};455+456+module.exports.commandSync = (command, options) => {457+ const [file, ...args] = parseCommand(command);458+ return execa.sync(file, args, options);459+};modified:index.test-d.ts+13 added
144 unmodified linesExpand all145146147148149150151152153154155156157158159160161144 unmodified linesExpand all);expectType<ExecaSyncReturnValue<Buffer>>( execa.sync('unicorns', ['foo'], {encoding: null}));
expectType<ExecaChildProcess<string>>(execa.command('unicorns'));expectType<ExecaReturnValue<string>>(await execa.command('unicorns'));expectType<ExecaReturnValue<string>>(await execa.command('unicorns', {encoding: 'utf8'}));expectType<ExecaReturnValue<Buffer>>(await execa.command('unicorns', {encoding: null}));expectType<ExecaReturnValue<string>>(await execa.command('unicorns foo', {encoding: 'utf8'}));expectType<ExecaReturnValue<Buffer>>(await execa.command('unicorns foo', {encoding: null}));
expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns'));expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns', {encoding: 'utf8'}));expectType<ExecaSyncReturnValue<Buffer>>(execa.commandSync('unicorns', {encoding: null}));expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns foo', {encoding: 'utf8'}));expectType<ExecaSyncReturnValue<Buffer>>(execa.commandSync('unicorns foo', {encoding: null}));modified:readme.md+19 added-13 removed
14 unmodified lines15 - Higher max buffer. 10 MB instead of 200 KB.16 - [Executes locally installed binaries by name.](#preferlocal)17 - [Cleans up spawned processes when the parent process dies.](#cleanup)18 - [Get interleaved output](#all) from `stdout` and `stderr` similar to what is printed on the terminal. [*(Async only)*](#execasyncfile-arguments-options)19-- [Can specify command and arguments as a single string without a shell](#execafile-arguments-options)19+- [Can specify command and arguments as a single string without a shell](#execacommandcommand-options)20 - More descriptive errors.21 22 23 ## Install26 unmodified lines50 51 52 // Catching an error53 try {54- await execa('wrong command');54+ await execa('wrong', ['command']);55 } catch (error) {56 console.log(error);57 /*58 {30 unmodified lines89 })();90 91 // Catching an error with a sync method92 try {93- execa.sync('wrong command');93+ execa.sync('wrong', ['command']);94 } catch (error) {95 console.log(error);96 /*97 {18 unmodified lines116 117 118 ## API119 120-### execa(file, [arguments], [options])121-### execa(command, [options])120+### execa(file, arguments, [options])121 122 Execute a file. Think of this as a mix of [`child_process.execFile()`](https://nodejs.org/api/child_process.html#child_process_child_process_execfile_file_args_options_callback) and [`child_process.spawn()`](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options).123 125-Arguments can be specified in either:126- - `arguments`: `execa('echo', ['unicorns'])`.127- - `command`: `execa('echo unicorns')`.124+No escaping/quoting is needed.125 129-Arguments should not be escaped nor quoted, except inside `command` where spaces can be escaped with a backslash.130-126 Unless the [`shell`](#shell) option is used, no shell interpreter (Bash, `cmd.exe`, etc.) is used, so shell features such as variables substitution (`echo $PATH`) are not allowed.127 128 Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) which:129 - is also a `Promise` resolving or rejecting with a [`childProcessResult`](#childProcessResult).7 unmodified lines137 138 Stream combining/interleaving [`stdout`](https://nodejs.org/api/child_process.html#child_process_subprocess_stdout) and [`stderr`](https://nodejs.org/api/child_process.html#child_process_subprocess_stderr).139 140 ### execa.sync(file, [arguments], [options])146-### execa.sync(command, [options])141 142 Execute a file synchronously.143 144 Returns or throws a [`childProcessResult`](#childProcessResult).145 146+### execa.command(command, [options])147+148+Same as [`execa()`](#execafile-arguments-options) except both file and arguments are specified in a single `command` string. For example, `execa('echo', ['unicorns'])` is the same as `execa.command('echo unicorns')`.149+150+If the file or an argument contains spaces, they must be escaped with backslashes. This matters especially if `command` is not a constant but a variable, for example with `__dirname` or `process.cwd()`. Except for spaces, no escaping/quoting is needed.151+152+### execa.commandSync(command, [options])153+154+Same as [`execa.command()`](#execacommand-command-options) but synchronous.155+156+Returns or throws a [`childProcessResult`](#childProcessResult).157+158 ### childProcessResult159 160 Type: `object`161 170 unmodified lines332 #### argv0333 334 Type: `string`335 330-Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified.336+Explicitly set the value of `argv[0]` sent to the child process. This will be set to `file` if not specified.337 338 #### stdio339 340 Type: `string | string[]`<br>23 unmodified lines364 365 Type: `boolean | string`<br>366 Default: `false`367 362-If `true`, runs `command` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.368+If `true`, runs `file` inside of a shell. Uses `/bin/sh` on UNIX and `cmd.exe` on Windows. A different shell can be specified as a string. The shell should understand the `-c` switch on UNIX or `/d /s /c` on Windows.369 370 We recommend against using this option since it is:371 - not cross-platform, encouraging shell-specific syntax.372 - slower, because of the additional shell interpretation.67 unmodified linesmodified:test.js+45 added-41 removed
95 unmodified lines96 await execa('fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});97 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');98 });99 100-test('allow string arguments', async t => {101- const {stdout} = await execa('node fixtures/echo foo bar');102- t.is(stdout, 'foo\nbar');103-});104-105-test('allow string arguments in synchronous mode', t => {106- const {stdout} = execa.sync('node fixtures/echo foo bar');107- t.is(stdout, 'foo\nbar');108-});109-110-test('forbid string arguments together with array arguments', t => {111- t.throws(() => {112- execa('node fixtures/echo foo bar', ['foo', 'bar']);113- }, /Arguments cannot be inside/);114-});115-116-test('ignore consecutive spaces in string arguments', async t => {117- const {stdout} = await execa('node fixtures/echo foo bar');118- t.is(stdout, 'foo\nbar');119-});120-121-test('escape other whitespaces in string arguments', async t => {122- const {stdout} = await execa('node fixtures/echo foo\tbar');123- t.is(stdout, 'foo\tbar');124-});125-126-test('allow escaping spaces in commands', async t => {127- const {stdout} = await execa('./fixtures/command\\ with\\ space foo bar');128- t.is(stdout, 'foo\nbar');129-});130-131-test('allow escaping spaces in string arguments', async t => {132- const {stdout} = await execa('node fixtures/echo foo\\ bar');133- t.is(stdout, 'foo bar');134-});135-136-test('trim string arguments', async t => {137- const {stdout} = await execa(' node fixtures/echo foo bar ');138- t.is(stdout, 'foo\nbar');139-});140-100 test('execa.sync()', t => {101 const {stdout} = execa.sync('noop', ['foo']);102 t.is(stdout, 'foo');103 });565 unmodified lines669 subprocess.kill();670 const {isCanceled} = await t.throwsAsync(subprocess);671 t.false(isCanceled);672 });673+674+test('allow commands with spaces and no array arguments', async t => {675+ const {stdout} = await execa('./fixtures/command with space');676+ t.is(stdout, '');677+});678+679+test('allow commands with spaces and array arguments', async t => {680+ const {stdout} = await execa('./fixtures/command with space', ['foo', 'bar']);681+ t.is(stdout, 'foo\nbar');682+});683+684+test('execa.command()', async t => {685+ const {stdout} = await execa.command('node fixtures/echo foo bar');686+ t.is(stdout, 'foo\nbar');687+});688+689+test('execa.command() ignores consecutive spaces', async t => {690+ const {stdout} = await execa.command('node fixtures/echo foo bar');691+ t.is(stdout, 'foo\nbar');692+});693+694+test('execa.command() allows escaping spaces in commands', async t => {695+ const {stdout} = await execa.command('./fixtures/command\\ with\\ space foo bar');696+ t.is(stdout, 'foo\nbar');697+});698+699+test('execa.command() allows escaping spaces in arguments', async t => {700+ const {stdout} = await execa.command('node fixtures/echo foo\\ bar');701+ t.is(stdout, 'foo bar');702+});703+704+test('execa.command() escapes other whitespaces', async t => {705+ const {stdout} = await execa.command('node fixtures/echo foo\tbar');706+ t.is(stdout, 'foo\tbar');707+});708+709+test('execa.command() trims', async t => {710+ const {stdout} = await execa.command(' node fixtures/echo foo bar ');711+ t.is(stdout, 'foo\nbar');712+});713+714+test('execa.command.sync()', t => {715+ const {stdout} = execa.commandSync('node fixtures/echo foo bar');716+ t.is(stdout, 'foo\nbar');717+});