Skip to content
Myr

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

5 files+156 added−106 removed

modified:index.d.ts+31 added
366 unmodified lines
367 sync(368 file: string,369 options?: execa.SyncOptions<null>370 ): execa.ExecaSyncReturnValue<Buffer>;371372 /**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')`.374375 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.376377 @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.379380 @example381 ```382 import execa from 'execa';383384 (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>;393394 /**395 Same as `execa.command()` but synchronous.396397 @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};403404export = execa;
modified:index.js+48 added-52 removed
15 unmodified lines
16const TEN_MEGABYTES = 1000 * 1000 * 10;1718const SPACES_REGEXP = / +/g;1920// Allow spaces to be escaped by a backslash if not meant as a delimiter21function handleEscaping(tokens, token, index) {22 if (index === 0) {23 return [token];24 }2526 const previousToken = tokens[tokens.length - 1];2728 if (previousToken.endsWith('\\')) {29 return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`];30 }3132 return [...tokens, token];33}3435function 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 }3940 const [file, ...extraArgs] = command41 .trim()42 .split(SPACES_REGEXP)43 .reduce(handleEscaping, []);44 return [file, extraArgs];45}4647function handleArgs(command, args, options = {}) {48 if (args && !Array.isArray(args)) {49 options = args;50 args = [];51 }5253 if (!options.shell && command.includes(' ')) {54 [command, args] = parseCommand(command, args);55 }5657 const parsed = crossSpawn._parse(command, args, options);58 command = parsed.command;20function handleArgs(file, args, options = {}) {21 const parsed = crossSpawn._parse(file, args, options);22 file = parsed.command;23 args = parsed.args;24 options = parsed.options;2526 options = {
24 unmodified lines
51 }5253 options.stdio = stdio(options);5491 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 }5996 return {command, args, options, parsed};60 return {file, args, options, parsed};61}6263function handleInput(spawned, input) {64 // Checking for stdin is workaround for https://github.com/nodejs/node/issues/26852
135 unmodified lines
200201 return `failed with exit code ${exitCode} (${exitCodeName})`;202}203240function joinCommand(command, args = []) {204function joinCommand(file, args = []) {205 if (!Array.isArray(args)) {242 return command;206 return file;207 }208245 return [command, ...args].join(' ');209 return [file, ...args].join(' ');210}211248const execa = (command, args, options) => {249 const parsed = handleArgs(command, args, options);212const 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);216217 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 lines
383};384385module.exports = execa;386423module.exports.sync = (command, args, options) => {424 const parsed = handleArgs(command, args, options);425 const joinedCommand = joinCommand(command, args);387module.exports.sync = (file, args, options) => {388 const parsed = handleArgs(file, args, options);389 const joinedCommand = joinCommand(file, args);390391 if (isStream(parsed.options.input)) {392 throw new TypeError('The `input` option cannot be a stream in sync mode');393 }394431 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);398399 if (result.error || result.status !== 0 || result.signal !== null) {
24 unmodified lines
424 isCanceled: false,425 killed: false426 };427};428429// Allow spaces to be escaped by a backslash if not meant as a delimiter430function handleEscaping(tokens, token, index) {431 if (index === 0) {432 return [token];433 }434435 const previousToken = tokens[tokens.length - 1];436437 if (previousToken.endsWith('\\')) {438 return [...tokens.slice(0, -1), `${previousToken.slice(0, -1)} ${token}`];439 }440441 return [...tokens, token];442}443444function parseCommand(command) {445 return command446 .trim()447 .split(SPACES_REGEXP)448 .reduce(handleEscaping, []);449}450451module.exports.command = (command, options) => {452 const [file, ...args] = parseCommand(command);453 return execa(file, args, options);454};455456module.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
modified:readme.md+19 added-13 removed
14 unmodified lines
15- 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.212223## Install
26 unmodified lines
505152 // 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 lines
89})();9091// Catching an error with a sync method92try {93 execa.sync('wrong command');93 execa.sync('wrong', ['command']);94} catch (error) {95 console.log(error);96 /*97 {
18 unmodified lines
116117118## API119120### execa(file, [arguments], [options])121### execa(command, [options])120### execa(file, arguments, [options])121122Execute 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).123125Arguments can be specified in either:126 - `arguments`: `execa('echo', ['unicorns'])`.127 - `command`: `execa('echo unicorns')`.124No escaping/quoting is needed.125129Arguments should not be escaped nor quoted, except inside `command` where spaces can be escaped with a backslash.130126Unless 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.127128Returns 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 lines
137138Stream 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).139140### execa.sync(file, [arguments], [options])146### execa.sync(command, [options])141142Execute a file synchronously.143144Returns or throws a [`childProcessResult`](#childProcessResult).145146### execa.command(command, [options])147148Same 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')`.149150If 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.151152### execa.commandSync(command, [options])153154Same as [`execa.command()`](#execacommand-command-options) but synchronous.155156Returns or throws a [`childProcessResult`](#childProcessResult).157158### childProcessResult159160Type: `object`161
170 unmodified lines
332#### argv0333334Type: `string`335330Explicitly set the value of `argv[0]` sent to the child process. This will be set to `command` or `file` if not specified.336Explicitly set the value of `argv[0]` sent to the child process. This will be set to `file` if not specified.337338#### stdio339340Type: `string | string[]`<br>
23 unmodified lines
364365Type: `boolean | string`<br>366Default: `false`367362If `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.368If `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.369370We 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 lines
modified:test.js+45 added-41 removed
95 unmodified lines
96 await execa('fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});97 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');98});99100test('allow string arguments', async t => {101 const {stdout} = await execa('node fixtures/echo foo bar');102 t.is(stdout, 'foo\nbar');103});104105test('allow string arguments in synchronous mode', t => {106 const {stdout} = execa.sync('node fixtures/echo foo bar');107 t.is(stdout, 'foo\nbar');108});109110test('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});115116test('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});120121test('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});125126test('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});130131test('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});135136test('trim string arguments', async t => {137 const {stdout} = await execa(' node fixtures/echo foo bar ');138 t.is(stdout, 'foo\nbar');139});140100test('execa.sync()', t => {101 const {stdout} = execa.sync('noop', ['foo']);102 t.is(stdout, 'foo');103});
565 unmodified lines
669 subprocess.kill();670 const {isCanceled} = await t.throwsAsync(subprocess);671 t.false(isCanceled);672});673674test('allow commands with spaces and no array arguments', async t => {675 const {stdout} = await execa('./fixtures/command with space');676 t.is(stdout, '');677});678679test('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});683684test('execa.command()', async t => {685 const {stdout} = await execa.command('node fixtures/echo foo bar');686 t.is(stdout, 'foo\nbar');687});688689test('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});693694test('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});698699test('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});703704test('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});708709test('execa.command() trims', async t => {710 const {stdout} = await execa.command(' node fixtures/echo foo bar ');711 t.is(stdout, 'foo\nbar');712});713714test('execa.command.sync()', t => {715 const {stdout} = execa.commandSync('node fixtures/echo foo bar');716 t.is(stdout, 'foo\nbar');717});