Skip to content
Myr

Use `async/await` instead of direct `Promise` manipulation (#659)

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

authored by ehmicky · committed by GitHub · parent 20b2ee6 · Browse files · 4 files+58 added−64 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+58 added−64 removed

  • other:+58 added−64 removed

4 files+58 added−64 removed

modified:lib/kill.js+10 added-20 removed
modified:lib/promise.js-8 removed
modified:lib/stream.js+41 added-26 removed
2 unmodified lines
3import {finished} from 'node:stream/promises';4import process from 'node:process';5import getStream, {getStreamAsArrayBuffer} from 'get-stream';6import mergeStreams from '@sindresorhus/merge-streams';7import {throwOnTimeout, cleanupOnExit} from './kill.js';89// `all` interleaves `stdout` and `stderr`10export const makeAllStream = (spawned, {all}) => {11 if (!all) {
48 unmodified lines
6061// eslint-disable-next-line unicorn/text-encoding-identifier-case62const isUtf8Encoding = encoding => encoding === 'utf8' || encoding === 'utf-8';6364// Retrieve streams created by the `std*` options65const getCustomStreams = stdioStreams => stdioStreams.filter(({type}) => type !== 'native' && type !== 'stringOrBuffer');6667// Some `stdout`/`stderr` options create a stream, e.g. when passing a file path.68// The `.pipe()` method automatically ends that stream when `childProcess.stdout|stderr` ends.69// This makes sure we want for the completion of those streams, in order to catch any error.70// Since we want to end those streams, they cannot be infinite, except for `process.stdout|stderr`.71// However, for the `stdin`/`input`/`inputFile` options, we only wait for errors, not completion.72// This is because source streams completion should end destination streams, but not the other way around.73// This allows for source streams to pipe to multiple destinations.74// We make an exception for `filePath`, since we create that source stream and we know it is piped to a single destination.71const waitForStreamEnd = ({value, type, direction}, processDone) => {72 if (type === 'native' || type === 'stringOrBuffer') {73 return;74 }75const waitForCustomStreamsEnd = customStreams => customStreams76 .filter(({value, type, direction}) => shouldWaitForCustomStream(value, type, direction))77 .map(({value}) => finished(value));7876 return type === 'filePath' || (direction === 'output' && value !== process.stdout && value !== process.stderr)77 ? finished(value)78 : Promise.race([processDone, throwOnStreamError(value)]);79};79const throwOnCustomStreamsError = customStreams => customStreams80 .filter(({value, type, direction}) => !shouldWaitForCustomStream(value, type, direction))81 .map(({value}) => throwOnStreamError(value));8281const throwIfStreamError = (stream, processDone) => stream === null82 ? undefined83 : Promise.race([processDone, throwOnStreamError(stream)]);83const shouldWaitForCustomStream = (value, type, direction) => type === 'filePath'84 || (direction === 'output' && value !== process.stdout && value !== process.stderr);8586const throwIfStreamError = stream => stream === null ? [] : [throwOnStreamError(stream)];8788const throwOnStreamError = async stream => {89 const [error] = await once(stream, 'error');90 throw error;91};9293// The streams created by the `std*` options are automatically ended by `.pipe()`.94// However `.pipe()` only does so when the source stream ended, not when it errored.95// Therefore, when `childProcess.stdin|stdout|stderr` errors, those streams must be manually destroyed.93const cleanupStdioStreams = (stdioStreams, error) => {94 for (const stdioStream of stdioStreams) {95 if (stdioStream.autoDestroy) {96 stdioStream.value.destroy(error);96const cleanupStdioStreams = (customStreams, error) => {97 for (const customStream of customStreams) {98 if (customStream.autoDestroy) {99 customStream.value.destroy(error);100 }101 }102};103104// Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)105export const getSpawnedResult = async (106 spawned,104 {encoding, buffer, maxBuffer},107 {encoding, buffer, maxBuffer, timeout, killSignal, cleanup, detached},108 context,109 stdioStreams,106 processDone,110) => {111 const finalizers = [];112 cleanupOnExit(spawned, cleanup, detached, finalizers);113 const customStreams = getCustomStreams(stdioStreams);114115 const stdoutPromise = getStreamPromise(spawned.stdout, {encoding, buffer, maxBuffer});116 const stderrPromise = getStreamPromise(spawned.stderr, {encoding, buffer, maxBuffer});117 const allPromise = getStreamPromise(spawned.all, {encoding, buffer, maxBuffer: maxBuffer * 2});118119 try {113 return await Promise.all([114 processDone,115 stdoutPromise,116 stderrPromise,117 allPromise,118 throwIfStreamError(spawned.stdin, processDone),119 ...stdioStreams.map(stdioStream => waitForStreamEnd(stdioStream, processDone)),120 return await Promise.race([121 Promise.all([122 once(spawned, 'exit'),123 stdoutPromise,124 stderrPromise,125 allPromise,126 ...waitForCustomStreamsEnd(customStreams),127 ]),128 ...throwOnCustomStreamsError(customStreams),129 ...throwIfStreamError(spawned.stdin),130 ...throwOnTimeout({spawned, timeout, killSignal, context, finalizers}),131 ]);132 } catch (error) {133 spawned.kill();134 const results = await Promise.all([124 {error, signal: error.signal, timedOut: error.timedOut},135 [undefined, context.signal, error],136 getBufferedData(stdoutPromise, encoding),137 getBufferedData(stderrPromise, encoding),138 getBufferedData(allPromise, encoding),139 ]);129 cleanupStdioStreams(stdioStreams, error);140 cleanupStdioStreams(customStreams, error);141 return results;142 } finally {143 for (const finalizer of finalizers) {144 finalizer();145 }146 }147};
modified:index.js+7 added-10 removed
8 unmodified lines
9import {makeError} from './lib/error.js';10import {handleInputAsync, pipeOutputAsync} from './lib/stdio/async.js';11import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';12import {normalizeStdioNode} from './lib/stdio/normalize.js';13import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';13import {spawnedKill, spawnedCancel, validateTimeout} from './lib/kill.js';14import {addPipeMethods} from './lib/pipe.js';15import {getSpawnedResult, makeAllStream} from './lib/stream.js';16import {mergePromise, getSpawnedPromise} from './lib/promise.js';16import {mergePromise} from './lib/promise.js';17import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';18import {logCommand, verboseDefault} from './lib/verbose.js';1920const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;
40 unmodified lines
61 cleanup: true,62 all: false,63 windowsHide: true,64 verbose: verboseDefault,65 killSignal: 'SIGTERM',66 ...initialOptions,67 shell: normalizeFileUrl(initialOptions.shell),68 };69
56 unmodified lines
126 mergePromise(dummySpawned, errorPromise);127 return dummySpawned;128 }129129 const context = {isCanceled: false};130 const context = {isCanceled: false, timedOut: false};131132 spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));133 spawned.cancel = spawnedCancel.bind(null, spawned, context);134
8 unmodified lines
143 return spawned;144}145146const handlePromise = async ({spawned, options, context, stdioStreams, command, escapedCommand}) => {146 const spawnedPromise = getSpawnedPromise(spawned);147 const timedPromise = setupTimeout(spawned, options, spawnedPromise);148 const processDone = setExitHandler(spawned, options, timedPromise);149147 const [151 {error, exitCode, signal, timedOut},148 [exitCode, signal, error],149 stdoutResult,150 stderrResult,151 allResult,155 ] = await getSpawnedResult(spawned, options, stdioStreams, processDone);152 ] = await getSpawnedResult(spawned, options, context, stdioStreams);153 const stdout = handleOutput(options, stdoutResult);154 const stderr = handleOutput(options, stderrResult);155 const all = handleOutput(options, allResult);156
8 unmodified lines
165 all,166 command,167 escapedCommand,168 options,172 timedOut,169 timedOut: context.timedOut,170 isCanceled,171 });172173 if (!options.reject) {
157 unmodified lines