Support single string input without using the `shell` option (#182)
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 9e5b976 · Browse files · 4 files·+91 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+91 added−3 removed
- other:+91 added−3 removed
Provenance
- Commit
075faf3- Tree
d8a4769- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
9e5b976
4 files changed+91 added−3 removed
added:fixtures/echo+3 added
1+#!/usr/bin/env node2+'use strict';3+console.log(process.argv.slice(2).join('\n'))modified:index.js+39 added-1 removed
13 unmodified lines14 const stdio = require('./lib/stdio');15 16 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[index - 1];27+28+ if (!previousToken.endsWith('\\')) {29+ return [...tokens, token];30+ }31+32+ return [...tokens.slice(0, index - 1), `${previousToken.slice(0, -1)} ${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+18-function handleArgs(command, args, options) {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;59 args = parsed.args;60 options = parsed.options;438 unmodified linesmodified:readme.md+15 added-2 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 - [Adds an `.all` property](#execafile-arguments-options) with interleaved output from `stdout` and `stderr`, similar to what the terminal sees. [*(Async only)*](#execasyncfile-arguments-options)19+- [Can specify command and arguments as a single string without a shell](#execafile-arguments-options)20 21 22 ## Install23 91 unmodified lines115 116 ## API117 118 ### execa(file, [arguments], [options])119+### execa(command, [options])120 121 Execute a file.122 123+Arguments can be specified in either:124+ - `arguments`: `execa('echo', ['unicorns'])`.125+ - `command`: `execa('echo unicorns')`.126+127+Arguments should not be escaped nor quoted. Exception: inside `command`, spaces can be escaped with a backslash.128+129 Think of this as a mix of `child_process.execFile` and `child_process.spawn`.130 131+As opposed to [`execa.shell()`](#execashellcommand-options), no shell interpreter (Bash, `cmd.exe`, etc.) is used, so shell features such as variables substitution (`echo $PATH`) are not allowed.132+133 Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess) which is enhanced to be a `Promise`.134 135 It exposes an additional `.all` stream, with `stdout` and `stderr` interleaved.136 1 unmodified line138 139 The promise result is an `Object` with `stdout`, `stderr` and `all` properties.140 141 ### execa.stdout(file, [arguments], [options])142+### execa.stdout(command, [options])143 144 Same as `execa()`, but returns only `stdout`.145 146 ### execa.stderr(file, [arguments], [options])147+### execa.stderr(command, [options])148 149 Same as `execa()`, but returns only `stderr`.150 151 ### execa.shell(command, [options])152 141-Execute a command through the system shell. Prefer `execa()` whenever possible, as it's both faster and safer.153+Execute a command through the system shell. Prefer `execa()` whenever possible, as it's faster, safer and more cross-platform.154 155 Returns a [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess).156 157 The `child_process` instance is enhanced to also be promise for a result object with `stdout` and `stderr` properties.158 159 ### execa.sync(file, [arguments], [options])160+### execa.sync(command, [options])161 162 Execute a file synchronously.163 164 Returns the same result object as [`child_process.spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options).1 unmodified line166 It does not have the `.all` property that `execa()` has because the [underlying synchronous implementation](https://nodejs.org/api/child_process.html#child_process_child_process_execfilesync_file_args_options) only returns `stdout` and `stderr` at the end of the execution, so they cannot be interleaved.167 168 This method throws an `Error` if the command fails.169 157-### execa.shellSync(file, [options])170+### execa.shellSync(command, [options])171 172 Execute a command synchronously through the system shell.173 174 Returns the same result object as [`child_process.spawnSync`](https://nodejs.org/api/child_process.html#child_process_child_process_spawnsync_command_args_options).195 unmodified linesmodified:test.js+34 added
99 unmodified lines100 await execa('fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});101 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');102 });103 104+test('allow string arguments', async t => {105+ const {stdout} = await execa('node fixtures/echo foo bar');106+ t.is(stdout, 'foo\nbar');107+});108+109+test('allow string arguments in synchronous mode', t => {110+ const {stdout} = execa.sync('node fixtures/echo foo bar');111+ t.is(stdout, 'foo\nbar');112+});113+114+test('forbid string arguments together with array arguments', t => {115+ t.throws(() => execa('node fixtures/echo foo bar', ['foo', 'bar']), /Arguments cannot be inside/);116+});117+118+test('ignore consecutive spaces in string arguments', async t => {119+ const {stdout} = await execa('node fixtures/echo foo bar');120+ t.is(stdout, 'foo\nbar');121+});122+123+test('escape other whitespaces in string arguments', async t => {124+ const {stdout} = await execa('node fixtures/echo foo\tbar');125+ t.is(stdout, 'foo\tbar');126+});127+128+test('allow escaping spaces in string arguments', async t => {129+ const {stdout} = await execa('node fixtures/echo foo\\ bar');130+ t.is(stdout, 'foo bar');131+});132+133+test('trim string arguments', async t => {134+ const {stdout} = await execa(' node fixtures/echo foo bar ');135+ t.is(stdout, 'foo\nbar');136+});137+138 test('execa.shell()', async t => {139 const {stdout} = await execa.shell('node fixtures/noop foo');140 t.is(stdout, 'foo');141 });553 unmodified lines