`.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
Provenance
- Commit
316f562- Tree
1f71b94- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
86949e0
8 files changed+189 added−21 removed
modified:docs/scripts.md+5 added-4 removed
4 unmodified lines5 ```js6 import {$} from 'execa';7 8 const {stdout: name} = await $`cat package.json`9- .pipe($({stdin: 'pipe'})`grep name`);9+ .pipe`grep name`;10 console.log(name);11 12 const branch = await $`git branch --show-current`;13 await $`dep deploy --branch=${branch}`;584 unmodified lines598 599 ```js600 // Execa601 await $`npm run build`602- .pipe($({stdin: 'pipe'})`sort`)603- .pipe($({stdin: 'pipe'})`head -n2`);602+ .pipe`sort`603+ .pipe`head -n2`;604 ```605 606 ### Piping stdout and stderr to another command607 12 unmodified lines620 ```621 622 ```js623 // Execa624-await $({all: true})`echo example`.pipe($({from: 'all', stdin: 'pipe'})`cat`);624+await $({all: true})`echo example`625+ .pipe({from: 'all'})`cat`;626 ```627 628 ### Piping stdout to a file629 50 unmodified linesmodified:lib/pipe/validate.js+1 added-6 removed
121234519 unmodified lines252627283031323329303132108 unmodified linesExpand allimport {ChildProcess} from 'node:child_process';import {STANDARD_STREAMS_ALIASES} from '../utils.js';import {STANDARD_STREAMS_ALIASES, isExecaChildProcess} from '../utils.js';import {makeEarlyError} from '../return/error.js';import {abortSourceStream, endDestinationStream} from './streaming.js';
export const normalizePipeArguments = (destination, from, {spawned: source, stdioStreamsGroups, options}) => {19 unmodified lines return {destinationError: error}; }};
const isExecaChildProcess = destination => destination instanceof ChildProcess && typeof destination.then === 'function' && typeof destination.pipe === 'function';
const getSourceStream = (source, stdioStreamsGroups, from, options) => { try { const streamIndex = getStreamIndex(stdioStreamsGroups, from); const sourceStream = streamIndex === 'all' ? source.all : source.stdio[streamIndex];108 unmodified linesExpand allmodified:lib/script.js+26 added-4 removed
1-import {ChildProcess} from 'node:child_process';1 import isPlainObject from 'is-plain-obj';3-import {isBinary, binaryToString} from './utils.js';2+import {isBinary, binaryToString, isChildProcess, isExecaChildProcess} from './utils.js';3 import {execa} from './async.js';4 import {execaSync} from './sync.js';5 6 const create$ = options => {6 unmodified lines13 throw new TypeError('Please use either $(option) or $`command`.');14 }15 16 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 }21 22 $.sync = (templates, ...expressions) => {23 if (isPlainObject(templates)) {14 unmodified lines38 };39 40 export const $ = create$();41 42+const 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+ }47+48+ return originalPipe(firstArgument, ...args);49+ }50+51+ if (isPlainObject(firstArgument)) {52+ return scriptPipe.bind(undefined, originalPipe, {...options, ...firstArgument});53+ }54+55+ 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+ }58+59+ const childProcess = create$({...options, stdin: 'pipe'})(firstArgument, ...args);60+ return originalPipe(childProcess, options);61+};62+63 const parseTemplates = (templates, expressions) => {64 let tokens = [];65 66 for (const [index, template] of templates.entries()) {50 unmodified lines117 118 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 linesmodified:lib/utils.js+7 added
12345618 unmodified lines25262728293031323334import {Buffer} from 'node:buffer';import {ChildProcess} from 'node:child_process';import {addAbortListener} from 'node:events';import process from 'node:process';
export const bufferToUint8Array = buffer => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);18 unmodified lines addAbortListener(signal, () => { eventEmitter.setMaxListeners(eventEmitter.getMaxListeners() - maxListenersIncrement); });};
export const isExecaChildProcess = value => isChildProcess(value) && typeof value.then === 'function' && typeof value.pipe === 'function';
export const isChildProcess = value => value instanceof ChildProcess;modified:test/script.js+52 added
1+import {spawn} from 'node:child_process';2 import {inspect} from 'node:util';3 import test from 'ava';4 import {isStream} from 'is-stream';5 import {$} from '../index.js';6 import {setFixtureDir} from './helpers/fixtures-dir.js';7+import {foobarString} from './helpers/input.js';8 9 setFixtureDir();10 11 test('$', async t => {253 unmodified lines265 266 test('$ stdin has no default value when stdio is set', t => {267 t.true(isStream($({stdio: 'pipe'})`noop.js`.stdin));268 });269+270+test('$.pipe(childProcess)', async t => {271+ const {stdout} = await $`noop.js ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`);272+ t.is(stdout, foobarString);273+});274+275+test('$.pipe`command`', async t => {276+ const {stdout} = await $`noop.js ${foobarString}`.pipe`stdin.js`;277+ t.is(stdout, foobarString);278+});279+280+test('$.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+});284+285+test('$.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+});289+290+test('$.pipe(options)`command`', async t => {291+ const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})`stdin.js`;292+ t.is(stdout, `${foobarString}\n`);293+});294+295+test('$.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+});299+300+test('$.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+});304+305+test('$.pipe(options)(childProcess) fails', t => {306+ t.throws(() => {307+ $`empty.js`.pipe({stdout: 'pipe'})($`empty.js`);308+ }, {message: /Please use \.pipe/});309+});310+311+const testInvalidPipe = (t, ...args) => {312+ t.throws(() => {313+ $`empty.js`.pipe(...args);314+ }, {message: /must be a template string/});315+};316+317+test('$.pipe(nonExecaChildProcess) fails', testInvalidPipe, spawn('node', ['--version']));318+test('$.pipe(false) fails', testInvalidPipe, false);modified:index.d.ts+35 added-3 removed
839 unmodified lines840 841 This can be called multiple times to chain a series of processes.842 843 Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.844+845+ When using `$`, the following simpler syntax can be used instead.846+847+ ```js848+ import {$} from 'execa';849+850+ await $`command`.pipe`secondCommand`;851+852+ // 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 };858 859+type 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.862+863+ This can be called multiple times to chain a series of processes.864+865+ Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.866+867+ When using `$`, the following simpler syntax can be used instead.868+869+ ```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+};880+881 export type ExecaChildPromise<OptionsType extends Options = Options> = {882 stdin: StreamUnlessIgnored<'0', OptionsType>;883 884 stdout: StreamUnlessIgnored<'1', OptionsType>;293 unmodified lines1178 //=> 'rainbows'1179 ```1180 */1181 <NewOptionsType extends CommonOptions = {}>1149- (options: NewOptionsType):1150- Execa$<OptionsType & NewOptionsType>;1182+ (options: NewOptionsType): Execa$<OptionsType & NewOptionsType>;1183 1184 (templates: TemplateStringsArray, ...expressions: TemplateExpression[]):1153- ExecaChildProcess<StricterOptions<OptionsType, Options>>;1185+ ExecaChildProcess<StricterOptions<OptionsType, Options>> & ScriptPipableProcess;1186 1187 /**1188 Same as $\`command\` but synchronous.1189 189 unmodified linesmodified:index.test-d.ts+42 added-4 removed
82 unmodified lines83 84 const execaBufferPromise = execa('unicorns', {encoding: 'buffer', all: true});85 const bufferResult = await execaBufferPromise;86 87+ const scriptPromise = $`unicorns`;88+89 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));136 137+ 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);141+142 expectType<Readable>(execaPromise.all);143 const noAllPromise = execa('unicorns');144 expectType<undefined>(noAllPromise.all);145 const noAllResult = await noAllPromise;1213 unmodified lines1359 expectError(execa('unicorns').kill('SIGKILL', {}));1360 expectError(execa('unicorns').kill(null, new Error('test')));1361 1362 expectError(execa(['unicorns', 'arg']));1325-expectType<ExecaChildProcess>(execa('unicorns'));1326-expectType<ExecaChildProcess>(execa(fileUrl));1363+expectAssignable<ExecaChildProcess>(execa('unicorns'));1364+expectAssignable<ExecaChildProcess>(execa(fileUrl));1365 expectType<ExecaReturnValue>(await execa('unicorns'));1366 expectAssignable<{stdout: string}>(await execa('unicorns'));1367 expectAssignable<{stdout: Uint8Array}>(await execa('unicorns', {encoding: 'buffer'}));1368 expectAssignable<{stdout: string}>(await execa('unicorns', ['foo']));6 unmodified lines1375 expectAssignable<{stdout: Uint8Array}>(execaSync('unicorns', {encoding: 'buffer'}));1376 expectAssignable<{stdout: string}>(execaSync('unicorns', ['foo']));1377 expectAssignable<{stdout: Uint8Array}>(execaSync('unicorns', ['foo'], {encoding: 'buffer'}));1378 1341-expectType<ExecaChildProcess>(execaCommand('unicorns'));1379+expectAssignable<ExecaChildProcess>(execaCommand('unicorns'));1380 expectType<ExecaReturnValue>(await execaCommand('unicorns'));1381 expectAssignable<{stdout: string}>(await execaCommand('unicorns'));1382 expectAssignable<{stdout: Uint8Array}>(await execaCommand('unicorns', {encoding: 'buffer'}));1383 expectAssignable<{stdout: string}>(await execaCommand('unicorns foo'));5 unmodified lines1389 expectAssignable<{stdout: string}>(execaCommandSync('unicorns foo'));1390 expectAssignable<{stdout: Uint8Array}>(execaCommandSync('unicorns foo', {encoding: 'buffer'}));1391 1392 expectError(execaNode(['unicorns', 'arg']));1355-expectType<ExecaChildProcess>(execaNode('unicorns'));1393+expectAssignable<ExecaChildProcess>(execaNode('unicorns'));1394 expectType<ExecaReturnValue>(await execaNode('unicorns'));1395 expectType<ExecaReturnValue>(await execaNode(fileUrl));1396 expectAssignable<{stdout: string}>(await execaNode('unicorns'));1397 expectAssignable<{stdout: Uint8Array}>(await execaNode('unicorns', {encoding: 'buffer'}));66 unmodified linesmodified:readme.md+21 added
122 unmodified lines123 await $$`echo rainbows`;124 //=> 'rainbows'125 ```126 127+#### Piping128+129+```js130+import {$} from 'execa';131+132+await $`npm run build`133+ .pipe`sort`134+ .pipe`head -n2`;135+```136+137 #### Verbose mode138 139 ```sh140 > node file.js195 unmodified lines336 This can be called multiple times to chain a series of processes.337 338 Multiple child processes can be piped to the same process. Conversely, the same child process can be piped to multiple other processes.339 340+When using [`$`](#command), the following [simpler syntax](docs/scripts.md#piping-stdout-to-another-command) can be used instead.341+342+```js343+import {$} from 'execa';344+345+await $`command`.pipe`secondCommand`;346+347+// To pass either child process options or pipe options348+await $`command`.pipe(options)`secondCommand`;349+```350+351 ##### pipeOptions352 353 Type: `object`354 657 unmodified lines