Skip to content
Myr

`.pipe()` shortcut for `$` (#840)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by ehmicky · committed by GitHub · parent 86949e0 · Browse files · 8 files+189 added−21 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+189 added−21 removed

  • tests:+52 added−0 removed
  • other:+137 added−21 removed

8 files+189 added−21 removed

modified:docs/scripts.md+5 added-4 removed
4 unmodified lines
5```js6import {$} from 'execa';78const {stdout: name} = await $`cat package.json`9 .pipe($({stdin: 'pipe'})`grep name`);9 .pipe`grep name`;10console.log(name);1112const branch = await $`git branch --show-current`;13await $`dep deploy --branch=${branch}`;
584 unmodified lines
598599```js600// Execa601await $`npm run build`602 .pipe($({stdin: 'pipe'})`sort`)603 .pipe($({stdin: 'pipe'})`head -n2`);602 .pipe`sort`603 .pipe`head -n2`;604```605606### Piping stdout and stderr to another command607
12 unmodified lines
620```621622```js623// Execa624await $({all: true})`echo example`.pipe($({from: 'all', stdin: 'pipe'})`cat`);624await $({all: true})`echo example`625 .pipe({from: 'all'})`cat`;626```627628### Piping stdout to a file629
50 unmodified lines
modified:lib/pipe/validate.js+1 added-6 removed
modified:lib/script.js+26 added-4 removed
1import {ChildProcess} from 'node:child_process';1import isPlainObject from 'is-plain-obj';3import {isBinary, binaryToString} from './utils.js';2import {isBinary, binaryToString, isChildProcess, isExecaChildProcess} from './utils.js';3import {execa} from './async.js';4import {execaSync} from './sync.js';56const create$ = options => {
6 unmodified lines
13 throw new TypeError('Please use either $(option) or $`command`.');14 }1516 const [file, ...args] = parseTemplates(templatesOrOptions, expressions);18 return execa(file, args, normalizeScriptOptions(options));17 const childProcess = execa(file, args, normalizeScriptOptions(options));18 childProcess.pipe = scriptPipe.bind(undefined, childProcess.pipe.bind(childProcess), {});19 return childProcess;20 }2122 $.sync = (templates, ...expressions) => {23 if (isPlainObject(templates)) {
14 unmodified lines
38};3940export const $ = create$();4142const scriptPipe = (originalPipe, options, firstArgument, ...args) => {43 if (isExecaChildProcess(firstArgument)) {44 if (Object.keys(options).length > 0) {45 throw new TypeError('Please use .pipe(options)`command` or .pipe($(options)`command`) instead of .pipe(options)($`command`).');46 }4748 return originalPipe(firstArgument, ...args);49 }5051 if (isPlainObject(firstArgument)) {52 return scriptPipe.bind(undefined, originalPipe, {...options, ...firstArgument});53 }5455 if (!Array.isArray(firstArgument)) {56 throw new TypeError('The first argument must be a template string, an options object, or an Execa child process.');57 }5859 const childProcess = create$({...options, stdin: 'pipe'})(firstArgument, ...args);60 return originalPipe(childProcess, options);61};6263const parseTemplates = (templates, expressions) => {64 let tokens = [];6566 for (const [index, template] of templates.entries()) {
50 unmodified lines
117118 if (119 typeOfExpression === 'object'120 && expression !== null99 && !(expression instanceof ChildProcess)121 && !isChildProcess(expression)122 && 'stdout' in expression123 ) {124 const typeOfStdout = typeof expression.stdout;125
23 unmodified lines
modified:lib/utils.js+7 added
modified:test/script.js+52 added
1import {spawn} from 'node:child_process';2import {inspect} from 'node:util';3import test from 'ava';4import {isStream} from 'is-stream';5import {$} from '../index.js';6import {setFixtureDir} from './helpers/fixtures-dir.js';7import {foobarString} from './helpers/input.js';89setFixtureDir();1011test('$', async t => {
253 unmodified lines
265266test('$ stdin has no default value when stdio is set', t => {267 t.true(isStream($({stdio: 'pipe'})`noop.js`.stdin));268});269270test('$.pipe(childProcess)', async t => {271 const {stdout} = await $`noop.js ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`);272 t.is(stdout, foobarString);273});274275test('$.pipe`command`', async t => {276 const {stdout} = await $`noop.js ${foobarString}`.pipe`stdin.js`;277 t.is(stdout, foobarString);278});279280test('$.pipe(childProcess, pipeOptions)', async t => {281 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});282 t.is(stdout, foobarString);283});284285test('$.pipe(pipeOptions)`command`', async t => {286 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe({from: 'stderr'})`stdin.js`;287 t.is(stdout, foobarString);288});289290test('$.pipe(options)`command`', async t => {291 const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})`stdin.js`;292 t.is(stdout, `${foobarString}\n`);293});294295test('$.pipe(pipeAndProcessOptions)`command`', async t => {296 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;297 t.is(stdout, `${foobarString}\n`);298});299300test('$.pipe(options)(secondOptions)`command`', async t => {301 const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;302 t.is(stdout, foobarString);303});304305test('$.pipe(options)(childProcess) fails', t => {306 t.throws(() => {307 $`empty.js`.pipe({stdout: 'pipe'})($`empty.js`);308 }, {message: /Please use \.pipe/});309});310311const testInvalidPipe = (t, ...args) => {312 t.throws(() => {313 $`empty.js`.pipe(...args);314 }, {message: /must be a template string/});315};316317test('$.pipe(nonExecaChildProcess) fails', testInvalidPipe, spawn('node', ['--version']));318test('$.pipe(false) fails', testInvalidPipe, false);
modified:index.d.ts+35 added-3 removed
839 unmodified lines
840841 This can be called multiple times to chain a series of processes.842843 Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.844845 When using `$`, the following simpler syntax can be used instead.846847 ```js848 import {$} from 'execa';849850 await $`command`.pipe`secondCommand`;851852 // To pass either child process options or pipe options853 await $`command`.pipe(options)`secondCommand`;854 ```855 */856 pipe<Destination extends ExecaChildProcess>(destination: Destination, options?: PipeOptions): Promise<Awaited<Destination>> & PipableProcess;857};858859type ScriptPipableProcess = PipableProcess & {860 /**861 [Pipe](https://nodejs.org/api/stream.html#readablepipedestination-options) the child process' `stdout` to a second Execa child process' `stdin`. This resolves with that second process' result. If either process is rejected, this is rejected with that process' error instead.862863 This can be called multiple times to chain a series of processes.864865 Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.866867 When using `$`, the following simpler syntax can be used instead.868869 ```js870 await $`command`.pipe`secondCommand`;871 // To pass either child process options or pipe options872 await $`command`.pipe(options)`secondCommand`;873 ```874 */875 pipe(templates: TemplateStringsArray, ...expressions: TemplateExpression[]): Promise<ExecaReturnValue<{}>> & ScriptPipableProcess;876 pipe<OptionsType extends Options & PipeOptions = {}>(options: OptionsType):877 (templates: TemplateStringsArray, ...expressions: TemplateExpression[])878 => Promise<ExecaReturnValue<OptionsType>> & ScriptPipableProcess;879};880881export type ExecaChildPromise<OptionsType extends Options = Options> = {882 stdin: StreamUnlessIgnored<'0', OptionsType>;883884 stdout: StreamUnlessIgnored<'1', OptionsType>;
293 unmodified lines
1178 //=> 'rainbows'1179 ```1180 */1181 <NewOptionsType extends CommonOptions = {}>1149 (options: NewOptionsType):1150 Execa$<OptionsType & NewOptionsType>;1182 (options: NewOptionsType): Execa$<OptionsType & NewOptionsType>;11831184 (templates: TemplateStringsArray, ...expressions: TemplateExpression[]):1153 ExecaChildProcess<StricterOptions<OptionsType, Options>>;1185 ExecaChildProcess<StricterOptions<OptionsType, Options>> & ScriptPipableProcess;11861187 /**1188 Same as $\`command\` but synchronous.1189
189 unmodified lines
modified:index.test-d.ts+42 added-4 removed
82 unmodified lines
8384 const execaBufferPromise = execa('unicorns', {encoding: 'buffer', all: true});85 const bufferResult = await execaBufferPromise;8687 const scriptPromise = $`unicorns`;8889 expectType<typeof bufferResult>(await execaPromise.pipe(execaBufferPromise));90 expectType<typeof bufferResult>(await scriptPromise.pipe(execaBufferPromise));91 expectNotType<typeof bufferResult>(await execaPromise.pipe(execaPromise));92 expectNotType<typeof bufferResult>(await scriptPromise.pipe(execaPromise));93 expectType<ExecaReturnValue<{}>>(await scriptPromise.pipe`stdin`);94 expectType<typeof bufferResult>(await execaPromise.pipe(execaPromise).pipe(execaBufferPromise));95 expectType<typeof bufferResult>(await scriptPromise.pipe(execaPromise).pipe(execaBufferPromise));96 expectType <ExecaReturnValue<{}>>(await scriptPromise.pipe`stdin`.pipe`stdin`);97 await execaPromise.pipe(execaPromise).pipe(execaBufferPromise, {from: 'stdout'});98 await scriptPromise.pipe(execaPromise).pipe(execaBufferPromise, {from: 'stdout'});99 await scriptPromise.pipe`stdin`.pipe({from: 'stdout'})`stdin`;100 expectError(execaPromise.pipe(execaBufferPromise).stdout);101 expectError(scriptPromise.pipe(execaBufferPromise).stdout);102 expectError(scriptPromise.pipe`stdin`.stdout);103 expectError(execaPromise.pipe(createWriteStream('output.txt')));104 expectError(scriptPromise.pipe(createWriteStream('output.txt')));105 expectError(execaPromise.pipe('output.txt'));106 expectError(scriptPromise.pipe('output.txt'));107 await execaPromise.pipe(execaBufferPromise, {});108 await scriptPromise.pipe(execaBufferPromise, {});109 await scriptPromise.pipe({})`stdin`;110 expectError(execaPromise.pipe(execaBufferPromise, 'stdout'));111 expectError(scriptPromise.pipe(execaBufferPromise, 'stdout'));112 expectError(scriptPromise.pipe('stdout')`stdin`);113 await execaPromise.pipe(execaBufferPromise, {from: 'stdout'});114 await scriptPromise.pipe(execaBufferPromise, {from: 'stdout'});115 await scriptPromise.pipe({from: 'stdout'})`stdin`;116 await execaPromise.pipe(execaBufferPromise, {from: 'stderr'});117 await scriptPromise.pipe(execaBufferPromise, {from: 'stderr'});118 await scriptPromise.pipe({from: 'stderr'})`stdin`;119 await execaPromise.pipe(execaBufferPromise, {from: 'all'});120 await scriptPromise.pipe(execaBufferPromise, {from: 'all'});121 await scriptPromise.pipe({from: 'all'})`stdin`;122 await execaPromise.pipe(execaBufferPromise, {from: 3});123 await scriptPromise.pipe(execaBufferPromise, {from: 3});124 await scriptPromise.pipe({from: 3})`stdin`;125 expectError(execaPromise.pipe(execaBufferPromise, {from: 'other'}));126 expectError(scriptPromise.pipe(execaBufferPromise, {from: 'other'}));127 expectError(scriptPromise.pipe({from: 'other'})`stdin`);128 await execaPromise.pipe(execaBufferPromise, {signal: new AbortController().signal});129 await scriptPromise.pipe(execaBufferPromise, {signal: new AbortController().signal});130 await scriptPromise.pipe({signal: new AbortController().signal})`stdin`;131 expectError(await execaPromise.pipe(execaBufferPromise, {signal: true}));132 expectError(await scriptPromise.pipe(execaBufferPromise, {signal: true}));133 expectError(await scriptPromise.pipe({signal: true})`stdin`);134 expectError(await scriptPromise.pipe({})({}));135 expectError(await scriptPromise.pipe({})(execaPromise));136137 const pipeResult = await scriptPromise.pipe`stdin`;138 expectType<string>(pipeResult.stdout);139 const ignorePipeResult = await scriptPromise.pipe({stdout: 'ignore'})`stdin`;140 expectType<undefined>(ignorePipeResult.stdout);141142 expectType<Readable>(execaPromise.all);143 const noAllPromise = execa('unicorns');144 expectType<undefined>(noAllPromise.all);145 const noAllResult = await noAllPromise;
1213 unmodified lines
1359expectError(execa('unicorns').kill('SIGKILL', {}));1360expectError(execa('unicorns').kill(null, new Error('test')));13611362expectError(execa(['unicorns', 'arg']));1325expectType<ExecaChildProcess>(execa('unicorns'));1326expectType<ExecaChildProcess>(execa(fileUrl));1363expectAssignable<ExecaChildProcess>(execa('unicorns'));1364expectAssignable<ExecaChildProcess>(execa(fileUrl));1365expectType<ExecaReturnValue>(await execa('unicorns'));1366expectAssignable<{stdout: string}>(await execa('unicorns'));1367expectAssignable<{stdout: Uint8Array}>(await execa('unicorns', {encoding: 'buffer'}));1368expectAssignable<{stdout: string}>(await execa('unicorns', ['foo']));
6 unmodified lines
1375expectAssignable<{stdout: Uint8Array}>(execaSync('unicorns', {encoding: 'buffer'}));1376expectAssignable<{stdout: string}>(execaSync('unicorns', ['foo']));1377expectAssignable<{stdout: Uint8Array}>(execaSync('unicorns', ['foo'], {encoding: 'buffer'}));13781341expectType<ExecaChildProcess>(execaCommand('unicorns'));1379expectAssignable<ExecaChildProcess>(execaCommand('unicorns'));1380expectType<ExecaReturnValue>(await execaCommand('unicorns'));1381expectAssignable<{stdout: string}>(await execaCommand('unicorns'));1382expectAssignable<{stdout: Uint8Array}>(await execaCommand('unicorns', {encoding: 'buffer'}));1383expectAssignable<{stdout: string}>(await execaCommand('unicorns foo'));
5 unmodified lines
1389expectAssignable<{stdout: string}>(execaCommandSync('unicorns foo'));1390expectAssignable<{stdout: Uint8Array}>(execaCommandSync('unicorns foo', {encoding: 'buffer'}));13911392expectError(execaNode(['unicorns', 'arg']));1355expectType<ExecaChildProcess>(execaNode('unicorns'));1393expectAssignable<ExecaChildProcess>(execaNode('unicorns'));1394expectType<ExecaReturnValue>(await execaNode('unicorns'));1395expectType<ExecaReturnValue>(await execaNode(fileUrl));1396expectAssignable<{stdout: string}>(await execaNode('unicorns'));1397expectAssignable<{stdout: Uint8Array}>(await execaNode('unicorns', {encoding: 'buffer'}));
66 unmodified lines
modified:readme.md+21 added
122 unmodified lines
123await $$`echo rainbows`;124//=> 'rainbows'125```126127#### Piping128129```js130import {$} from 'execa';131132await $`npm run build`133 .pipe`sort`134 .pipe`head -n2`;135```136137#### Verbose mode138139```sh140> node file.js
195 unmodified lines
336This can be called multiple times to chain a series of processes.337338Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.339340When using [`$`](#command), the following [simpler syntax](docs/scripts.md#piping-stdout-to-another-command) can be used instead.341342```js343import {$} from 'execa';344345await $`command`.pipe`secondCommand`;346347// To pass either child process options or pipe options348await $`command`.pipe(options)`secondCommand`;349```350351##### pipeOptions352353Type: `object`354
657 unmodified lines