Allow `execa` return values in `$` template expressions (#528)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Aaron Casanova · committed by GitHub · parent a6d1141 · Browse files · 5 files·+191 added−8 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+191 added−8 removed
- tests:+104 added−5 removed
- other:+87 added−3 removed
Provenance
- Commit
58ea251- Tree
2d3d582- Author
Aaron Casanova <32409546+aaronccasanova@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
a6d1141
5 files changed+191 added−8 removed
modified:lib/command.js+38 added-2 removed
123456734 unmodified lines42434445464748495051525354555657585960616263646566676869707172737475767778798081823 unmodified lines86878889545590919293949596import {Buffer} from 'node:buffer';import {ChildProcess} from 'node:child_process';
const normalizeArgs = (file, args = []) => { if (!Array.isArray(args)) { return [file]; }34 unmodified lines
return tokens;};
const parseExpression = expression => { const typeOfExpression = typeof expression;
if (typeOfExpression === 'string') { return expression; }
if (typeOfExpression === 'number') { return String(expression); }
if ( typeOfExpression === 'object' && expression !== null && !(expression instanceof ChildProcess) && 'stdout' in expression ) { const typeOfStdout = typeof expression.stdout;
if (typeOfStdout === 'string') { return expression.stdout; }
if (Buffer.isBuffer(expression.stdout)) { return expression.stdout.toString(); }
throw new TypeError(`Unexpected "${typeOfStdout}" stdout in template expression`); }
throw new TypeError(`Unexpected "${typeOfExpression}" in template expression`);};
const parseTemplate = (template, index, templates, expressions) => { const templateString = template ?? templates.raw[index]; const templateTokens = templateString.split(SPACES_REGEXP).filter(Boolean);
3 unmodified lines
const expression = expressions[index];
return Array.isArray(expression) ? [...templateTokens, ...expression.map(String)] : [...templateTokens, String(expression)]; ? [...templateTokens, ...expression.map(expression => parseExpression(expression))] : [...templateTokens, parseExpression(expression)];};
export const parseTemplates = (templates, expressions) => templates.flatMap( (template, index) => parseTemplate(template, index, templates, expressions),);modified:test/command.js+104 added-5 removed
1+import {inspect} from 'node:util';2 import test from 'ava';3 import {execa, execaSync, execaCommand, execaCommandSync, $} from '../index.js';4 import {setFixtureDir} from './helpers/fixtures-dir.js';5 95 unmodified lines101 const {stdout} = await $`node test/fixtures/echo.js foo ${'bar'}`;102 t.is(stdout, 'foo\nbar');103 });104 105+test('$ allows number interpolation', async t => {106+ const {stdout} = await $`node test/fixtures/echo.js 1 ${2}`;107+ t.is(stdout, '1\n2');108+});109+110 test('$ allows array interpolation', async t => {111 const {stdout} = await $`node test/fixtures/echo.js ${['foo', 'bar']}`;112 t.is(stdout, 'foo\nbar');113 });114 115+test('$ allows execa return value interpolation', async t => {116+ const foo = await $`node test/fixtures/echo.js foo`;117+ const {stdout} = await $`node test/fixtures/echo.js ${foo} bar`;118+ t.is(stdout, 'foo\nbar');119+});120+121+test('$ allows execa return value array interpolation', async t => {122+ const foo = await $`node test/fixtures/echo.js foo`;123+ const {stdout} = await $`node test/fixtures/echo.js ${[foo, 'bar']}`;124+ t.is(stdout, 'foo\nbar');125+});126+127+test('$ allows execa return value buffer interpolation', async t => {128+ const foo = await $({encoding: null})`node test/fixtures/echo.js foo`;129+ const {stdout} = await $`node test/fixtures/echo.js ${foo} bar`;130+ t.is(stdout, 'foo\nbar');131+});132+133+test('$ allows execa return value buffer array interpolation', async t => {134+ const foo = await $({encoding: null})`node test/fixtures/echo.js foo`;135+ const {stdout} = await $`node test/fixtures/echo.js ${[foo, 'bar']}`;136+ t.is(stdout, 'foo\nbar');137+});138+139 test('$ ignores consecutive spaces', async t => {140 const {stdout} = await $`node test/fixtures/echo.js foo bar`;141 t.is(stdout, 'foo\nbar');142 });27 unmodified lines170 const {stdout} = await $`node test/fixtures/echo.js \u`;171 t.is(stdout, '\\u');172 });173 144-test('$ coerces all interpolated expressions to strings', async t => {145- const {stdout} = await $`node test/fixtures/echo.js ${0} ${undefined} ${null}`;146- t.is(stdout, '0\nundefined\nnull');147-});148-174 test('$ allows escaping spaces in commands with interpolation', async t => {175 const {stdout} = await $`${'command with space.js'} foo bar`;176 t.is(stdout, 'foo\nbar');177 });16 unmodified lines194 test('$.sync accepts options', t => {195 const {stdout} = $({stripFinalNewline: true}).sync`noop.js foo`;196 t.is(stdout, 'foo');197 });198+199+test('$.sync allows execa return value interpolation', t => {200+ const foo = $.sync`node test/fixtures/echo.js foo`;201+ const {stdout} = $.sync`node test/fixtures/echo.js ${foo} bar`;202+ t.is(stdout, 'foo\nbar');203+});204+205+test('$.sync allows execa return value array interpolation', t => {206+ const foo = $.sync`node test/fixtures/echo.js foo`;207+ const {stdout} = $.sync`node test/fixtures/echo.js ${[foo, 'bar']}`;208+ t.is(stdout, 'foo\nbar');209+});210+211+test('$.sync allows execa return value buffer interpolation', t => {212+ const foo = $({encoding: null}).sync`node test/fixtures/echo.js foo`;213+ const {stdout} = $.sync`node test/fixtures/echo.js ${foo} bar`;214+ t.is(stdout, 'foo\nbar');215+});216+217+test('$.sync allows execa return value buffer array interpolation', t => {218+ const foo = $({encoding: null}).sync`node test/fixtures/echo.js foo`;219+ const {stdout} = $.sync`node test/fixtures/echo.js ${[foo, 'bar']}`;220+ t.is(stdout, 'foo\nbar');221+});222+223+const invalidExpression = test.macro({224+ async exec(t, input, expected) {225+ await t.throwsAsync(226+ async () => $`node test/fixtures/echo.js ${input}`,227+ {instanceOf: TypeError, message: expected},228+ );229+230+ t.throws(231+ () => $.sync`node test/fixtures/echo.js ${input}`,232+ {instanceOf: TypeError, message: expected},233+ );234+ },235+ title(prettyInput, input, expected) {236+ return `$ APIs throw on invalid '${prettyInput ?? inspect(input)}' expression with '${expected}'`;237+ },238+});239+240+test(invalidExpression, undefined, 'Unexpected "undefined" in template expression');241+test(invalidExpression, [undefined], 'Unexpected "undefined" in template expression');242+243+test(invalidExpression, null, 'Unexpected "object" in template expression');244+test(invalidExpression, [null], 'Unexpected "object" in template expression');245+246+test(invalidExpression, true, 'Unexpected "boolean" in template expression');247+test(invalidExpression, [true], 'Unexpected "boolean" in template expression');248+249+test(invalidExpression, {}, 'Unexpected "object" in template expression');250+test(invalidExpression, [{}], 'Unexpected "object" in template expression');251+252+test(invalidExpression, {foo: 'bar'}, 'Unexpected "object" in template expression');253+test(invalidExpression, [{foo: 'bar'}], 'Unexpected "object" in template expression');254+255+test(invalidExpression, {stdout: undefined}, 'Unexpected "undefined" stdout in template expression');256+test(invalidExpression, [{stdout: undefined}], 'Unexpected "undefined" stdout in template expression');257+258+test(invalidExpression, {stdout: 1}, 'Unexpected "number" stdout in template expression');259+test(invalidExpression, [{stdout: 1}], 'Unexpected "number" stdout in template expression');260+261+test(invalidExpression, Promise.resolve(), 'Unexpected "object" in template expression');262+test(invalidExpression, [Promise.resolve()], 'Unexpected "object" in template expression');263+264+test(invalidExpression, Promise.resolve({stdout: 'foo'}), 'Unexpected "object" in template expression');265+test(invalidExpression, [Promise.resolve({stdout: 'foo'})], 'Unexpected "object" in template expression');266+267+test('$`noop.js`', invalidExpression, $`noop.js`, 'Unexpected "object" in template expression');268+test('[ $`noop.js` ]', invalidExpression, [$`noop.js`], 'Unexpected "object" in template expression');269+270+test('$({stdio: \'inherit\'}).sync`noop.js`', invalidExpression, $({stdio: 'inherit'}).sync`noop.js`, 'Unexpected "undefined" stdout in template expression');271+test('[ $({stdio: \'inherit\'}).sync`noop.js` ]', invalidExpression, [$({stdio: 'inherit'}).sync`noop.js`], 'Unexpected "undefined" stdout in template expression');modified:index.d.ts+30 added-1 removed
539 unmodified lines540 */541 export function execaCommand(command: string, options?: Options): ExecaChildProcess;542 export function execaCommand(command: string, options?: Options<null>): ExecaChildProcess<Buffer>;543 544-type TemplateExpression = string | number | Array<string | number>;544+type TemplateExpression =545+ | string546+ | number547+ | ExecaReturnValue<string | Buffer>548+ | ExecaSyncReturnValue<string | Buffer>549+ | Array<string | number | ExecaReturnValue<string | Buffer> | ExecaSyncReturnValue<string | Buffer>>;550 551 type Execa$<StdoutStderrType = string> = {552 /**553 Same as `execa()` except both file and arguments are specified in a single tagged template string. For example, `` $`echo unicorns` `` is the same as `execa('echo', ['unicorns'])`.1 unmodified line555 It's important to note that quotes, backslashes, and spaces are automatically escaped and have no special meaning unless the `shell` option is used. This escaping behavior also applies to interpolated expressions such as strings (`` $`echo ${'string'}` ``), arrays of strings (`` $`echo ${['array', 'of strings']}` ``), and so on.556 557 The `shell` option must be used if the `command` uses shell-specific features (for example, `&&` or `||`), as opposed to being a simple `file` followed by its `arguments`.558 559+ As a convenience, the result from previous `` $`command` `` or `` $.sync`command` `` calls can be used as template expressions in subsequent commands and `$`/`$.sync` will use the `stdout` value. See the example below `` with results from `$` or `$.sync` `` for more details.560+561 @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.562 563 @example <caption>Basic</caption>564 ```37 unmodified lines602 603 $({stdio: 'inherit'}).sync`echo rainbows`;604 //=> 'rainbows'605 ```606+607+ @example <caption>With results from `$` or `$.sync`</caption>608+ ```609+ import {$} from 'execa';610+611+ const unicorns = await $`echo unicorns`;612+613+ $({stdio: 'inherit'}).sync`echo ${unicorns} rainbows`;614+ //=> 'unicorns rainbows'615+ ```616 */617 (options: Options<undefined>): Execa$<StdoutStderrType>;618 (options: Options): Execa$;619 (options: Options<null>): Execa$<Buffer>;31 unmodified lines651 It's important to note that quotes, backslashes, and spaces are automatically escaped and have no special meaning unless the `shell` option is used. This escaping behavior also applies to interpolated expressions such as strings (`` $`echo ${'string'}` ``), arrays of strings (`` $`echo ${['array', 'of strings']}` ``), and so on.652 653 The `shell` option must be used if the `command` uses shell-specific features (for example, `&&` or `||`), as opposed to being a simple `file` followed by its `arguments`.654 655+As a convenience, the result from previous `` $`command` `` or `` $.sync`command` `` calls can be used as template expressions in subsequent commands and `$`/`$.sync` will use the `stdout` value. See the example below `` with results from `$` or `$.sync` `` for more details.656+657 @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.658 659 @example <caption>Basic</caption>660 ```37 unmodified lines698 699 $({stdio: 'inherit'}).sync`echo rainbows`;700 //=> 'rainbows'701 ```702+703+@example <caption>With results from `$` or `$.sync`</caption>704+```705+import {$} from 'execa';706+707+const unicorns = await $`echo unicorns`;708+709+$({stdio: 'inherit'}).sync`echo ${unicorns} rainbows`;710+//=> 'unicorns rainbows'711+```712 */713 export const $: Execa$;714 715 /**32 unmodified linesmodified:index.test-d.ts+6 added
263 unmodified lines264 expectType<ExecaReturnValue>(await $`unicorns ${['foo', 'bar']}`);265 expectType<ExecaSyncReturnValue>($.sync`unicorns ${['foo', 'bar']}`);266 expectType<ExecaReturnValue>(await $`unicorns ${[1, 2]}`);267 expectType<ExecaSyncReturnValue>($.sync`unicorns ${[1, 2]}`);268+expectType<ExecaReturnValue>(await $`unicorns ${await $`echo foo`}`);269+expectError<ExecaReturnValue>(await $`unicorns ${$`echo foo`}`);270+expectType<ExecaSyncReturnValue>($.sync`unicorns ${$.sync`echo foo`}`);271+expectType<ExecaReturnValue>(await $`unicorns ${[await $`echo foo`, 'bar']}`);272+expectError<ExecaReturnValue>(await $`unicorns ${[$`echo foo`, 'bar']}`);273+expectType<ExecaSyncReturnValue>($.sync`unicorns ${[$.sync`echo foo`, 'bar']}`);274 expectType<ExecaReturnValue>(await $`unicorns ${true.toString()}`);275 expectType<ExecaSyncReturnValue>($.sync`unicorns ${false.toString()}`);276 expectError<ExecaReturnValue>(await $`unicorns ${true}`);277 expectError<ExecaSyncReturnValue>($.sync`unicorns ${false}`);modified:readme.md+13 added
88 unmodified lines89 $({stdio: 'inherit'}).sync`echo rainbows`;90 //=> 'rainbows'91 ```92 93+#### With results from `$` or `$.sync`94+95+```js96+import {$} from 'execa';97+98+const unicorns = await $`echo unicorns`;99+100+$({stdio: 'inherit'}).sync`echo ${unicorns} rainbows`;101+//=> 'unicorns rainbows'102+```103+104 ### Pipe the child process stdout to the parent105 106 ```js107 import {execa} from 'execa';152 unmodified lines260 It's important to note that quotes, backslashes, and spaces are automatically escaped and have no special meaning unless the [`shell` option](#shell) is used. This escaping behavior also applies to interpolated expressions such as strings (`` $`echo ${'string'}` ``), arrays of strings (`` $`echo ${['array', 'of strings']}` ``), and so on.261 262 The [`shell` option](#shell) must be used if the `command` uses shell-specific features (for example, `&&` or `||`), as opposed to being a simple `file` followed by its `arguments`.263 264+As a convenience, the result from previous [`` $`command` ``](#command) or [`` $.sync`command` ``](#synccommand) calls can be used as template expressions in subsequent commands and `$`/`$.sync` will use the `stdout` value. See the example above [with results from `$` or `$.sync`](#with-results-from--or-sync) for more details.265+266 Returns a `Promise` that resolves or rejects with a [`childProcessResult`](#childProcessResult).267 268 ### $.sync\`command\`269 481 unmodified lines