Skip to content
Myr

Allow `stdin` to be a sync/async iterable (#604)

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

authored by ehmicky · committed by GitHub · parent 2f89219 · Browse files · 7 files+175 added−15 removed
This commit

State

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

Diff stats

7 files+175 added−15 removed

  • tests:+70 added−0 removed
  • other:+105 added−15 removed

7 files+175 added−15 removed

modified:lib/stdio.js+36 added
modified:lib/stream.js+35 added-5 removed
modified:test/stream.js+70 added
95 unmodified lines
96 t.is(stderr, undefined);97 t.is(all, undefined);98});99100test('stdin option can be a sync iterable of strings', async t => {101 const {stdout} = await execa('stdin.js', {stdin: ['foo', 'bar']});102 t.is(stdout, 'foobar');103});104105const textEncoder = new TextEncoder();106const binaryFoo = textEncoder.encode('foo');107const binaryBar = textEncoder.encode('bar');108109test('stdin option can be a sync iterable of Uint8Arrays', async t => {110 const {stdout} = await execa('stdin.js', {stdin: [binaryFoo, binaryBar]});111 t.is(stdout, 'foobar');112});113114const stringGenerator = function * () {115 yield * ['foo', 'bar'];116};117118const binaryGenerator = function * () {119 yield * [binaryFoo, binaryBar];120};121122const throwingGenerator = function * () {123 yield 'foo';124 throw new Error('generator error');125};126127test('stdin option can be an async iterable of strings', async t => {128 const {stdout} = await execa('stdin.js', {stdin: stringGenerator()});129 t.is(stdout, 'foobar');130});131132test('stdin option can be an async iterable of Uint8Arrays', async t => {133 const {stdout} = await execa('stdin.js', {stdin: binaryGenerator()});134 t.is(stdout, 'foobar');135});136137test('stdin option cannot be a sync iterable with execa.sync()', t => {138 t.throws(() => {139 execaSync('stdin.js', {stdin: ['foo', 'bar']});140 }, {message: /an iterable in sync mode/});141});142143test('stdin option cannot be an async iterable with execa.sync()', t => {144 t.throws(() => {145 execaSync('stdin.js', {stdin: stringGenerator()});146 }, {message: /an iterable in sync mode/});147});148149test('stdin option cannot be an iterable when "input" is used', t => {150 t.throws(() => {151 execa('stdin.js', {stdin: ['foo', 'bar'], input: 'foobar'});152 }, {message: /when the `input` option/});153});154155test('stdin option cannot be an iterable when "inputFile" is used', t => {156 t.throws(() => {157 execa('stdin.js', {stdin: ['foo', 'bar'], inputFile: 'dummy.txt'});158 }, {message: /when the `inputFile` option/});159});160161test('stdin option cannot be a generic iterable string', async t => {162 await t.throwsAsync(() => execa('stdin.js', {stdin: 'foobar'}), {code: 'ERR_INVALID_SYNC_FORK_INPUT'});163});164165test('stdin option handles errors in iterables', async t => {166 const {originalMessage} = await t.throwsAsync(() => execa('stdin.js', {stdin: throwingGenerator()}));167 t.is(originalMessage, 'generator error');168});169170test('input option can be a String', async t => {171 const {stdout} = await execa('stdin.js', {input: 'foobar'});172 t.is(stdout, 'foobar');173});
203 unmodified lines
modified:index.d.ts+5 added-1 removed
10 unmodified lines
11 | Stream12 | number13 | undefined;1415export type StdinOption = StdioOption | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>;1617type EncodingOption =18 | 'utf8'19 // eslint-disable-next-line unicorn/text-encoding-identifier-case20 | 'utf-8'
66 unmodified lines
8788 /**89 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).9091 It can also be an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), providing neither [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) nor the [`inputFile` option](#inputfile) is used.9293 @default `inherit` with `$`, `pipe` otherwise94 */91 readonly stdin?: StdioOption;95 readonly stdin?: StdinOption;9697 /**98 Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).99
900 unmodified lines
modified:index.js+8 added-8 removed
5 unmodified lines
6import stripFinalNewline from 'strip-final-newline';7import {npmRunPathEnv} from 'npm-run-path';8import onetime from 'onetime';9import {makeError} from './lib/error.js';10import {normalizeStdio, normalizeStdioNode} from './lib/stdio.js';10import {handleStdioOption, normalizeStdioNode} from './lib/stdio.js';11import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';12import {addPipeMethods} from './lib/pipe.js';13import {validateInputOptions, handleInput, getSpawnedResult, makeAllStream, handleInputSync} from './lib/stream.js';14import {mergePromise, getSpawnedPromise} from './lib/promise.js';
36 unmodified lines
51 };5253 options.env = getEnv(options);5455 options.stdio = normalizeStdio(options);55 const stdioStreams = handleStdioOption(options);5657 if (process.platform === 'win32' && path.basename(file, '.exe') === 'cmd') {58 // #11659 args.unshift('/q');60 }6162 return {file, args, options, parsed};62 return {file, args, options, parsed, stdioStreams};63};6465const handleOutput = (options, value, error) => {66 if (typeof value !== 'string' && !Buffer.isBuffer(value)) {
14 unmodified lines
81 const escapedCommand = getEscapedCommand(file, args);82 logCommand(escapedCommand, parsed.options);8384 validateTimeout(parsed.options);85 validateInputOptions(parsed.options);85 validateInputOptions(parsed.options, parsed.stdioStreams);8687 let spawned;88 try {89 spawned = childProcess.spawn(parsed.file, parsed.args, parsed.options);
25 unmodified lines
115 spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));116 spawned.cancel = spawnedCancel.bind(null, spawned, context);117118 const handlePromise = async () => {119 const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);119 const [{error, exitCode, signal, timedOut}, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, parsed.stdioStreams, processDone);120 const stdout = handleOutput(parsed.options, stdoutResult);121 const stderr = handleOutput(parsed.options, stderrResult);122 const all = handleOutput(parsed.options, allResult);123
35 unmodified lines
159 };160161 const handlePromiseOnce = onetime(handlePromise);162163 handleInput(spawned, parsed.options);163 handleInput(spawned, parsed.options, parsed.stdioStreams);164165 spawned.all = makeAllStream(spawned, parsed.options);166167 addPipeMethods(spawned);
6 unmodified lines
174 const command = joinCommand(file, args);175 const escapedCommand = getEscapedCommand(file, args);176 logCommand(escapedCommand, parsed.options);177178 validateInputOptions(parsed.options);179 const inputOption = handleInputSync(parsed.options);178 validateInputOptions(parsed.options, parsed.stdioStreams);179 const inputOption = handleInputSync(parsed.options, parsed.stdioStreams);180181 let result;182 try {183 result = childProcess.spawnSync(parsed.file, parsed.args, {...parsed.options, input: inputOption});
130 unmodified lines
modified:index.test-d.ts+18 added
126 unmodified lines
127 expectType<string>(execaError.shortMessage);128 expectType<string | undefined>(execaError.originalMessage);129}130131const stringGenerator = function * () {132 yield '';133};134135const binaryGenerator = function * () {136 yield new Uint8Array(0);137};138139const numberGenerator = function * () {140 yield 0;141};142143/* eslint-disable @typescript-eslint/no-floating-promises */144execa('unicorns', {cleanup: false});145execa('unicorns', {preferLocal: false});146execa('unicorns', {localDir: '.'});
10 unmodified lines
157execa('unicorns', {stdin: 'ipc'});158execa('unicorns', {stdin: 'ignore'});159execa('unicorns', {stdin: 'inherit'});160execa('unicorns', {stdin: process.stdin});161execa('unicorns', {stdin: ['']});162execa('unicorns', {stdin: [new Uint8Array(0)]});163execa('unicorns', {stdin: stringGenerator()});164execa('unicorns', {stdin: binaryGenerator()});165expectError(execa('unicorns', {stdin: [0]}));166expectError(execa('unicorns', {stdin: numberGenerator()}));167execa('unicorns', {stdin: 1});168execa('unicorns', {stdin: undefined});169execa('unicorns', {stdout: 'pipe'});170execa('unicorns', {stdout: 'overlapped'});
195 unmodified lines
modified:readme.md+3 added-1 removed
557 unmodified lines
558If the input is not a file, use the [`input` option](#input) instead.559560#### stdin561562Type: `string | number | Stream | undefined`\562Type: `string | number | Stream | undefined | Iterable<string | Uint8Array> | AsyncIterable<string | Uint8Array>`\563Default: `inherit` with [`$`](#command), `pipe` otherwise564565Same options as [`stdio`](https://nodejs.org/dist/latest-v6.x/docs/api/child_process.html#child_process_options_stdio).566567It can also be an [`Iterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol) or an [`AsyncIterable`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_async_iterator_and_async_iterable_protocols), providing neither [`execaSync()`](#execasyncfile-arguments-options), the [`input` option](#input) nor the [`inputFile` option](#inputfile) is used.568569#### stdout570571Type: `string | number | Stream | undefined`\572Default: `pipe`
241 unmodified lines