Simplify `lines` option (#929)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent 477bbc4 · Browse files · 15 files·+175 added−94 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+175 added−94 removed
- tests:+83 added−34 removed
- other:+92 added−60 removed
Provenance
- Commit
d30fcbc- Tree
fc5528e- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
477bbc4
15 files changed+175 added−94 removed
modified:docs/transform.md-2 removed
51 unmodified lines52 This is more efficient and recommended if the data is either:53 - Binary: Which does not have lines.54 - Text: But the transform works even if a line or word is split across multiple chunks.55 56-Please note the [`lines`](../readme.md#lines) option is unrelated: it has no impact on transforms.57-56 ## Newlines57 58 Unless [`{transform, binary: true}`](#binary-data) is used, the transform iterates over lines.59 By default, newlines are stripped from each `line` argument.142 unmodified linesmodified:lib/arguments/options.js+2 added-1 removed
6 unmodified lines7891011111213141543 unmodified lines59606162636465666756 unmodified lines6 unmodified linesimport {validateTimeout} from '../exit/timeout.js';import {logCommand} from '../verbose/start.js';import {getVerboseInfo} from '../verbose/info.js';import {getStartTime} from '../return/duration.js';import {validateEncoding} from './encoding.js';import {validateEncoding, BINARY_ENCODINGS} from './encoding.js';import {handleNodeOption} from './node.js';import {joinCommand} from './escape.js';import {normalizeCwd, safeNormalizeFileUrl, normalizeFileUrl} from './cwd.js';
43 unmodified lines validateEncoding(options); options.shell = normalizeFileUrl(options.shell); options.env = getEnv(options); options.forceKillAfterDelay = normalizeForceKillAfterDelay(options.forceKillAfterDelay); options.lines &&= !BINARY_ENCODINGS.has(options.encoding) && options.buffer;
if (process.platform === 'win32' && basename(file, '.exe') === 'cmd') { // #116 args.unshift('/q');56 unmodified linesmodified:lib/stdio/encoding-final.js+4 added-9 removed
12345656789107 unmodified lines1819202122222324252626272829303132282930316 unmodified linesimport {StringDecoder} from 'node:string_decoder';
// Apply the `encoding` option using an implicit generator.// This encodes the final output of `stdout`/`stderr`.export const handleStreamsEncoding = ({stdioItems, options: {encoding}, isSync, direction, optionName}) => { if (!shouldEncodeOutput({stdioItems, encoding, isSync, direction})) {export const handleStreamsEncoding = ({options: {encoding}, isSync, direction, optionName, objectMode}) => { if (!shouldEncodeOutput({encoding, isSync, direction, objectMode})) { return []; }
const stringDecoder = new StringDecoder(encoding);7 unmodified lines optionName, }];};
const shouldEncodeOutput = ({stdioItems, encoding, isSync, direction}) => direction === 'output'const shouldEncodeOutput = ({encoding, isSync, direction, objectMode}) => direction === 'output' && encoding !== 'utf8' && encoding !== 'buffer' && !isSync && !isWritableObjectMode(stdioItems); && !objectMode;
const isWritableObjectMode = stdioItems => { const lastObjectStdioItem = stdioItems.findLast(({type, value}) => type === 'generator' && value.objectMode !== undefined); return lastObjectStdioItem !== undefined && lastObjectStdioItem.value.objectMode;};
const encodingStringGenerator = function * (stringDecoder, chunk) { yield stringDecoder.write(chunk);};
6 unmodified linesmodified:lib/stdio/generator.js+17 added-4 removed
4 unmodified lines5 import {pipeStreams} from './pipeline.js';6 import {isGeneratorOptions, isAsyncGenerator} from './type.js';7 import {getValidateTransformReturn} from './validate.js';8 9-export const normalizeGenerators = (stdioItems, direction, {encoding}) => {10- const nonGenerators = stdioItems.filter(({type}) => type !== 'generator');11- const generators = stdioItems.filter(({type}) => type === 'generator');9+export const getObjectMode = (stdioItems, direction, options) => {10+ const generators = getGenerators(stdioItems, direction, options);11+ if (generators.length === 0) {12+ return false;13+ }14 15+ const {value: {readableObjectMode, writableObjectMode}} = generators.at(-1);16+ return direction === 'input' ? writableObjectMode : readableObjectMode;17+};18+19+export const normalizeGenerators = (stdioItems, direction, options) => [20+ ...stdioItems.filter(({type}) => type !== 'generator'),21+ ...getGenerators(stdioItems, direction, options),22+];23+24+const getGenerators = (stdioItems, direction, {encoding}) => {25+ const generators = stdioItems.filter(({type}) => type === 'generator');26 const newGenerators = Array.from({length: generators.length});27 28 for (const [index, stdioItem] of Object.entries(generators)) {29 newGenerators[index] = normalizeGenerator({stdioItem, index: Number(index), newGenerators, direction, encoding});30 }31 19- return [...nonGenerators, ...sortGenerators(newGenerators, direction)];32+ return sortGenerators(newGenerators, direction);33 };34 35 const normalizeGenerator = ({stdioItem, stdioItem: {value}, index, newGenerators, direction, encoding}) => {36 const {90 unmodified linesmodified:lib/stdio/handle.js+11 added-12 removed
4 unmodified lines5 import {handleNativeStream} from './native.js';6 import {handleInputOptions} from './input.js';7 import {handleStreamsLines} from './lines.js';8 import {handleStreamsEncoding} from './encoding-final.js';9-import {normalizeGenerators} from './generator.js';9+import {normalizeGenerators, getObjectMode} from './generator.js';10 import {forwardStdio, willPipeFileDescriptor} from './forward.js';11 12 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode13 export const handleInput = (addProperties, options, verboseInfo, isSync) => {8 unmodified lines22 // We make sure passing an array with a single item behaves the same as passing that item without an array.23 // This is what users would expect.24 // For example, `stdout: ['ignore']` behaves the same as `stdout: 'ignore'`.25 const getFileDescriptor = ({stdioOption, fdNumber, addProperties, options, isSync, stdioState, verboseInfo}) => {26+ const outputLines = [];27 const optionName = getOptionName(fdNumber);28 const stdioItems = initializeStdioItems(stdioOption, fdNumber, options, optionName);29 const direction = getStreamDirection(stdioItems, fdNumber, optionName);29- const normalizedStdioItems = normalizeStdioItems({stdioItems, fdNumber, optionName, addProperties, options, isSync, direction, stdioState, verboseInfo});30- return {fdNumber, direction, stdioItems: normalizedStdioItems};30+ const normalizedStdioItems = normalizeStdioItems({stdioItems, fdNumber, optionName, addProperties, options, isSync, direction, stdioState, verboseInfo, outputLines});31+ return {fdNumber, direction, outputLines, stdioItems: normalizedStdioItems};32 };33 34 const getOptionName = fdNumber => KNOWN_OPTION_NAMES[fdNumber] ?? `stdio[${fdNumber}]`;35 const KNOWN_OPTION_NAMES = ['stdin', 'stdout', 'stderr'];58 unmodified lines94 throw new TypeError(`The \`${optionName}: { file: '...' }\` option must be used instead of \`${optionName}: '...'\`.`);95 }96 };97 97-const normalizeStdioItems = ({stdioItems, fdNumber, optionName, addProperties, options, isSync, direction, stdioState, verboseInfo}) => {98- const allStdioItems = addInternalStdioItems({stdioItems, fdNumber, optionName, options, isSync, direction, stdioState, verboseInfo});98+const normalizeStdioItems = ({stdioItems, fdNumber, optionName, addProperties, options, isSync, direction, stdioState, verboseInfo, outputLines}) => {99+ const allStdioItems = addInternalStdioItems({stdioItems, fdNumber, optionName, options, isSync, direction, stdioState, verboseInfo, outputLines});100 const normalizedStdioItems = normalizeGenerators(allStdioItems, direction, options);101 return normalizedStdioItems.map(stdioItem => addStreamProperties(stdioItem, addProperties, direction));102 };103 103-const addInternalStdioItems = ({stdioItems, fdNumber, optionName, options, isSync, direction, stdioState, verboseInfo}) => {104+const addInternalStdioItems = ({stdioItems, fdNumber, optionName, options, isSync, direction, stdioState, verboseInfo, outputLines}) => {105 if (!willPipeFileDescriptor(stdioItems)) {106 return stdioItems;107 }108 108- const newStdioItems = [109+ const objectMode = getObjectMode(stdioItems, direction, options);110+ return [111 ...stdioItems,112 ...handleStreamsVerbose({stdioItems, options, isSync, stdioState, verboseInfo, fdNumber, optionName}),111- ...handleStreamsLines({options, isSync, direction, optionName}),113+ ...handleStreamsLines({options, isSync, direction, optionName, objectMode, outputLines}),114+ ...handleStreamsEncoding({options, isSync, direction, optionName, objectMode}),115 ];113- return [114- ...newStdioItems,115- ...handleStreamsEncoding({stdioItems: newStdioItems, options, isSync, direction, optionName}),116- ];116 };117 118 // Some `stdio` values require Execa to create streams.119 // For example, file paths create file read/write streams.5 unmodified linesmodified:lib/stdio/lines.js+17 added-7 removed
11234556788910111213131415151617181819192021222324252627282930import {BINARY_ENCODINGS} from '../arguments/encoding.js';import {MaxBufferError} from 'get-stream';import stripFinalNewlineFunction from 'strip-final-newline';
// Split chunks line-wise for streams exposed to users like `subprocess.stdout`.// Appending a noop transform in object mode is enough to do this, since every non-binary transform iterates line-wise.export const handleStreamsLines = ({options: {lines, encoding, stripFinalNewline}, isSync, direction, optionName}) => shouldSplitLines({lines, encoding, isSync, direction})export const handleStreamsLines = ({options: {lines, stripFinalNewline, maxBuffer}, isSync, direction, optionName, objectMode, outputLines}) => shouldSplitLines({lines, isSync, direction, objectMode}) ? [{ type: 'generator', value: {transform: linesEndGenerator, objectMode: true, preserveNewlines: !stripFinalNewline}, value: {transform: linesEndGenerator.bind(undefined, {outputLines, stripFinalNewline, maxBuffer}), preserveNewlines: true}, optionName, }] : [];
const shouldSplitLines = ({lines, encoding, isSync, direction}) => direction === 'output'const shouldSplitLines = ({lines, isSync, direction, objectMode}) => direction === 'output' && lines && !BINARY_ENCODINGS.has(encoding) && !objectMode && !isSync;
const linesEndGenerator = function * (chunk) { yield chunk;const linesEndGenerator = function * ({outputLines, stripFinalNewline, maxBuffer}, line) { if (outputLines.length >= maxBuffer) { const error = new MaxBufferError(); error.bufferedData = outputLines; throw error; }
const strippedLine = stripFinalNewline ? stripFinalNewlineFunction(line) : line; outputLines.push(strippedLine);
yield line;};modified:lib/stream/resolve.js+4 added-4 removed
10 unmodified lines11 12 // Retrieve result of subprocess: exit code, signal, error, streams (stdout/stderr/all)13 export const getSubprocessResult = async ({14 subprocess,15- options: {encoding, buffer, maxBuffer, timeoutDuration: timeout},15+ options: {encoding, buffer, maxBuffer, lines, timeoutDuration: timeout},16 context,17 fileDescriptors,18 originalStreams,19 controller,20 }) => {21 const exitPromise = waitForExit(subprocess);22 const streamInfo = {originalStreams, fileDescriptors, subprocess, exitPromise, propagating: false};23 24- const stdioPromises = waitForSubprocessStreams({subprocess, encoding, buffer, maxBuffer, streamInfo});24+ const stdioPromises = waitForSubprocessStreams({subprocess, encoding, buffer, maxBuffer, lines, streamInfo});25 const allPromise = waitForAllStream({subprocess, encoding, buffer, maxBuffer, streamInfo});26 const originalPromises = waitForOriginalStreams(originalStreams, subprocess, streamInfo);27 const customStreamsEndPromises = waitForCustomStreamsEnd(fileDescriptors, streamInfo);28 23 unmodified lines52 }53 };54 55 // Read the contents of `subprocess.std*` and|or wait for its completion56-const waitForSubprocessStreams = ({subprocess, encoding, buffer, maxBuffer, streamInfo}) =>57- subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({stream, subprocess, fdNumber, encoding, buffer, maxBuffer, streamInfo}));56+const waitForSubprocessStreams = ({subprocess, encoding, buffer, maxBuffer, lines, streamInfo}) =>57+ subprocess.stdio.map((stream, fdNumber) => waitForSubprocessStream({stream, subprocess, fdNumber, encoding, buffer, maxBuffer, lines, streamInfo}));58 59 // Transforms replace `subprocess.std*`, which means they are not exposed to users.60 // However, we still want to wait for their completion.61 const waitForOriginalStreams = (originalStreams, subprocess, streamInfo) =>23 unmodified linesmodified:lib/stream/subprocess.js+17 added-8 removed
1 import {setImmediate} from 'node:timers/promises';2 import getStream, {getStreamAsArrayBuffer, getStreamAsArray, MaxBufferError} from 'get-stream';3-import {waitForStream, handleStreamError, isInputFileDescriptor} from './wait.js';3+import {waitForStream, handleStreamError, isInputFileDescriptor, getFileDescriptor} from './wait.js';4 5-export const waitForSubprocessStream = async ({stream, subprocess, fdNumber, encoding, buffer, maxBuffer, streamInfo}) => {5+export const waitForSubprocessStream = async ({stream, subprocess, fdNumber, encoding, buffer, maxBuffer, lines, streamInfo}) => {6 if (!stream) {7 return;8 }9 10- if (isInputFileDescriptor(fdNumber, streamInfo.fileDescriptors)) {10+ if (isInputFileDescriptor(streamInfo, fdNumber)) {11 await waitForStream(stream, fdNumber, streamInfo);12 return;13 }14 5 unmodified lines20 return;21 }22 23 try {24- return await getAnyStream(stream, encoding, maxBuffer);24+ return await getAnyStream({stream, fdNumber, encoding, maxBuffer, lines, streamInfo});25 } catch (error) {26 if (error instanceof MaxBufferError) {27 subprocess.kill();28 }11 unmodified lines40 stream.resume();41 }42 };43 44-const getAnyStream = async (stream, encoding, maxBuffer) => {44+const getAnyStream = async ({stream, fdNumber, encoding, maxBuffer, lines, streamInfo}) => {45 if (stream.readableObjectMode) {46 return getStreamAsArray(stream, {maxBuffer});47 }48 49+ if (lines) {50+ return getOutputLines(stream, fdNumber, streamInfo);51+ }52+53 const contents = encoding === 'buffer'54 ? await getStreamAsArrayBuffer(stream, {maxBuffer})55 : await getStream(stream, {maxBuffer});56 return applyEncoding(contents, encoding);57 };58 59+const getOutputLines = async (stream, fdNumber, streamInfo) => {60+ await waitForStream(stream, fdNumber, streamInfo);61+ return getFileDescriptor(streamInfo, fdNumber).outputLines;62+};63+64 // On failure, `result.stdout|stderr|all` should contain the currently buffered stream65 // They are automatically closed and flushed by Node.js when the subprocess exits66 // When `buffer` is `false`, `streamPromise` is `undefined` and there is no buffered data to retrieve67 export const getBufferedData = async (streamPromise, encoding) => {3 unmodified lines71 return handleBufferedData(error, encoding);72 }73 };74 66-const handleBufferedData = (error, encoding) => error.bufferedData === undefined || Array.isArray(error.bufferedData)67- ? error.bufferedData68- : applyEncoding(error.bufferedData, encoding);75+const handleBufferedData = ({bufferedData}, encoding) => bufferedData === undefined || Array.isArray(bufferedData)76+ ? bufferedData77+ : applyEncoding(bufferedData, encoding);78 79 const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;modified:lib/stream/wait.js+4 added-4 removed
69 unmodified lines70 return isStreamEpipe(error) || isStreamAbort(error);71 }72 73 streamInfo.propagating = true;74- return isInputFileDescriptor(fdNumber, streamInfo.fileDescriptors) === isSameDirection74+ return isInputFileDescriptor(streamInfo, fdNumber) === isSameDirection75 ? isStreamEpipe(error)76 : isStreamAbort(error);77 };78 1 unmodified line80 // For example, `subprocess.stdin` is technically a Duplex, but can only be used as a writable.81 // Therefore, we need to use the file descriptor's direction (`stdin` is input, `stdout` is output, etc.).82 // However, while `subprocess.std*` and transforms follow that direction, any stream passed the `std*` option has the opposite direction.83 // For example, `subprocess.stdin` is a writable, but the `stdin` option is a readable.84-export const isInputFileDescriptor = (fdNumber, fileDescriptors) => fileDescriptors85- .find(fileDescriptor => fileDescriptor.fdNumber === fdNumber)86- .direction === 'input';84+export const isInputFileDescriptor = (streamInfo, fdNumber) => getFileDescriptor(streamInfo, fdNumber).direction === 'input';85 86+export const getFileDescriptor = ({fileDescriptors}, fdNumber) => fileDescriptors.find(fileDescriptor => fileDescriptor.fdNumber === fdNumber);87+88 // When `stream.destroy()` is called without an `error` argument, stream is aborted.89 // This is the only way to abort a readable stream, which can be useful in some instances.90 // Therefore, we ignore this error on readable streams.91 export const isStreamAbort = error => error?.code === 'ERR_STREAM_PREMATURE_CLOSE';7 unmodified linesmodified:test/convert/readable.js+4 added-3 removed
21 unmodified lines22 getReadableSubprocess,23 getReadWriteSubprocess,24 } from '../helpers/convert.js';25 import {foobarString, foobarBuffer, foobarObject} from '../helpers/input.js';26+import {simpleFull} from '../helpers/lines.js';27 import {prematureClose, fullStdio} from '../helpers/stdio.js';28 import {outputObjectGenerator, getChunksGenerator} from '../helpers/generator.js';29 import {defaultHighWaterMark, defaultObjectHighWaterMark} from '../helpers/stream.js';30 282 unmodified lines313 await text(stream);314 });315 316 test('.readable() can iterate over lines', async t => {316- const subprocess = execa('noop-fd.js', ['1', 'aaa\nbbb\nccc'], {lines: true});317+ const subprocess = execa('noop-fd.js', ['1', simpleFull]);318 const lines = [];318- for await (const line of subprocess.readable()) {319+ for await (const line of subprocess.readable({binary: false, preserveNewlines: false})) {320 lines.push(line);321 }322 323 const expectedLines = ['aaa', 'bbb', 'ccc'];324 t.deepEqual(lines, expectedLines);324- await assertSubprocessOutput(t, subprocess, expectedLines);325+ await assertSubprocessOutput(t, subprocess, simpleFull);326 });327 328 test('.readable() can wait for data', async t => {329 const subprocess = execa('noop.js', {stdout: getChunksGenerator([foobarString, foobarString], false, true)});127 unmodified linesmodified:test/stdio/lines.js+75 added-28 removed
1+import {Buffer} from 'node:buffer';2 import {once} from 'node:events';3 import {Writable} from 'node:stream';4 import test from 'ava';5+import {MaxBufferError} from 'get-stream';6 import {execa, execaSync} from '../../index.js';7 import {setFixtureDir} from '../helpers/fixtures-dir.js';8 import {fullStdio} from '../helpers/stdio.js';9 import {getChunksGenerator} from '../helpers/generator.js';8-import {foobarObject} from '../helpers/input.js';10+import {foobarString, foobarObject} from '../helpers/input.js';11+import {assertStreamOutput, assertIterableChunks} from '../helpers/convert.js';12 import {13 simpleFull,14 simpleChunks,15 simpleFullUint8Array,4 unmodified lines20 } from '../helpers/lines.js';21 22 setFixtureDir();23 24+const getSimpleChunkSubprocess = options => execa('noop-fd.js', ['1', simpleFull], {lines: true, ...options});25+26 // eslint-disable-next-line max-params27 const testStreamLines = async (t, fdNumber, input, expectedOutput, stripFinalNewline) => {28 const {stdio} = await execa('noop-fd.js', [`${fdNumber}`, input], {29 ...fullStdio,34 unmodified lines64 t.deepEqual(stdout, expectedLines);65 };66 67 test('"lines: true" works with strings generators', testStreamLinesGenerator, simpleChunks, simpleFullEndLines, false, false);63-test('"lines: true" works with strings generators, objectMode', testStreamLinesGenerator, simpleChunks, simpleChunks, true, false);68 test('"lines: true" works with strings generators, binary', testStreamLinesGenerator, simpleChunks, simpleLines, false, true);65-test('"lines: true" works with strings generators, binary, objectMode', testStreamLinesGenerator, simpleChunks, simpleChunks, true, true);69 test('"lines: true" works with big strings generators', testStreamLinesGenerator, [bigString], bigArray, false, false);67-test('"lines: true" works with big strings generators, objectMode', testStreamLinesGenerator, [bigString], [bigString], true, false);70 test('"lines: true" works with big strings generators without newlines', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false);71+test('"lines: true" is a noop with strings generators, objectMode', testStreamLinesGenerator, simpleChunks, simpleChunks, true, false);72+test('"lines: true" is a noop with strings generators, binary, objectMode', testStreamLinesGenerator, simpleChunks, simpleChunks, true, true);73+test('"lines: true" is a noop big strings generators, objectMode', testStreamLinesGenerator, [bigString], [bigString], true, false);69-test('"lines: true" works with big strings generators without newlines, objectMode', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false);74+test('"lines: true" is a noop big strings generators without newlines, objectMode', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false);75 76 test('"lines: true" is a noop with objects generators, objectMode', async t => {77 const {stdout} = await execa('noop.js', {78 stdout: getChunksGenerator([foobarObject], true),2 unmodified lines81 t.deepEqual(stdout, [foobarObject]);82 });83 84 const testOtherEncoding = async (t, expectedOutput, encoding, stripFinalNewline) => {80- const {stdout} = await execa('noop-fd.js', ['1', simpleFull], {lines: true, encoding, stripFinalNewline});85+ const {stdout} = await getSimpleChunkSubprocess({encoding, stripFinalNewline});86 t.deepEqual(stdout, expectedOutput);87 };88 89 test('"lines: true" is a noop with "encoding: buffer"', testOtherEncoding, simpleFullUint8Array, 'buffer', false);90 test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline', testOtherEncoding, simpleFullUint8Array, 'buffer', false);91 test('"lines: true" is a noop with "encoding: hex"', testOtherEncoding, simpleFullHex, 'hex', false);92 test('"lines: true" is a noop with "encoding: hex", stripFinalNewline', testOtherEncoding, simpleFullHex, 'hex', true);93 89-const getSimpleChunkSubprocess = (stripFinalNewline, options) => execa('noop-fd.js', ['1', ...simpleChunks], {90- lines: true,91- stripFinalNewline,92- ...options,94+test('"lines: true" is a noop with "buffer: false"', async t => {95+ const {stdout} = await getSimpleChunkSubprocess({buffer: false});96+ t.is(stdout, undefined);97 });98 95-const testAsyncIteration = async (t, expectedOutput, stripFinalNewline) => {96- const subprocess = getSimpleChunkSubprocess(stripFinalNewline);97- const [stdout] = await Promise.all([subprocess.stdout.toArray(), subprocess]);98- t.deepEqual(stdout, expectedOutput);99+test('"lines: true" can be below "maxBuffer"', async t => {100+ const maxBuffer = simpleLines.length;101+ const {stdout} = await getSimpleChunkSubprocess({maxBuffer});102+ t.deepEqual(stdout, noNewlinesChunks);103+});104+105+test('"lines: true" can be above "maxBuffer"', async t => {106+ const maxBuffer = simpleLines.length - 1;107+ const {cause, stdout} = await t.throwsAsync(getSimpleChunkSubprocess({maxBuffer}));108+ t.true(cause instanceof MaxBufferError);109+ t.deepEqual(stdout, noNewlinesChunks.slice(0, maxBuffer));110+});111+112+test('"lines: true" stops on stream error', async t => {113+ const cause = new Error(foobarString);114+ const error = await t.throwsAsync(getSimpleChunkSubprocess({115+ * stdout(line) {116+ if (line === noNewlinesChunks[2]) {117+ throw cause;118+ }119+120+ yield line;121+ },122+ }));123+ t.is(error.cause, cause);124+ t.deepEqual(error.stdout, noNewlinesChunks.slice(0, 2));125+});126+127+const testAsyncIteration = async (t, expectedLines, stripFinalNewline) => {128+ const subprocess = getSimpleChunkSubprocess({stripFinalNewline});129+ t.false(subprocess.stdout.readableObjectMode);130+ await assertStreamOutput(t, subprocess.stdout, simpleFull);131+ const {stdout} = await subprocess;132+ t.deepEqual(stdout, expectedLines);133 };134 101-test('"lines: true" works with stream async iteration, string', testAsyncIteration, simpleLines, false);102-test('"lines: true" works with stream async iteration, string, stripFinalNewline', testAsyncIteration, noNewlinesChunks, true);135+test('"lines: true" works with stream async iteration', testAsyncIteration, simpleLines, false);136+test('"lines: true" works with stream async iteration, stripFinalNewline', testAsyncIteration, noNewlinesChunks, true);137 104-const testDataEvents = async (t, [expectedFirstLine], stripFinalNewline) => {105- const subprocess = getSimpleChunkSubprocess(stripFinalNewline);106- const [[firstLine]] = await Promise.all([once(subprocess.stdout, 'data'), subprocess]);107- t.deepEqual(firstLine, expectedFirstLine);138+const testDataEvents = async (t, expectedLines, stripFinalNewline) => {139+ const subprocess = getSimpleChunkSubprocess({stripFinalNewline});140+ const [firstLine] = await once(subprocess.stdout, 'data');141+ t.deepEqual(firstLine, Buffer.from(simpleLines[0]));142+ const {stdout} = await subprocess;143+ t.deepEqual(stdout, expectedLines);144 };145 110-test('"lines: true" works with stream "data" events, string', testDataEvents, simpleLines, false);111-test('"lines: true" works with stream "data" events, string, stripFinalNewline', testDataEvents, noNewlinesChunks, true);146+test('"lines: true" works with stream "data" events', testDataEvents, simpleLines, false);147+test('"lines: true" works with stream "data" events, stripFinalNewline', testDataEvents, noNewlinesChunks, true);148 113-const testWritableStream = async (t, expectedOutput, stripFinalNewline) => {149+const testWritableStream = async (t, expectedLines, stripFinalNewline) => {150 const lines = [];151 const writable = new Writable({152 write(line, encoding, done) {117- lines.push(line);153+ lines.push(line.toString());154 done();155 },156 decodeStrings: false,157 });122- await getSimpleChunkSubprocess(stripFinalNewline, {stdout: ['pipe', writable]});123- t.deepEqual(lines, expectedOutput);158+ const {stdout} = await getSimpleChunkSubprocess({stripFinalNewline, stdout: ['pipe', writable]});159+ t.deepEqual(lines, simpleLines);160+ t.deepEqual(stdout, expectedLines);161 };162 126-test('"lines: true" works with writable streams targets, string', testWritableStream, simpleLines, false);127-test('"lines: true" works with writable streams targets, string, stripFinalNewline', testWritableStream, noNewlinesChunks, true);163+test('"lines: true" works with writable streams targets', testWritableStream, simpleLines, false);164+test('"lines: true" works with writable streams targets, stripFinalNewline', testWritableStream, noNewlinesChunks, true);165+166+const testIterable = async (t, expectedLines, stripFinalNewline) => {167+ const subprocess = getSimpleChunkSubprocess({stripFinalNewline});168+ await assertIterableChunks(t, subprocess, noNewlinesChunks);169+ const {stdout} = await subprocess;170+ t.deepEqual(stdout, expectedLines);171+};172+173+test('"lines: true" works with subprocess.iterable()', testIterable, simpleLines, false);174+test('"lines: true" works with subprocess.iterable(), stripFinalNewline', testIterable, noNewlinesChunks, true);modified:test/stream/max-buffer.js+4 added-3 removed
6 unmodified lines7 8 setFixtureDir();9 10 const maxBuffer = 10;11+const maxBufferMessage = /maxBuffer exceeded/;12 13 const testMaxBufferSuccess = async (t, fdNumber, all) => {14 await t.notThrowsAsync(execa('max-buffer.js', [`${fdNumber}`, `${maxBuffer}`], {...fullStdio, maxBuffer, all}));15 };5 unmodified lines21 22 test('maxBuffer uses killSignal', async t => {23 const {isTerminated, signal} = await t.throwsAsync(24 execa('noop-forever.js', ['.'.repeat(maxBuffer + 1)], {maxBuffer, killSignal: 'SIGINT'}),24- {message: /maxBuffer exceeded/},25+ {message: maxBufferMessage},26 );27 t.true(isTerminated);28 t.is(signal, 'SIGINT');29 });1 unmodified line31 const testMaxBufferLimit = async (t, fdNumber, all) => {32 const length = all ? maxBuffer * 2 : maxBuffer;33 const result = await t.throwsAsync(34 execa('max-buffer.js', [`${fdNumber}`, `${length + 1}`], {...fullStdio, maxBuffer, all}),34- {message: /maxBuffer exceeded/},35+ {message: maxBufferMessage},36 );37 t.is(all ? result.all : result.stdio[fdNumber], '.'.repeat(length));38 };39 58 unmodified lines98 99 const testMaxBufferAbort = async (t, fdNumber) => {100 const subprocess = execa('max-buffer.js', [`${fdNumber}`, `${maxBuffer + 1}`], {...fullStdio, maxBuffer});101 await Promise.all([101- t.throwsAsync(subprocess, {message: /maxBuffer exceeded/}),102+ t.throwsAsync(subprocess, {message: maxBufferMessage}),103 t.throwsAsync(getStream(subprocess.stdio[fdNumber]), {code: 'ERR_STREAM_PREMATURE_CLOSE'}),104 ]);105 };106 3 unmodified linesmodified:index.d.ts+4 added-5 removed
217 unmodified lines218 > = IsObjectResult extends true ? unknown[]219 : Encoding extends BufferEncodingOption220 ? Uint8Array221 : LinesOption extends true222+ ? Encoding extends BinaryEncodingOption223+ ? string222- ? string[]224+ : string[]225 : string;226 227 // Type of `result.all`228 type AllOutput<OptionsType extends Options = Options> = AllOutputProperty<OptionsType['all'], OptionsType>;173 unmodified lines402 */403 readonly stdio?: StdioOptions<IsSync>;404 405 /**404- Split `stdout` and `stderr` into lines.405- - `result.stdout`, `result.stderr`, `result.all` and `result.stdio` are arrays of lines.406- - `subprocess.stdout`, `subprocess.stderr`, `subprocess.all`, `subprocess.stdio`, `subprocess.readable()` and `subprocess.duplex()` iterate over lines instead of arbitrary chunks.407- - Any stream passed to the `stdout`, `stderr` or `stdio` option receives lines instead of arbitrary chunks.406+ Set `result.stdout`, `result.stderr`, `result.all` and `result.stdio` as arrays of strings, splitting the subprocess' output into lines.407 408 This cannot be used if the `encoding` option is binary.409 410 @default false1177 unmodified linesmodified:index.test-d.ts+11 added
451 unmodified lines452 expectType<Uint8Array>(linesBufferResult.stderr);453 expectType<Uint8Array>(linesBufferResult.stdio[2]);454 expectType<Uint8Array>(linesBufferResult.all);455 456+ const linesHexResult = await execa('unicorns', {lines: true, encoding: 'hex', all: true});457+ expectType<string>(linesHexResult.stdout);458+ expectType<string>(linesHexResult.stdio[1]);459+ expectType<string>(linesHexResult.stderr);460+ expectType<string>(linesHexResult.stdio[2]);461+ expectType<string>(linesHexResult.all);462+463 const noBufferPromise = execa('unicorns', {buffer: false, all: true});464 expectType<Writable>(noBufferPromise.stdin);465 expectType<Readable>(noBufferPromise.stdout);466 expectType<Readable>(noBufferPromise.stderr);195 unmodified lines662 663 const ignoreFd3Result = await execa('unicorns', {stdio: ['pipe', 'pipe', 'pipe', 'ignore']});664 expectType<undefined>(ignoreFd3Result.stdio[3]);665 666+ const objectTransformLinesStdoutResult = await execa('unicorns', {lines: true, stdout: {transform: objectGenerator, final: objectFinal, objectMode: true}});667+ expectType<unknown[]>(objectTransformLinesStdoutResult.stdout);668+ expectType<[undefined, unknown[], string[]]>(objectTransformLinesStdoutResult.stdio);669+670 const objectTransformStdoutResult = await execa('unicorns', {stdout: {transform: objectGenerator, final: objectFinal, objectMode: true}});671 expectType<unknown[]>(objectTransformStdoutResult.stdout);672 expectType<[undefined, unknown[], string]>(objectTransformStdoutResult.stdio);673 1126 unmodified linesmodified:readme.md+1 added-4 removed
942 unmodified lines943 944 Type: `boolean`\945 Default: `false`946 947-Split `stdout` and `stderr` into lines.948-- [`result.stdout`](#stdout), [`result.stderr`](#stderr), [`result.all`](#all-1) and [`result.stdio`](#stdio) are arrays of lines.949-- [`subprocess.stdout`](https://nodejs.org/api/child_process.html#subprocessstdout), [`subprocess.stderr`](https://nodejs.org/api/child_process.html#subprocessstderr), [`subprocess.all`](#all), [`subprocess.stdio`](https://nodejs.org/api/child_process.html#subprocessstdio), [`subprocess.readable()`](#readablereadableoptions) and [`subprocess.duplex`](#duplexduplexoptions) iterate over lines instead of arbitrary chunks.950-- Any stream passed to the [`stdout`](#stdout-1), [`stderr`](#stderr-1) or [`stdio`](#stdio-1) option receives lines instead of arbitrary chunks.947+Set [`result.stdout`](#stdout), [`result.stderr`](#stderr), [`result.all`](#all-1) and [`result.stdio`](#stdio) as arrays of strings, splitting the subprocess' output into lines.948 949 This cannot be used if the [`encoding` option](#encoding) is binary.950 951 #### encoding265 unmodified lines