Fix `encoding` option (#696)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by ehmicky · committed by GitHub · parent e8f6bbd · Browse files · 8 files·+73 added−27 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+73 added−27 removed
- tests:+33 added−2 removed
- other:+40 added−25 removed
Provenance
- Commit
b6f9fa2- Tree
5365fdf- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
e8f6bbd
8 files changed+73 added−27 removed
modified:lib/stdio/async.js+1 added-1 removed
5 unmodified lines678910101112131458 unmodified lines5 unmodified linesimport {TYPE_TO_MESSAGE} from './type.js';import {generatorToTransformStream, pipeGenerator} from './generator.js';
// Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async modeexport const handleInputAsync = options => handleInput(addPropertiesAsync, options);export const handleInputAsync = options => handleInput(addPropertiesAsync, options, false);
const forbiddenIfAsync = ({type, optionName}) => { throw new TypeError(`The \`${optionName}\` option cannot be ${TYPE_TO_MESSAGE[type]}.`);};58 unmodified linesadded:lib/stdio/encoding.js+27 added
123456789101112131415161718192021222324252627import {StringDecoder} from 'node:string_decoder';
// Apply the `encoding` option using an implicit generator.export const handleStreamsEncoding = (stdioStreams, {encoding}, isSync) => { if (stdioStreams[0].direction === 'input' || IGNORED_ENCODINGS.has(encoding) || isSync) { return stdioStreams.map(stdioStream => ({...stdioStream, encoding})); }
const value = encodingEndGenerator.bind(undefined, encoding); return [...stdioStreams, {...stdioStreams[0], type: 'generator', value, encoding: 'buffer'}];};
// eslint-disable-next-line unicorn/text-encoding-identifier-caseconst IGNORED_ENCODINGS = new Set(['utf8', 'utf-8', 'buffer']);
const encodingEndGenerator = async function * (encoding, chunks) { const stringDecoder = new StringDecoder(encoding);
for await (const chunk of chunks) { yield stringDecoder.write(chunk); }
const lastChunk = stringDecoder.end(); if (lastChunk !== '') { yield lastChunk; }};modified:lib/stdio/generator.js+1 added-1 removed
24 unmodified lines2526272829293031323376 unmodified lines24 unmodified lines Those convert the chunk type from `Buffer` to `string | Uint8Array` depending on the encoding option.- This new iterable is transformed again to another one, this time by applying the user-supplied generator.- Finally, `Readable.from()` is used to convert this final iterable to a `Readable` stream.*/export const generatorToTransformStream = ({value}, {encoding}) => {export const generatorToTransformStream = ({value, encoding}) => { const objectMode = false; const highWaterMark = getDefaultHighWaterMark(objectMode); const passThrough = new PassThrough({objectMode, highWaterMark, destroy: destroyPassThrough}); const iterable = passThrough.iterator();76 unmodified linesmodified:lib/stdio/handle.js+6 added-4 removed
1 unmodified line2 import {addStreamDirection} from './direction.js';3 import {normalizeStdio} from './normalize.js';4 import {handleNativeStream} from './native.js';5 import {handleInputOptions} from './input.js';6+import {handleStreamsEncoding} from './encoding.js';7 8 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in async/sync mode8-export const handleInput = (addProperties, options) => {9+export const handleInput = (addProperties, options, isSync) => {10 const stdio = normalizeStdio(options);11 const [stdinStreams, ...otherStreamsGroups] = stdio.map((stdioOption, index) => getStdioStreams(stdioOption, index));12 const stdioStreamsGroups = [[...stdinStreams, ...handleInputOptions(options)], ...otherStreamsGroups]13 .map(stdioStreams => validateStreams(stdioStreams))14 .map(stdioStreams => addStreamDirection(stdioStreams))15+ .map(stdioStreams => handleStreamsEncoding(stdioStreams, options, isSync))14- .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties, options));16+ .map(stdioStreams => addStreamsProperties(stdioStreams, addProperties));17 options.stdio = transformStdio(stdioStreamsGroups);18 return stdioStreamsGroups;19 };20 58 unmodified lines79 80 // Some `stdio` values require Execa to create streams.81 // For example, file paths create file read/write streams.82 // Those transformations are specified in `addProperties`, which is both direction-specific and type-specific.81-const addStreamsProperties = (stdioStreams, addProperties, options) => stdioStreams.map(stdioStream => ({83+const addStreamsProperties = (stdioStreams, addProperties) => stdioStreams.map(stdioStream => ({84 ...stdioStream,83- ...addProperties[stdioStream.direction][stdioStream.type]?.(stdioStream, options),85+ ...addProperties[stdioStream.direction][stdioStream.type]?.(stdioStream),86 }));87 88 // When the `std*: Iterable | WebStream | URL | filePath`, `input` or `inputFile` option is used, we pipe to `spawned.std*`.89 // When the `std*: Array` option is used, we emulate some of the native values ('inherit', Node.js stream and file descriptor integer). To do so, we also need to pipe to `spawned.std*`.11 unmodified linesmodified:lib/stdio/sync.js+1 added-1 removed
4 unmodified lines5 import {bufferToUint8Array} from './utils.js';6 7 // Handle `input`, `inputFile`, `stdin`, `stdout` and `stderr` options, before spawning, in sync mode8 export const handleInputSync = options => {9- const stdioStreamsGroups = handleInput(addPropertiesSync, options);9+ const stdioStreamsGroups = handleInput(addPropertiesSync, options, true);10 addInputOptionSync(stdioStreamsGroups, options);11 return stdioStreamsGroups;12 };13 68 unmodified linesmodified:lib/stream.js+4 added-18 removed
1-import {Buffer} from 'node:buffer';1 import {once} from 'node:events';2 import {finished} from 'node:stream/promises';3 import getStream, {getStreamAsArrayBuffer} from 'get-stream';4 import mergeStreams from '@sindresorhus/merge-streams';37 unmodified lines42 if (!stream || !buffer) {43 return;44 }45 47- const contents = isUtf8Encoding(encoding)48- ? await getStream(stream, {maxBuffer})49- : await getStreamAsArrayBuffer(stream, {maxBuffer});46+ const contents = encoding === 'buffer'47+ ? await getStreamAsArrayBuffer(stream, {maxBuffer})48+ : await getStream(stream, {maxBuffer});49 return applyEncoding(contents, encoding);50 };51 53-const applyEncoding = (contents, encoding) => {54- if (isUtf8Encoding(encoding)) {55- return contents;56- }52+const applyEncoding = (contents, encoding) => encoding === 'buffer' ? new Uint8Array(contents) : contents;53 58- if (encoding === 'buffer') {59- return new Uint8Array(contents);60- }61-62- return Buffer.from(contents).toString(encoding);63-};64-65-// eslint-disable-next-line unicorn/text-encoding-identifier-case66-const isUtf8Encoding = encoding => encoding === 'utf8' || encoding === 'utf-8';67-54 // Retrieve streams created by the `std*` options55 const getCustomStreams = stdioStreamsGroups => stdioStreamsGroups.flat().filter(({type}) => type !== 'native');56 57 // Some `stdout`/`stderr` options create a stream, e.g. when passing a file path.77 unmodified linesmodified:test/encoding.js+30 added
1 import {Buffer} from 'node:buffer';2 import {exec} from 'node:child_process';3+import {setTimeout} from 'node:timers/promises';4 import {promisify} from 'node:util';5 import test from 'ava';6+import getStream, {getStreamAsBuffer} from 'get-stream';7 import {execa, execaSync} from '../index.js';8 import {setFixtureDir, FIXTURES_DIR} from './helpers/fixtures-dir.js';9 import {fullStdio} from './helpers/stdio.js';10 4 unmodified lines15 const checkEncoding = async (t, encoding, index, execaMethod) => {16 const {stdio} = await execaMethod('noop-fd.js', [`${index}`, STRING_TO_ENCODE], {...fullStdio, encoding});17 compareValues(t, stdio[index], encoding);18 19+ if (execaMethod !== execaSync) {20+ const childProcess = execaMethod('noop-fd.js', [`${index}`, STRING_TO_ENCODE], {...fullStdio, encoding, buffer: false});21+ const getStreamMethod = encoding === 'buffer' ? getStreamAsBuffer : getStream;22+ const result = await getStreamMethod(childProcess.stdio[index]);23+ compareValues(t, result, encoding);24+ await childProcess;25+ }26+27 if (index === 3) {28 return;29 }30 97 unmodified lines128 129 test('validate unknown encodings', async t => {130 await t.throwsAsync(execa('noop.js', {encoding: 'unknownEncoding'}), {code: 'ERR_UNKNOWN_ENCODING'});131 });132+133+const foobarArray = ['fo', 'ob', 'ar', '..'];134+135+const delayedGenerator = async function * (chunks) {136+ // eslint-disable-next-line no-unused-vars137+ for await (const chunk of chunks) {138+ yield foobarArray[0];139+ await setTimeout(0);140+ yield foobarArray[1];141+ await setTimeout(0);142+ yield foobarArray[2];143+ await setTimeout(0);144+ yield foobarArray[3];145+ }146+};147+148+test('Handle multibyte characters', async t => {149+ const {stdout} = await execa('noop.js', {stdout: delayedGenerator, encoding: 'base64'});150+ t.is(stdout, btoa(foobarArray.join('')));151+});modified:test/stream.js+3 added-2 removed
115 unmodified lines116 test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, 2);117 test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, 3);118 119 const testMaxBufferHex = async (t, index) => {120+ const halfMaxBuffer = maxBuffer / 2;121 const {stdio} = await t.throwsAsync(121- execa('max-buffer.js', [`${index}`, `${maxBuffer + 1}`], {...fullStdio, maxBuffer, encoding: 'hex'}),122+ execa('max-buffer.js', [`${index}`, `${halfMaxBuffer + 1}`], {...fullStdio, maxBuffer, encoding: 'hex'}),123 );123- t.is(stdio[index], Buffer.from('.'.repeat(maxBuffer)).toString('hex'));124+ t.is(stdio[index], Buffer.from('.'.repeat(halfMaxBuffer)).toString('hex'));125 };126 127 test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);128 test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);176 unmodified lines