Skip to content
Myr

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

4 files+249 added−227 removed

added:lib/stream.js+105 added
1const isStream = require('is-stream');2const getStream = require('get-stream');3const mergeStream = require('merge-stream');45// `input` option6const 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 }1213 if (isStream(input)) {14 input.pipe(spawned.stdin);15 } else {16 spawned.stdin.end(input);17 }18};1920// `all` interleaves `stdout` and `stderr`21const makeAllStream = spawned => {22 if (!spawned.stdout && !spawned.stderr) {23 return;24 }2526 const mixed = mergeStream();2728 if (spawned.stdout) {29 mixed.add(spawned.stdout);30 }3132 if (spawned.stderr) {33 mixed.add(spawned.stderr);34 }3536 return mixed;37};3839// On failure, `result.stdout|stderr|all` should contain the currently buffered stream40const getBufferedData = async (stream, streamPromise) => {41 if (!stream) {42 return;43 }4445 stream.destroy();4647 try {48 return await streamPromise;49 } catch (error) {50 return error.bufferedData;51 }52};5354const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {55 if (!stream) {56 return;57 }5859 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 }6768 if (encoding) {69 return getStream(stream, {encoding, maxBuffer});70 }7172 return getStream.buffer(stream, {maxBuffer});73};7475// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)76const 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});8081 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};9293const validateInputSync = ({input}) => {94 if (isStream(input)) {95 throw new TypeError('The `input` option cannot be a stream in sync mode');96 }97};9899module.exports = {100 handleInput,101 makeAllStream,102 getSpawnedResult,103 validateInputSync104};105
added:test/stream.js+141 added
1import path from 'path';2import fs from 'fs';3import stream from 'stream';4import test from 'ava';5import getStream from 'get-stream';6import tempfile from 'tempfile';7import execa from '..';89process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;1011test('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});1617test('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});2223test('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});2829test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {30 const {all} = await execa('noop-132');31 t.is(all, '132');32});3334test('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});4041test('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});4748test('input option can be a String', async t => {49 const {stdout} = await execa('stdin', {input: 'foobar'});50 t.is(stdout, 'foobar');51});5253test('input option can be a Buffer', async t => {54 const {stdout} = await execa('stdin', {input: 'testing12'});55 t.is(stdout, 'testing12');56});5758test('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});6566test('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});7172test('input option can be a String - sync', t => {73 const {stdout} = execa.sync('stdin', {input: 'foobar'});74 t.is(stdout, 'foobar');75});7677test('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});8182test('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});8990test('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});9899test('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});105106test('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});112113test('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 ]);120121 t.is(result.stdout, undefined);122 t.is(stdout, '.........\n');123});124125test('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 ]);132133 t.is(result.stderr, undefined);134 t.is(stderr, '.........\n');135});136137test('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
1import path from 'path';2import fs from 'fs';3import stream from 'stream';2import test from 'ava';5import getStream from 'get-stream';3import isRunning from 'is-running';7import tempfile from 'tempfile';4import execa from '..';56process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;7process.env.FOO = 'foo';
16 unmodified lines
24 t.is(stdout, 'Hello World');25 });26}2732test('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});3738test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {39 const {all} = await execa('noop-132');40 t.is(all, '132');41});4243test('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});4950test('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});5657test('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});6263test('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});6828test('execa.sync()', t => {29 const {stdout} = execa.sync('noop', ['foo']);30 t.is(stdout, 'foo');31});
61 unmodified lines
93 );94 t.true(envPaths.some(envPath => envPath === '/test/node_modules/.bin'));95});96138test('input option can be a String', async t => {139 const {stdout} = await execa('stdin', {input: 'foobar'});140 t.is(stdout, 'foobar');141});142143test('input option can be a Buffer', async t => {144 const {stdout} = await execa('stdin', {input: 'testing12'});145 t.is(stdout, 'testing12');146});147148test('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});155156test('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});161162test('input option can be a String - sync', t => {163 const {stdout} = execa.sync('stdin', {input: 'foobar'});164 t.is(stdout, 'foobar');165});166167test('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});17197test('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 lines
105 child.emit('error', new Error('test'));106 await t.throwsAsync(child, /test/);107});108184test('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});191192test('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});200109test('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 lines
137 });138 t.true(failed);139});140233test('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});239240test('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});246247test('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 ]);254255 t.is(result.stdout, undefined);256 t.is(stdout, '.........\n');257});258259test('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 ]);266267 t.is(result.stderr, undefined);268 t.is(stderr, '.........\n');269});270141test('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 lines
215 t.is(stdout, 'test');216 delete process.env.TEST;217});218349test('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});354219test('detach child process', async t => {220 const {stdout} = await execa('detach');221 const pid = Number(stdout);222 t.true(Number.isInteger(pid));
96 unmodified lines
modified:index.js+3 added-91 removed
2 unmodified lines
3const childProcess = require('child_process');4const crossSpawn = require('cross-spawn');5const stripFinalNewline = require('strip-final-newline');6const npmRunPath = require('npm-run-path');7const isStream = require('is-stream');8const getStream = require('get-stream');9const mergeStream = require('merge-stream');7const pFinally = require('p-finally');8const makeError = require('./lib/error');9const normalizeStdio = require('./lib/stdio');10const {spawnedKill, spawnedCancel, setupTimeout, setExitHandler, cleanup} = require('./lib/kill');11const {handleInput, getSpawnedResult, makeAllStream, validateInputSync} = require('./lib/stream.js');1213const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;1415const SPACES_REGEXP = / +/g;
40 unmodified lines
5657 return {file, args, options, parsed};58};5962const 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 }6869 if (isStream(input)) {70 input.pipe(spawned.stdin);71 } else {72 spawned.stdin.end(input);73 }74};7560const 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 lines
6970 return value;71};7289const makeAllStream = spawned => {90 if (!spawned.stdout && !spawned.stderr) {91 return;92 }9394 const mixed = mergeStream();9596 if (spawned.stdout) {97 mixed.add(spawned.stdout);98 }99100 if (spawned.stderr) {101 mixed.add(spawned.stderr);102 }103104 return mixed;105};106107const getBufferedData = async (stream, streamPromise) => {108 if (!stream) {109 return;110 }111112 stream.destroy();113114 try {115 return await streamPromise;116 } catch (error) {117 return error.bufferedData;118 }119};120121const getStreamPromise = (stream, {encoding, buffer, maxBuffer}) => {122 if (!stream) {123 return;124 }125126 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 }134135 if (encoding) {136 return getStream(stream, {encoding, maxBuffer});137 }138139 return getStream.buffer(stream, {maxBuffer});140};141142const 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});146147 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};15873const joinCommand = (file, args = []) => {74 if (!Array.isArray(args)) {75 return file;76 }
84 unmodified lines
161 cleanup(timeoutId, removeExitHandler);162 });163164 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 lines
212module.exports.sync = (file, args, options) => {213 const parsed = handleArgs(file, args, options);214 const command = joinCommand(file, args);215302 if (isStream(parsed.options.input)) {303 throw new TypeError('The `input` option cannot be a stream in sync mode');304 }216 validateInputSync(parsed.options);217218 let result;219 try {220 result = childProcess.spawnSync(parsed.file, parsed.args, parsed.options);
107 unmodified lines