Add `$` tagged templates API (#510)
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 6bb4a6d · Browse files · 6 files·+407 added−18 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: ehmicky <ehmicky@users.noreply.github.com>
- Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
Diff stats
6 files+407 added−18 removed
- tests:+86 added−1 removed
- other:+321 added−17 removed
Provenance
- Commit
eae327c- Tree
be60f45- Author
Aaron Casanova <32409546+aaronccasanova@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
6bb4a6d
6 files changed+407 added−18 removed
modified:lib/command.js+19 added
37 unmodified lines383940414243444546474849505152535455565758596037 unmodified lines }
return tokens;};
const parseTemplate = (template, index, templates, expressions) => { const templateString = template ?? templates.raw[index]; const templateTokens = templateString.split(SPACES_REGEXP).filter(Boolean);
if (index === expressions.length) { return templateTokens; }
const expression = expressions[index];
return Array.isArray(expression) ? [...templateTokens, ...expression.map(String)] : [...templateTokens, String(expression)];};
export const parseTemplates = (templates, expressions) => templates.flatMap( (template, index) => parseTemplate(template, index, templates, expressions),);modified:test/command.js+86 added-1 removed
122345677 unmodified lines84858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172import test from 'ava';import {execa, execaSync, execaCommand, execaCommandSync} from '../index.js';import {execa, execaSync, execaCommand, execaCommandSync, $} from '../index.js';import {setFixtureDir} from './helpers/fixtures-dir.js';
setFixtureDir();
77 unmodified linestest('execaCommandSync()', t => { const {stdout} = execaCommandSync('node test/fixtures/echo.js foo bar'); t.is(stdout, 'foo\nbar');});
test('$', async t => { const {stdout} = await $`node test/fixtures/echo.js foo bar`; t.is(stdout, 'foo\nbar');});
test('$ accepts options', async t => { const {stdout} = await $({stripFinalNewline: true})`noop.js foo`; t.is(stdout, 'foo');});
test('$ allows string interpolation', async t => { const {stdout} = await $`node test/fixtures/echo.js foo ${'bar'}`; t.is(stdout, 'foo\nbar');});
test('$ allows array interpolation', async t => { const {stdout} = await $`node test/fixtures/echo.js ${['foo', 'bar']}`; t.is(stdout, 'foo\nbar');});
test('$ ignores consecutive spaces', async t => { const {stdout} = await $`node test/fixtures/echo.js foo bar`; t.is(stdout, 'foo\nbar');});
test('$ allows escaping spaces with interpolation', async t => { const {stdout} = await $`node test/fixtures/echo.js ${'foo bar'}`; t.is(stdout, 'foo bar');});
test('$ disallows escaping spaces with backslashes', async t => { const {stdout} = await $`node test/fixtures/echo.js foo\\ bar`; t.is(stdout, 'foo\\\nbar');});
test('$ allows space escaped values in array interpolation', async t => { const {stdout} = await $`node test/fixtures/echo.js ${['foo', 'bar baz']}`; t.is(stdout, 'foo\nbar baz');});
test('$ passes newline escape sequence as one argument', async t => { const {stdout} = await $`node test/fixtures/echo.js \n`; t.is(stdout, '\n');});
test('$ passes newline escape sequence in interpolation as one argument', async t => { const {stdout} = await $`node test/fixtures/echo.js ${'\n'}`; t.is(stdout, '\n');});
test('$ handles invalid escape sequence', async t => { const {stdout} = await $`node test/fixtures/echo.js \u`; t.is(stdout, '\\u');});
test('$ coerces all interpolated expressions to strings', async t => { const {stdout} = await $`node test/fixtures/echo.js ${0} ${undefined} ${null}`; t.is(stdout, '0\nundefined\nnull');});
test('$ allows escaping spaces in commands with interpolation', async t => { const {stdout} = await $`${'command with space.js'} foo bar`; t.is(stdout, 'foo\nbar');});
test('$ escapes other whitespaces', async t => { const {stdout} = await $`node test/fixtures/echo.js foo\tbar`; t.is(stdout, 'foo\tbar');});
test('$ trims', async t => { const {stdout} = await $` node test/fixtures/echo.js foo bar `; t.is(stdout, 'foo\nbar');});
test('$.sync', t => { const {stdout} = $.sync`node test/fixtures/echo.js foo bar`; t.is(stdout, 'foo\nbar');});
test('$.sync accepts options', t => { const {stdout} = $({stripFinalNewline: true}).sync`noop.js foo`; t.is(stdout, 'foo');});modified:index.d.ts+158 added-16 removed
335 unmodified lines336 */337 signalDescription?: string;338 };339 340-export type ExecaSyncReturnValue<StdoutErrorType = string> = {341-} & ExecaReturnBase<StdoutErrorType>;340+export type ExecaSyncReturnValue<StdoutStderrType = string> = {341+} & ExecaReturnBase<StdoutStderrType>;342 343 /**344 Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.345 3 unmodified lines349 - timing out350 - being canceled351 - there's not enough memory or there are already too many child processes352 */353-export type ExecaReturnValue<StdoutErrorType = string> = {353+export type ExecaReturnValue<StdoutStderrType = string> = {354 /**355 The output of the process with `stdout` and `stderr` interleaved.356 357 This is `undefined` if either:358 - the `all` option is `false` (default value)359 - `execaSync()` was used360 */361- all?: StdoutErrorType;361+ all?: StdoutStderrType;362 363 /**364 Whether the process was canceled.365 366 You can cancel the spawned process using the [`signal`](https://github.com/sindresorhus/execa#signal-1) option.367 */368 isCanceled: boolean;369-} & ExecaSyncReturnValue<StdoutErrorType>;369+} & ExecaSyncReturnValue<StdoutStderrType>;370 371-export type ExecaSyncError<StdoutErrorType = string> = {371+export type ExecaSyncError<StdoutStderrType = string> = {372 /**373 Error message when the child process failed to run. In addition to the underlying error message, it also contains some information related to why the child process errored.374 375 The child process stderr then stdout are appended to the end, separated with newlines and not interleaved.10 unmodified lines386 387 This is `undefined` unless the child process exited due to an `error` event or a timeout.388 */389 originalMessage?: string;390-} & Error & ExecaReturnBase<StdoutErrorType>;390+} & Error & ExecaReturnBase<StdoutStderrType>;391 392-export type ExecaError<StdoutErrorType = string> = {392+export type ExecaError<StdoutStderrType = string> = {393 /**394 The output of the process with `stdout` and `stderr` interleaved.395 396 This is `undefined` if either:397 - the `all` option is `false` (default value)398 - `execaSync()` was used399 */400- all?: StdoutErrorType;400+ all?: StdoutStderrType;401 402 /**403 Whether the process was canceled.404 */405 isCanceled: boolean;406-} & ExecaSyncError<StdoutErrorType>;406+} & ExecaSyncError<StdoutStderrType>;407 408 export type KillOptions = {409 /**410 Milliseconds to wait for the child process to terminate before sending `SIGKILL`.4 unmodified lines415 */416 forceKillAfterTimeout?: number | false;417 };418 419-export type ExecaChildPromise<StdoutErrorType> = {419+export type ExecaChildPromise<StdoutStderrType> = {420 /**421 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).422 423 This is `undefined` if either:2 unmodified lines426 */427 all?: ReadableStream;428 429 catch<ResultType = never>(430- onRejected?: (reason: ExecaError<StdoutErrorType>) => ResultType | PromiseLike<ResultType>431- ): Promise<ExecaReturnValue<StdoutErrorType> | ResultType>;430+ onRejected?: (reason: ExecaError<StdoutStderrType>) => ResultType | PromiseLike<ResultType>431+ ): Promise<ExecaReturnValue<StdoutStderrType> | ResultType>;432 433 /**434 Same as the original [`child_process#kill()`](https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal), except if `signal` is `SIGTERM` (the default value) and the child process is not terminated after 5 seconds, force it by sending `SIGKILL`.435 */4 unmodified lines440 */441 cancel(): void;442 };443 444-export type ExecaChildProcess<StdoutErrorType = string> = ChildProcess &445-ExecaChildPromise<StdoutErrorType> &446-Promise<ExecaReturnValue<StdoutErrorType>>;444+export type ExecaChildProcess<StdoutStderrType = string> = ChildProcess &445+ExecaChildPromise<StdoutStderrType> &446+Promise<ExecaReturnValue<StdoutStderrType>>;447 448 /**449 Execute a file.450 89 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>;545+546+type Execa$<StdoutStderrType = string> = {547+ /**548+ 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'])`.549+550+ 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.551+552+ 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`.553+554+ @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.555+556+ @example <caption>Basic</caption>557+ ```558+ import {$} from 'execa';559+560+ const {stdout} = await $`echo unicorns`;561+ // const {stdout} = await $`echo ${'unicorns'}`;562+ // const {stdout} = await $`echo ${['unicorns', 'rainbows']}`;563+564+ console.log(stdout);565+ //=> 'unicorns'566+ ```567+568+ @example <caption>With options</caption>569+ ```570+ import {$} from 'execa';571+572+ await $({stdio: 'inherit'})`echo unicorns`;573+ //=> 'unicorns'574+ ```575+576+ @example <caption>With pre-defined options</caption>577+ ```578+ import {$} from 'execa';579+580+ const $$ = $({stdio: 'inherit'});581+ await $$`echo unicorns`;582+ //=> 'unicorns'583+ await $$({shell: true})`echo unicorns && echo rainbows`;584+ //=> 'unicorns'585+ //=> 'rainbows'586+ ```587+588+ @example <caption>Synchronous</caption>589+ ```590+ import {$} from 'execa';591+592+ const {stdout} = $.sync`echo unicorns`;593+ console.log(stdout);594+ //=> 'unicorns'595+596+ $({stdio: 'inherit'}).sync`echo rainbows`;597+ //=> 'rainbows'598+ ```599+ */600+ (options: Options<undefined>): Execa$<StdoutStderrType>;601+ (options: Options): Execa$;602+ (options: Options<null>): Execa$<Buffer>;603+ (604+ templates: TemplateStringsArray,605+ ...expressions: TemplateExpression[]606+ ): ExecaChildProcess<StdoutStderrType>;607+608+ /**609+ Same as `$` but synchronous like `execaSync()`.610+611+ @returns The stdout and stderr output.612+613+ @example614+ ```615+ import {$} from 'execa';616+617+ const {stdout} = $.sync`echo unicorns`;618+ console.log(stdout);619+ //=> 'unicorns'620+621+ $({stdio: 'inherit'}).sync`echo rainbows`;622+ //=> 'rainbows'623+ ```624+ */625+ sync(626+ templates: TemplateStringsArray,627+ ...expressions: TemplateExpression[]628+ ): ExecaSyncReturnValue<StdoutStderrType>;629+};630+631 /**632+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'])`.633+634+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.635+636+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`.637+638+@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.639+640+@example <caption>Basic</caption>641+```642+import {$} from 'execa';643+644+const {stdout} = await $`echo unicorns`;645+// const {stdout} = await $`echo ${'unicorns'}`;646+// const {stdout} = await $`echo ${['unicorns', 'rainbows']}`;647+648+console.log(stdout);649+//=> 'unicorns'650+```651+652+@example <caption>With options</caption>653+```654+import {$} from 'execa';655+656+await $({stdio: 'inherit'})`echo unicorns`;657+//=> 'unicorns'658+```659+660+@example <caption>With pre-defined options</caption>661+```662+import {$} from 'execa';663+664+const $$ = $({stdio: 'inherit'});665+await $$`echo unicorns`;666+//=> 'unicorns'667+await $$({shell: true})`echo unicorns && echo rainbows`;668+//=> 'unicorns'669+//=> 'rainbows'670+```671+672+@example <caption>Synchronous</caption>673+```674+import {$} from 'execa';675+676+const {stdout} = $.sync`echo unicorns`;677+console.log(stdout);678+//=> 'unicorns'679+680+$({stdio: 'inherit'}).sync`echo rainbows`;681+//=> 'rainbows'682+```683+*/684+export const $: Execa$;685+686+/**687 Same as `execaCommand()` but synchronous.688 689 @param command - The program/script to execute and its arguments.690 @returns A result `Object` with `stdout` and `stderr` properties.28 unmodified linesmodified:index.js+21 added-1 removed
9 unmodified lines10 import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js';11 import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';12 import {handleInput, getSpawnedResult, makeAllStream, validateInputSync} from './lib/stream.js';13 import {mergePromise, getSpawnedPromise} from './lib/promise.js';14-import {joinCommand, parseCommand, getEscapedCommand} from './lib/command.js';14+import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';15 16 const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;17 18 const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {204 unmodified lines223 killed: false,224 };225 }226 227+function create$(options) {228+ function $(templatesOrOptions, ...expressions) {229+ if (Array.isArray(templatesOrOptions)) {230+ const [file, ...args] = parseTemplates(templatesOrOptions, expressions);231+ return execa(file, args, options);232+ }233+234+ return create$({...options, ...templatesOrOptions});235+ }236+237+ $.sync = (templates, ...expressions) => {238+ const [file, ...args] = parseTemplates(templates, expressions);239+ return execaSync(file, args, options);240+ };241+242+ return $;243+}244+245+export const $ = create$();246+247 export function execaCommand(command, options) {248 const [file, ...args] = parseCommand(command);249 return execa(file, args, options);250 }37 unmodified linesmodified:index.test-d.ts+50 added
4 unmodified lines5 import * as process from 'node:process';6 import {type Readable as ReadableStream} from 'node:stream';7 import {expectType, expectError} from 'tsd';8 import {9+ $,10 execa,11 execaSync,12 execaCommand,13 execaCommandSync,205 unmodified lines219 );220 expectType<ExecaChildProcess<Buffer>>(221 execaNode('unicorns', ['foo'], {nodeOptions: ['--async-stack-traces'], encoding: null}),222 );223+224+expectType<ExecaChildProcess>($`unicorns`);225+expectType<ExecaReturnValue>(await $`unicorns`);226+expectType<ExecaSyncReturnValue>($.sync`unicorns`);227+228+expectType<ExecaChildProcess>($({encoding: 'utf8'})`unicorns`);229+expectType<ExecaReturnValue>(await $({encoding: 'utf8'})`unicorns`);230+expectType<ExecaSyncReturnValue>($({encoding: 'utf8'}).sync`unicorns`);231+232+expectType<ExecaChildProcess>($({encoding: 'utf8'})`unicorns foo`);233+expectType<ExecaReturnValue>(await $({encoding: 'utf8'})`unicorns foo`);234+expectType<ExecaSyncReturnValue>($({encoding: 'utf8'}).sync`unicorns foo`);235+236+expectType<ExecaChildProcess<Buffer>>($({encoding: null})`unicorns`);237+expectType<ExecaReturnValue<Buffer>>(await $({encoding: null})`unicorns`);238+expectType<ExecaSyncReturnValue<Buffer>>($({encoding: null}).sync`unicorns`);239+240+expectType<ExecaChildProcess<Buffer>>($({encoding: null})`unicorns foo`);241+expectType<ExecaReturnValue<Buffer>>(await $({encoding: null})`unicorns foo`);242+expectType<ExecaSyncReturnValue<Buffer>>($({encoding: null}).sync`unicorns foo`);243+244+expectType<ExecaChildProcess>($({encoding: null})({encoding: 'utf8'})`unicorns`);245+expectType<ExecaReturnValue>(await $({encoding: null})({encoding: 'utf8'})`unicorns`);246+expectType<ExecaSyncReturnValue>($({encoding: null})({encoding: 'utf8'}).sync`unicorns`);247+248+expectType<ExecaChildProcess>($({encoding: null})({encoding: 'utf8'})`unicorns foo`);249+expectType<ExecaReturnValue>(await $({encoding: null})({encoding: 'utf8'})`unicorns foo`);250+expectType<ExecaSyncReturnValue>($({encoding: null})({encoding: 'utf8'}).sync`unicorns foo`);251+252+expectType<ExecaChildProcess<Buffer>>($({encoding: null})({})`unicorns`);253+expectType<ExecaReturnValue<Buffer>>(await $({encoding: null})({})`unicorns`);254+expectType<ExecaSyncReturnValue<Buffer>>($({encoding: null})({}).sync`unicorns`);255+256+expectType<ExecaChildProcess<Buffer>>($({encoding: null})({})`unicorns foo`);257+expectType<ExecaReturnValue<Buffer>>(await $({encoding: null})({})`unicorns foo`);258+expectType<ExecaSyncReturnValue<Buffer>>($({encoding: null})({}).sync`unicorns foo`);259+260+expectType<ExecaReturnValue>(await $`unicorns ${'foo'}`);261+expectType<ExecaSyncReturnValue>($.sync`unicorns ${'foo'}`);262+expectType<ExecaReturnValue>(await $`unicorns ${1}`);263+expectType<ExecaSyncReturnValue>($.sync`unicorns ${1}`);264+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 ${true.toString()}`);269+expectType<ExecaSyncReturnValue>($.sync`unicorns ${false.toString()}`);270+expectError<ExecaReturnValue>(await $`unicorns ${true}`);271+expectError<ExecaSyncReturnValue>($.sync`unicorns ${false}`);modified:readme.md+73 added
37 unmodified lines38 console.log(stdout);39 //=> 'unicorns'40 ```41 42+### Using the tagged templates API43+44+#### Basic45+46+```js47+import {$} from 'execa';48+49+const {stdout} = await $`echo unicorns`;50+// const {stdout} = await $`echo ${'unicorns'}`;51+// const {stdout} = await $`echo ${['unicorns', 'rainbows']}`;52+53+console.log(stdout);54+//=> 'unicorns'55+```56+57+#### With options58+59+```js60+import {$} from 'execa';61+62+await $({stdio: 'inherit'})`echo unicorns`;63+//=> 'unicorns'64+```65+66+#### With pre-defined options67+68+```js69+import {$} from 'execa';70+71+const $$ = $({stdio: 'inherit'});72+73+await $$`echo unicorns`;74+//=> 'unicorns'75+await $$({shell: true})`echo unicorns && echo rainbows`;76+//=> 'unicorns'77+//=> 'rainbows'78+```79+80+#### Synchronous81+82+```js83+import {$} from 'execa';84+85+const {stdout} = $.sync`echo unicorns`;86+console.log(stdout);87+//=> 'unicorns'88+89+$({stdio: 'inherit'}).sync`echo rainbows`;90+//=> 'rainbows'91+```92+93 ### Pipe the child process stdout to the parent94 95 ```js96 import {execa} from 'execa';144 unmodified lines241 Execute a file synchronously.242 243 Returns or throws a [`childProcessResult`](#childProcessResult).244 245+### $\`command\`246+247+Same as [`execa()`](#execafile-arguments-options) except both file and arguments are specified in a single tagged template string. For example, `` $`echo unicorns` `` is the same as `execa('echo', ['unicorns'])`.248+249+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.250+251+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`.252+253+Returns a `Promise` that resolves or rejects with a [`childProcessResult`](#childProcessResult).254+255+### $.sync\`command\`256+257+Same as [$\`command\`](#command) but synchronous like [`execaSync()`](#execasyncfile-arguments-options).258+259+Returns or throws a [`childProcessResult`](#childProcessResult).260+261+### $(options)262+263+Binds options to the [`$`](#command) API. For example, you can use `$(options)` to create a new `$` instance with specific default options, which are then bound to both the asynchronous [`` $`command` ``](#command) and synchronous [`` $.sync`command` ``](#synccommand) APIs.264+265+> **Note:** Consecutive calls to this API will shallow merge the options.266+267 ### execaCommand(command, options?)268 269 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 `execaCommand('echo unicorns')`.270 467 unmodified lines