From 981f50ce10d9017745fd492fb9fe866defdba314 Mon Sep 17 00:00:00 2001 From: Anton Golub Date: Sun, 17 Mar 2024 22:17:20 +0300 Subject: [PATCH] feat: provide `input` option closes #720 --- src/core.ts | 12 +++++++++--- test/core.test.js | 16 +++++++++++++++- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/core.ts b/src/core.ts index 5d84151200..da1c77edcf 100644 --- a/src/core.ts +++ b/src/core.ts @@ -48,8 +48,9 @@ const processCwd = Symbol('processCwd') export interface Options { [processCwd]: string cwd?: string - verbose: boolean ac?: AbortController + input?: string | Buffer | Readable | ProcessOutput | ProcessPromise + verbose: boolean env: NodeJS.ProcessEnv shell: string | boolean nothrow: boolean @@ -187,11 +188,15 @@ export class ProcessPromise extends Promise { } run(): ProcessPromise { - const $ = this._snapshot - const self = this if (this.child) return this // The _run() can be called from a few places. this._prerun() // In case $1.pipe($2), the $2 returned, and on $2._run() invoke $1._run(). + const $ = this._snapshot + const self = this + const input = ($.input as ProcessPromise | ProcessOutput)?.stdout ?? $.input + + if (input) this.stdio('pipe') + $.log({ kind: 'cmd', cmd: this._command, @@ -199,6 +204,7 @@ export class ProcessPromise extends Promise { }) this.zurk = exec({ + input, cmd: $.prefix + this._command, cwd: $.cwd ?? $[processCwd], ac: $.ac, diff --git a/test/core.test.js b/test/core.test.js index b04a5b9285..383ac7f331 100644 --- a/test/core.test.js +++ b/test/core.test.js @@ -15,7 +15,7 @@ import assert from 'node:assert' import { test, describe, beforeEach } from 'node:test' import { inspect } from 'node:util' -import { Writable } from 'node:stream' +import { Readable, Writable } from 'node:stream' import { Socket } from 'node:net' import { ProcessPromise, ProcessOutput } from '../build/index.js' import '../build/globals.js' @@ -106,6 +106,20 @@ describe('core', () => { } }) + test('handles `input` option', async () => { + const p1 = $({ input: 'foo' })`cat` + const p2 = $({ input: Readable.from('bar') })`cat` + const p3 = $({ input: Buffer.from('baz') })`cat` + const p4 = $({ input: p3 })`cat` + const p5 = $({ input: await p3 })`cat` + + assert.equal((await p1).stdout, 'foo') + assert.equal((await p2).stdout, 'bar') + assert.equal((await p3).stdout, 'baz') + assert.equal((await p4).stdout, 'baz') + assert.equal((await p5).stdout, 'baz') + }) + test('pipes are working', async () => { let { stdout } = await $`echo "hello"` .pipe($`awk '{print $1" world"}'`)