Separate stream-related logic into their own file (#324)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by Sindre Sorhus · parent 97ef87d · Browse files · 4 files·+249 added−227 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+249 added−227 removed
- tests:+141 added−136 removed
- other:+108 added−91 removed
Provenance
- Commit
2b06e40- Tree
b1edb17- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
97ef87d
4 files changed+249 added−227 removed
added:lib/stream.js+105 added
1+const isStream = require('is-stream');2+const getStream = require('get-stream');3+const mergeStream = require('merge-stream');4+5+// `input` option6+const handleInput = (spawned, input) => {7+ // Checking for stdin is workaround for https://github.com/nodejs/node/issues/268528+ // TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.09+ if (input === undefined || spawned.stdin === undefined) {10+ return;11+ }12+13+ if (isStream(input)) {14+ input.pipe(spawned.stdin);15+ } else {16+ spawned.stdin.end(input);17+ }18+};19+20+// `all` interleaves `stdout` and `stderr`21+const makeAllStream = spawned => {22+ if (!spawned.stdout && !spawned.stderr) {23+ return;24+ }25+26+ const mixed = mergeStream();27+28+ if (spawned.stdout) {29+ mixed.add(spawned.stdout);30+ }31+32+ if (spawned.stderr) {33+ mixed.add(spawned.stderr);34+ }35+36+ return mixed;37+};38+39+// On failure, `result.stdout|stderr|all` should contain the currently buffered stream40+const getBufferedData = async (stream, streamPromise) => {41+ if (!stream) {42+ return;43+ }44+45+ stream.destroy();46+47+ try {48+ return await streamPromise;49+ } catch (error) {50+ return error.bufferedData;51+ }52+};53+54+const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {55+ if (!stream) {56+ return;57+ }58+59+ if (!buffer) {60+ // TODO: Use `ret = util.promisify(stream.finished)(stream);` when targeting Node.js 1061+ return new Promise((resolve, reject) => {62+ stream63+ .once('end', resolve)64+ .once('error', reject);65+ });66+ }67+68+ if (encoding) {69+ return getStream(stream, {encoding, maxBuffer});70+ }71+72+ return getStream.buffer(stream, {maxBuffer});73+};74+75+// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)76+const getSpawnedResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {77+ const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});78+ const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});79+ const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});80+81+ try {82+ return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);83+ } catch (error) {84+ return Promise.all([85+ {error, code: error.code, signal: error.signal},86+ getBufferedData(stdout, stdoutPromise),87+ getBufferedData(stderr, stderrPromise),88+ getBufferedData(all, allPromise)89+ ]);90+ }91+};92+93+const validateInputSync = ({input}) => {94+ if (isStream(input)) {95+ throw new TypeError('The `input` option cannot be a stream in sync mode');96+ }97+};98+99+module.exports = {100+ handleInput,101+ makeAllStream,102+ getSpawnedResult,103+ validateInputSync104+};105+added:test/stream.js+141 added
1+import path from 'path';2+import fs from 'fs';3+import stream from 'stream';4+import test from 'ava';5+import getStream from 'get-stream';6+import tempfile from 'tempfile';7+import execa from '..';8+9+process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;10+11+test('buffer', async t => {12+ const {stdout} = await execa('noop', ['foo'], {encoding: null});13+ t.true(Buffer.isBuffer(stdout));14+ t.is(stdout.toString(), 'foo');15+});16+17+test('pass `stdout` to a file descriptor', async t => {18+ const file = tempfile('.txt');19+ await execa('test/fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});20+ t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');21+});22+23+test('pass `stderr` to a file descriptor', async t => {24+ const file = tempfile('.txt');25+ await execa('test/fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});26+ t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');27+});28+29+test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {30+ const {all} = await execa('noop-132');31+ t.is(all, '132');32+});33+34+test('stdout/stderr/all are undefined if ignored', async t => {35+ const {stdout, stderr, all} = await execa('noop', {stdio: 'ignore'});36+ t.is(stdout, undefined);37+ t.is(stderr, undefined);38+ t.is(all, undefined);39+});40+41+test('stdout/stderr/all are undefined if ignored in sync mode', t => {42+ const {stdout, stderr, all} = execa.sync('noop', {stdio: 'ignore'});43+ t.is(stdout, undefined);44+ t.is(stderr, undefined);45+ t.is(all, undefined);46+});47+48+test('input option can be a String', async t => {49+ const {stdout} = await execa('stdin', {input: 'foobar'});50+ t.is(stdout, 'foobar');51+});52+53+test('input option can be a Buffer', async t => {54+ const {stdout} = await execa('stdin', {input: 'testing12'});55+ t.is(stdout, 'testing12');56+});57+58+test('input can be a Stream', async t => {59+ const s = new stream.PassThrough();60+ s.write('howdy');61+ s.end();62+ const {stdout} = await execa('stdin', {input: s});63+ t.is(stdout, 'howdy');64+});65+66+test('you can write to child.stdin', async t => {67+ const child = execa('stdin');68+ child.stdin.end('unicorns');69+ t.is((await child).stdout, 'unicorns');70+});71+72+test('input option can be a String - sync', t => {73+ const {stdout} = execa.sync('stdin', {input: 'foobar'});74+ t.is(stdout, 'foobar');75+});76+77+test('input option can be a Buffer - sync', t => {78+ const {stdout} = execa.sync('stdin', {input: Buffer.from('testing12', 'utf8')});79+ t.is(stdout, 'testing12');80+});81+82+test('opts.stdout:ignore - stdout will not collect data', async t => {83+ const {stdout} = await execa('stdin', {84+ input: 'hello',85+ stdio: [undefined, 'ignore', undefined]86+ });87+ t.is(stdout, undefined);88+});89+90+test('helpful error trying to provide an input stream in sync mode', t => {91+ t.throws(92+ () => {93+ execa.sync('stdin', {input: new stream.PassThrough()});94+ },95+ /The `input` option cannot be a stream in sync mode/96+ );97+});98+99+test('maxBuffer affects stdout', async t => {100+ await t.notThrowsAsync(execa('max-buffer', ['stdout', '10'], {maxBuffer: 10}));101+ const {stdout, all} = await t.throwsAsync(execa('max-buffer', ['stdout', '11'], {maxBuffer: 10}), /max-buffer stdout/);102+ t.is(stdout, '.'.repeat(10));103+ t.is(all, '.'.repeat(10));104+});105+106+test('maxBuffer affects stderr', async t => {107+ await t.notThrowsAsync(execa('max-buffer', ['stderr', '10'], {maxBuffer: 10}));108+ const {stderr, all} = await t.throwsAsync(execa('max-buffer', ['stderr', '11'], {maxBuffer: 10}), /max-buffer stderr/);109+ t.is(stderr, '.'.repeat(10));110+ t.is(all, '.'.repeat(10));111+});112+113+test('do not buffer stdout when `buffer` set to `false`', async t => {114+ const promise = execa('max-buffer', ['stdout', '10'], {buffer: false});115+ const [result, stdout] = await Promise.all([116+ promise,117+ getStream(promise.stdout),118+ getStream(promise.all)119+ ]);120+121+ t.is(result.stdout, undefined);122+ t.is(stdout, '.........\n');123+});124+125+test('do not buffer stderr when `buffer` set to `false`', async t => {126+ const promise = execa('max-buffer', ['stderr', '10'], {buffer: false});127+ const [result, stderr] = await Promise.all([128+ promise,129+ getStream(promise.stderr),130+ getStream(promise.all)131+ ]);132+133+ t.is(result.stderr, undefined);134+ t.is(stderr, '.........\n');135+});136+137+test('do not buffer when streaming', async t => {138+ const {stdout} = execa('max-buffer', ['stdout', '21'], {maxBuffer: 10});139+ const result = await getStream(stdout);140+ t.is(result, '....................\n');141+});modified:test/test.js-136 removed
1 import path from 'path';2-import fs from 'fs';3-import stream from 'stream';2 import test from 'ava';5-import getStream from 'get-stream';3 import isRunning from 'is-running';7-import tempfile from 'tempfile';4 import execa from '..';5 6 process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;7 process.env.FOO = 'foo';16 unmodified lines24 t.is(stdout, 'Hello World');25 });26 }27 32-test('buffer', async t => {33- const {stdout} = await execa('noop', ['foo'], {encoding: null});34- t.true(Buffer.isBuffer(stdout));35- t.is(stdout.toString(), 'foo');36-});37-38-test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {39- const {all} = await execa('noop-132');40- t.is(all, '132');41-});42-43-test('stdout/stderr/all are undefined if ignored', async t => {44- const {stdout, stderr, all} = await execa('noop', {stdio: 'ignore'});45- t.is(stdout, undefined);46- t.is(stderr, undefined);47- t.is(all, undefined);48-});49-50-test('stdout/stderr/all are undefined if ignored in sync mode', t => {51- const {stdout, stderr, all} = execa.sync('noop', {stdio: 'ignore'});52- t.is(stdout, undefined);53- t.is(stderr, undefined);54- t.is(all, undefined);55-});56-57-test('pass `stdout` to a file descriptor', async t => {58- const file = tempfile('.txt');59- await execa('test/fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});60- t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');61-});62-63-test('pass `stderr` to a file descriptor', async t => {64- const file = tempfile('.txt');65- await execa('test/fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});66- t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');67-});68-28 test('execa.sync()', t => {29 const {stdout} = execa.sync('noop', ['foo']);30 t.is(stdout, 'foo');31 });61 unmodified lines93 );94 t.true(envPaths.some(envPath => envPath === '/test/node_modules/.bin'));95 });96 138-test('input option can be a String', async t => {139- const {stdout} = await execa('stdin', {input: 'foobar'});140- t.is(stdout, 'foobar');141-});142-143-test('input option can be a Buffer', async t => {144- const {stdout} = await execa('stdin', {input: 'testing12'});145- t.is(stdout, 'testing12');146-});147-148-test('input can be a Stream', async t => {149- const s = new stream.PassThrough();150- s.write('howdy');151- s.end();152- const {stdout} = await execa('stdin', {input: s});153- t.is(stdout, 'howdy');154-});155-156-test('you can write to child.stdin', async t => {157- const child = execa('stdin');158- child.stdin.end('unicorns');159- t.is((await child).stdout, 'unicorns');160-});161-162-test('input option can be a String - sync', t => {163- const {stdout} = execa.sync('stdin', {input: 'foobar'});164- t.is(stdout, 'foobar');165-});166-167-test('input option can be a Buffer - sync', t => {168- const {stdout} = execa.sync('stdin', {input: Buffer.from('testing12', 'utf8')});169- t.is(stdout, 'testing12');170-});171-97 test('stdin errors are handled', async t => {98 const child = execa('noop');99 child.stdin.emit('error', new Error('test'));100 await t.throwsAsync(child, /test/);4 unmodified lines105 child.emit('error', new Error('test'));106 await t.throwsAsync(child, /test/);107 });108 184-test('opts.stdout:ignore - stdout will not collect data', async t => {185- const {stdout} = await execa('stdin', {186- input: 'hello',187- stdio: [undefined, 'ignore', undefined]188- });189- t.is(stdout, undefined);190-});191-192-test('helpful error trying to provide an input stream in sync mode', t => {193- t.throws(194- () => {195- execa.sync('stdin', {input: new stream.PassThrough()});196- },197- /The `input` option cannot be a stream in sync mode/198- );199-});200-109 test('child process errors rejects promise right away', async t => {110 const child = execa('forever');111 child.emit('error', new Error('test'));112 await t.throwsAsync(child, /test/);24 unmodified lines137 });138 t.true(failed);139 });140 233-test('maxBuffer affects stdout', async t => {234- await t.notThrowsAsync(execa('max-buffer', ['stdout', '10'], {maxBuffer: 10}));235- const {stdout, all} = await t.throwsAsync(execa('max-buffer', ['stdout', '11'], {maxBuffer: 10}), /max-buffer stdout/);236- t.is(stdout, '.'.repeat(10));237- t.is(all, '.'.repeat(10));238-});239-240-test('maxBuffer affects stderr', async t => {241- await t.notThrowsAsync(execa('max-buffer', ['stderr', '10'], {maxBuffer: 10}));242- const {stderr, all} = await t.throwsAsync(execa('max-buffer', ['stderr', '11'], {maxBuffer: 10}), /max-buffer stderr/);243- t.is(stderr, '.'.repeat(10));244- t.is(all, '.'.repeat(10));245-});246-247-test('do not buffer stdout when `buffer` set to `false`', async t => {248- const promise = execa('max-buffer', ['stdout', '10'], {buffer: false});249- const [result, stdout] = await Promise.all([250- promise,251- getStream(promise.stdout),252- getStream(promise.all)253- ]);254-255- t.is(result.stdout, undefined);256- t.is(stdout, '.........\n');257-});258-259-test('do not buffer stderr when `buffer` set to `false`', async t => {260- const promise = execa('max-buffer', ['stderr', '10'], {buffer: false});261- const [result, stderr] = await Promise.all([262- promise,263- getStream(promise.stderr),264- getStream(promise.all)265- ]);266-267- t.is(result.stderr, undefined);268- t.is(stderr, '.........\n');269-});270-141 test('use relative path with \'..\' chars', async t => {142 const pathViaParentDir = path.join('..', path.basename(path.dirname(__dirname)), 'test', 'fixtures', 'noop');143 const {stdout} = await execa(pathViaParentDir, ['foo']);144 t.is(stdout, 'foo');70 unmodified lines215 t.is(stdout, 'test');216 delete process.env.TEST;217 });218 349-test('do not buffer when streaming', async t => {350- const {stdout} = execa('max-buffer', ['stdout', '21'], {maxBuffer: 10});351- const result = await getStream(stdout);352- t.is(result, '....................\n');353-});354-219 test('detach child process', async t => {220 const {stdout} = await execa('detach');221 const pid = Number(stdout);222 t.true(Number.isInteger(pid));96 unmodified linesmodified:index.js+3 added-91 removed
2 unmodified lines3 const childProcess = require('child_process');4 const crossSpawn = require('cross-spawn');5 const stripFinalNewline = require('strip-final-newline');6 const npmRunPath = require('npm-run-path');7-const isStream = require('is-stream');8-const getStream = require('get-stream');9-const mergeStream = require('merge-stream');7 const pFinally = require('p-finally');8 const makeError = require('./lib/error');9 const normalizeStdio = require('./lib/stdio');10 const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler, cleanup} = require('./lib/kill');11+const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = require('./lib/stream.js');12 13 const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;14 15 const SPACES_REGEXP = / +/g;40 unmodified lines56 57 return {file, args, options, parsed};58 };59 62-const handleInput = (spawned, input) => {63- // Checking for stdin is workaround for https://github.com/nodejs/node/issues/2685264- // TODO: Remove `|| spawned.stdin === undefined` once we drop support for Node.js <=12.2.065- if (input === undefined || spawned.stdin === undefined) {66- return;67- }68-69- if (isStream(input)) {70- input.pipe(spawned.stdin);71- } else {72- spawned.stdin.end(input);73- }74-};75-60 const handleOutput = (options, value, error) => {61 if (typeof value !== 'string' && !Buffer.isBuffer(value)) {62 // When `execa.sync()` errors, we normalize it to '' to mimic `execa()`63 return error === undefined ? undefined : '';5 unmodified lines69 70 return value;71 };72 89-const makeAllStream = spawned => {90- if (!spawned.stdout && !spawned.stderr) {91- return;92- }93-94- const mixed = mergeStream();95-96- if (spawned.stdout) {97- mixed.add(spawned.stdout);98- }99-100- if (spawned.stderr) {101- mixed.add(spawned.stderr);102- }103-104- return mixed;105-};106-107-const getBufferedData = async (stream, streamPromise) => {108- if (!stream) {109- return;110- }111-112- stream.destroy();113-114- try {115- return await streamPromise;116- } catch (error) {117- return error.bufferedData;118- }119-};120-121-const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {122- if (!stream) {123- return;124- }125-126- if (!buffer) {127- // TODO: Use `ret = util.promisify(stream.finished)(stream);` when targeting Node.js 10128- return new Promise((resolve, reject) => {129- stream130- .once('end', resolve)131- .once('error', reject);132- });133- }134-135- if (encoding) {136- return getStream(stream, {encoding, maxBuffer});137- }138-139- return getStream.buffer(stream, {maxBuffer});140-};141-142-const getPromiseResult = async ({stdout, stderr, all}, {encoding, buffer, maxBuffer}, processDone) => {143- const stdoutPromise = getStreamPromise(stdout, {encoding, buffer, maxBuffer});144- const stderrPromise = getStreamPromise(stderr, {encoding, buffer, maxBuffer});145- const allPromise = getStreamPromise(all, {encoding, buffer, maxBuffer: maxBuffer * 2});146-147- try {148- return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);149- } catch (error) {150- return Promise.all([151- {error, code: error.code, signal: error.signal},152- getBufferedData(stdout, stdoutPromise),153- getBufferedData(stderr, stderrPromise),154- getBufferedData(all, allPromise)155- ]);156- }157-};158-73 const joinCommand = (file, args = []) => {74 if (!Array.isArray(args)) {75 return file;76 }84 unmodified lines161 cleanup(timeoutId, removeExitHandler);162 });163 164 const handlePromise = async () => {251- const [result, stdout, stderr, all] = await getPromiseResult(spawned, parsed.options, processDone);165+ const [result, stdout, stderr, all] = await getSpawnedResult(spawned, parsed.options, processDone);166 result.stdout = handleOutput(parsed.options, stdout);167 result.stderr = handleOutput(parsed.options, stderr);168 result.all = handleOutput(parsed.options, all);169 42 unmodified lines212 module.exports.sync = (file, args, options) => {213 const parsed = handleArgs(file, args, options);214 const command = joinCommand(file, args);215 302- if (isStream(parsed.options.input)) {303- throw new TypeError('The `input` option cannot be a stream in sync mode');304- }216+ validateInputSync(parsed.options);217 218 let result;219 try {220 result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);107 unmodified lines