Skip to content
Myr

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

6 files+407 added−18 removed

modified:lib/command.js+19 added
modified:test/command.js+86 added-1 removed
modified:index.d.ts+158 added-16 removed
335 unmodified lines
336 */337 signalDescription?: string;338};339340export type ExecaSyncReturnValue<StdoutErrorType = string> = {341} & ExecaReturnBase<StdoutErrorType>;340export type ExecaSyncReturnValue<StdoutStderrType = string> = {341} & ExecaReturnBase<StdoutStderrType>;342343/**344Result of a child process execution. On success this is a plain object. On failure this is also an `Error` instance.345
3 unmodified lines
349- timing out350- being canceled351- there's not enough memory or there are already too many child processes352*/353export type ExecaReturnValue<StdoutErrorType = string> = {353export type ExecaReturnValue<StdoutStderrType = string> = {354 /**355 The output of the process with `stdout` and `stderr` interleaved.356357 This is `undefined` if either:358 - the `all` option is `false` (default value)359 - `execaSync()` was used360 */361 all?: StdoutErrorType;361 all?: StdoutStderrType;362363 /**364 Whether the process was canceled.365366 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>;370371export type ExecaSyncError<StdoutErrorType = string> = {371export 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.374375 The child process stderr then stdout are appended to the end, separated with newlines and not interleaved.
10 unmodified lines
386387 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>;391392export type ExecaError<StdoutErrorType = string> = {392export type ExecaError<StdoutStderrType = string> = {393 /**394 The output of the process with `stdout` and `stderr` interleaved.395396 This is `undefined` if either:397 - the `all` option is `false` (default value)398 - `execaSync()` was used399 */400 all?: StdoutErrorType;400 all?: StdoutStderrType;401402 /**403 Whether the process was canceled.404 */405 isCanceled: boolean;406} & ExecaSyncError<StdoutErrorType>;406} & ExecaSyncError<StdoutStderrType>;407408export type KillOptions = {409 /**410 Milliseconds to wait for the child process to terminate before sending `SIGKILL`.
4 unmodified lines
415 */416 forceKillAfterTimeout?: number | false;417};418419export type ExecaChildPromise<StdoutErrorType> = {419export 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).422423 This is `undefined` if either:
2 unmodified lines
426 */427 all?: ReadableStream;428429 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>;432433 /**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 lines
440 */441 cancel(): void;442};443444export type ExecaChildProcess<StdoutErrorType = string> = ChildProcess &445ExecaChildPromise<StdoutErrorType> &446Promise<ExecaReturnValue<StdoutErrorType>>;444export type ExecaChildProcess<StdoutStderrType = string> = ChildProcess &445ExecaChildPromise<StdoutStderrType> &446Promise<ExecaReturnValue<StdoutStderrType>>;447448/**449Execute a file.450
89 unmodified lines
540*/541export function execaCommand(command: string, options?: Options): ExecaChildProcess;542export function execaCommand(command: string, options?: Options<null>): ExecaChildProcess<Buffer>;543544type TemplateExpression = string | number | Array<string | number>;545546type 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'])`.549550 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.551552 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`.553554 @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.555556 @example <caption>Basic</caption>557 ```558 import {$} from 'execa';559560 const {stdout} = await $`echo unicorns`;561 // const {stdout} = await $`echo ${'unicorns'}`;562 // const {stdout} = await $`echo ${['unicorns', 'rainbows']}`;563564 console.log(stdout);565 //=> 'unicorns'566 ```567568 @example <caption>With options</caption>569 ```570 import {$} from 'execa';571572 await $({stdio: 'inherit'})`echo unicorns`;573 //=> 'unicorns'574 ```575576 @example <caption>With pre-defined options</caption>577 ```578 import {$} from 'execa';579580 const $$ = $({stdio: 'inherit'});581 await $$`echo unicorns`;582 //=> 'unicorns'583 await $$({shell: true})`echo unicorns && echo rainbows`;584 //=> 'unicorns'585 //=> 'rainbows'586 ```587588 @example <caption>Synchronous</caption>589 ```590 import {$} from 'execa';591592 const {stdout} = $.sync`echo unicorns`;593 console.log(stdout);594 //=> 'unicorns'595596 $({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>;607608 /**609 Same as `$` but synchronous like `execaSync()`.610611 @returns The stdout and stderr output.612613 @example614 ```615 import {$} from 'execa';616617 const {stdout} = $.sync`echo unicorns`;618 console.log(stdout);619 //=> 'unicorns'620621 $({stdio: 'inherit'}).sync`echo rainbows`;622 //=> 'rainbows'623 ```624 */625 sync(626 templates: TemplateStringsArray,627 ...expressions: TemplateExpression[]628 ): ExecaSyncReturnValue<StdoutStderrType>;629};630631/**632Same 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'])`.633634It'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.635636The `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`.637638@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.639640@example <caption>Basic</caption>641```642import {$} from 'execa';643644const {stdout} = await $`echo unicorns`;645// const {stdout} = await $`echo ${'unicorns'}`;646// const {stdout} = await $`echo ${['unicorns', 'rainbows']}`;647648console.log(stdout);649//=> 'unicorns'650```651652@example <caption>With options</caption>653```654import {$} from 'execa';655656await $({stdio: 'inherit'})`echo unicorns`;657//=> 'unicorns'658```659660@example <caption>With pre-defined options</caption>661```662import {$} from 'execa';663664const $$ = $({stdio: 'inherit'});665await $$`echo unicorns`;666//=> 'unicorns'667await $$({shell: true})`echo unicorns && echo rainbows`;668//=> 'unicorns'669//=> 'rainbows'670```671672@example <caption>Synchronous</caption>673```674import {$} from 'execa';675676const {stdout} = $.sync`echo unicorns`;677console.log(stdout);678//=> 'unicorns'679680$({stdio: 'inherit'}).sync`echo rainbows`;681//=> 'rainbows'682```683*/684export const $: Execa$;685686/**687Same as `execaCommand()` but synchronous.688689@param command - The program/script to execute and its arguments.690@returns A result `Object` with `stdout` and `stderr` properties.
28 unmodified lines
modified:index.js+21 added-1 removed
9 unmodified lines
10import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js';11import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';12import {handleInput, getSpawnedResult, makeAllStream, validateInputSync} from './lib/stream.js';13import {mergePromise, getSpawnedPromise} from './lib/promise.js';14import {joinCommand, parseCommand, getEscapedCommand} from './lib/command.js';14import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';1516const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;1718const getEnv = ({env: envOption, extendEnv, preferLocal, localDir, execPath}) => {
204 unmodified lines
223 killed: false,224 };225}226227function 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 }233234 return create$({...options, ...templatesOrOptions});235 }236237 $.sync = (templates, ...expressions) => {238 const [file, ...args] = parseTemplates(templates, expressions);239 return execaSync(file, args, options);240 };241242 return $;243}244245export const $ = create$();246247export function execaCommand(command, options) {248 const [file, ...args] = parseCommand(command);249 return execa(file, args, options);250}
37 unmodified lines
modified:index.test-d.ts+50 added
4 unmodified lines
5import * as process from 'node:process';6import {type Readable as ReadableStream} from 'node:stream';7import {expectType, expectError} from 'tsd';8import {9 $,10 execa,11 execaSync,12 execaCommand,13 execaCommandSync,
205 unmodified lines
219);220expectType<ExecaChildProcess<Buffer>>(221 execaNode('unicorns', ['foo'], {nodeOptions: ['--async-stack-traces'], encoding: null}),222);223224expectType<ExecaChildProcess>($`unicorns`);225expectType<ExecaReturnValue>(await $`unicorns`);226expectType<ExecaSyncReturnValue>($.sync`unicorns`);227228expectType<ExecaChildProcess>($({encoding: 'utf8'})`unicorns`);229expectType<ExecaReturnValue>(await $({encoding: 'utf8'})`unicorns`);230expectType<ExecaSyncReturnValue>($({encoding: 'utf8'}).sync`unicorns`);231232expectType<ExecaChildProcess>($({encoding: 'utf8'})`unicorns foo`);233expectType<ExecaReturnValue>(await $({encoding: 'utf8'})`unicorns foo`);234expectType<ExecaSyncReturnValue>($({encoding: 'utf8'}).sync`unicorns foo`);235236expectType<ExecaChildProcess<Buffer>>($({encoding: null})`unicorns`);237expectType<ExecaReturnValue<Buffer>>(await $({encoding: null})`unicorns`);238expectType<ExecaSyncReturnValue<Buffer>>($({encoding: null}).sync`unicorns`);239240expectType<ExecaChildProcess<Buffer>>($({encoding: null})`unicorns foo`);241expectType<ExecaReturnValue<Buffer>>(await $({encoding: null})`unicorns foo`);242expectType<ExecaSyncReturnValue<Buffer>>($({encoding: null}).sync`unicorns foo`);243244expectType<ExecaChildProcess>($({encoding: null})({encoding: 'utf8'})`unicorns`);245expectType<ExecaReturnValue>(await $({encoding: null})({encoding: 'utf8'})`unicorns`);246expectType<ExecaSyncReturnValue>($({encoding: null})({encoding: 'utf8'}).sync`unicorns`);247248expectType<ExecaChildProcess>($({encoding: null})({encoding: 'utf8'})`unicorns foo`);249expectType<ExecaReturnValue>(await $({encoding: null})({encoding: 'utf8'})`unicorns foo`);250expectType<ExecaSyncReturnValue>($({encoding: null})({encoding: 'utf8'}).sync`unicorns foo`);251252expectType<ExecaChildProcess<Buffer>>($({encoding: null})({})`unicorns`);253expectType<ExecaReturnValue<Buffer>>(await $({encoding: null})({})`unicorns`);254expectType<ExecaSyncReturnValue<Buffer>>($({encoding: null})({}).sync`unicorns`);255256expectType<ExecaChildProcess<Buffer>>($({encoding: null})({})`unicorns foo`);257expectType<ExecaReturnValue<Buffer>>(await $({encoding: null})({})`unicorns foo`);258expectType<ExecaSyncReturnValue<Buffer>>($({encoding: null})({}).sync`unicorns foo`);259260expectType<ExecaReturnValue>(await $`unicorns ${'foo'}`);261expectType<ExecaSyncReturnValue>($.sync`unicorns ${'foo'}`);262expectType<ExecaReturnValue>(await $`unicorns ${1}`);263expectType<ExecaSyncReturnValue>($.sync`unicorns ${1}`);264expectType<ExecaReturnValue>(await $`unicorns ${['foo', 'bar']}`);265expectType<ExecaSyncReturnValue>($.sync`unicorns ${['foo', 'bar']}`);266expectType<ExecaReturnValue>(await $`unicorns ${[1, 2]}`);267expectType<ExecaSyncReturnValue>($.sync`unicorns ${[1, 2]}`);268expectType<ExecaReturnValue>(await $`unicorns ${true.toString()}`);269expectType<ExecaSyncReturnValue>($.sync`unicorns ${false.toString()}`);270expectError<ExecaReturnValue>(await $`unicorns ${true}`);271expectError<ExecaSyncReturnValue>($.sync`unicorns ${false}`);
modified:readme.md+73 added
37 unmodified lines
38console.log(stdout);39//=> 'unicorns'40```4142### Using the tagged templates API4344#### Basic4546```js47import {$} from 'execa';4849const {stdout} = await $`echo unicorns`;50// const {stdout} = await $`echo ${'unicorns'}`;51// const {stdout} = await $`echo ${['unicorns', 'rainbows']}`;5253console.log(stdout);54//=> 'unicorns'55```5657#### With options5859```js60import {$} from 'execa';6162await $({stdio: 'inherit'})`echo unicorns`;63//=> 'unicorns'64```6566#### With pre-defined options6768```js69import {$} from 'execa';7071const $$ = $({stdio: 'inherit'});7273await $$`echo unicorns`;74//=> 'unicorns'75await $$({shell: true})`echo unicorns && echo rainbows`;76//=> 'unicorns'77//=> 'rainbows'78```7980#### Synchronous8182```js83import {$} from 'execa';8485const {stdout} = $.sync`echo unicorns`;86console.log(stdout);87//=> 'unicorns'8889$({stdio: 'inherit'}).sync`echo rainbows`;90//=> 'rainbows'91```9293### Pipe the child process stdout to the parent9495```js96import {execa} from 'execa';
144 unmodified lines
241Execute a file synchronously.242243Returns or throws a [`childProcessResult`](#childProcessResult).244245### $\`command\`246247Same 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'])`.248249It'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.250251The [`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`.252253Returns a `Promise` that resolves or rejects with a [`childProcessResult`](#childProcessResult).254255### $.sync\`command\`256257Same as [$\`command\`](#command) but synchronous like [`execaSync()`](#execasyncfile-arguments-options).258259Returns or throws a [`childProcessResult`](#childProcessResult).260261### $(options)262263Binds 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.264265> **Note:** Consecutive calls to this API will shallow merge the options.266267### execaCommand(command, options?)268269Same 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