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
Provenance
- Commit
7122767- Tree
a267218- Author
ehmicky <ehmicky@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
20b2ee6
4 files changed+58 added−64 removed
modified:lib/kill.js+10 added-20 removed
49 unmodified lines505152535454555657575859606161626363646566676768697071727374686970717273747576777884798086818283848586929394959697878849 unmodified lines context.isCanceled = true; }};
const killAfterTimeout = async (spawned, timeout, killSignal, controller) => {const killAfterTimeout = async ({spawned, timeout, killSignal, context, controller}) => { await pSetTimeout(timeout, undefined, {ref: false, signal: controller.signal}); spawned.kill(killSignal); throw Object.assign(new Error('Timed out'), {timedOut: true, signal: killSignal}); Object.assign(context, {timedOut: true, signal: killSignal}); throw new Error('Timed out');};
// `timeout` option handlingexport const setupTimeout = async (spawned, {timeout, killSignal = 'SIGTERM'}, spawnedPromise) => {export const throwOnTimeout = ({spawned, timeout, killSignal, context, finalizers}) => { if (timeout === 0 || timeout === undefined) { return spawnedPromise; return []; }
const controller = new AbortController(); try { return await Promise.race([ spawnedPromise, killAfterTimeout(spawned, timeout, killSignal, controller), ]); } finally { controller.abort(); } finalizers.push(controller.abort.bind(controller)); return [killAfterTimeout({spawned, timeout, killSignal, context, controller})];};
export const validateTimeout = ({timeout}) => { if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) { throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`); }};
// `cleanup` option handlingexport const setExitHandler = async (spawned, {cleanup, detached}, timedPromise) => {export const cleanupOnExit = (spawned, cleanup, detached, finalizers) => { if (!cleanup || detached) { return timedPromise; return; }
const removeExitHandler = onExit(() => { spawned.kill(); });
try { return await timedPromise; } finally { removeExitHandler(); } finalizers.push(removeExitHandler);};modified:lib/promise.js-8 removed
1212347 unmodified lines12131415181920212223import {once} from 'node:events';
// eslint-disable-next-line unicorn/prefer-top-level-awaitconst nativePromisePrototype = (async () => {})().constructor.prototype;
const descriptors = ['then', 'catch', 'finally'].map(property => [7 unmodified lines const value = descriptor.value.bind(promise); Reflect.defineProperty(spawned, property, {...descriptor, value}); }};
// Use promises instead of `child_process` eventsexport const getSpawnedPromise = async spawned => { const [exitCode, signal] = await once(spawned, 'exit'); return {exitCode, signal};};modified:lib/stream.js+41 added-26 removed
2 unmodified lines3 import {finished} from 'node:stream/promises';4 import process from 'node:process';5 import getStream, {getStreamAsArrayBuffer} from 'get-stream';6 import mergeStreams from '@sindresorhus/merge-streams';7+import {throwOnTimeout, cleanupOnExit} from './kill.js';8 9 // `all` interleaves `stdout` and `stderr`10 export const makeAllStream = (spawned, {all}) => {11 if (!all) {48 unmodified lines60 61 // eslint-disable-next-line unicorn/text-encoding-identifier-case62 const isUtf8Encoding = encoding => encoding === 'utf8' || encoding === 'utf-8';63 64+// Retrieve streams created by the `std*` options65+const getCustomStreams = stdioStreams => stdioStreams.filter(({type}) => type !== 'native' && type !== 'stringOrBuffer');66+67 // 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.71-const waitForStreamEnd = ({value, type, direction}, processDone) => {72- if (type === 'native' || type === 'stringOrBuffer') {73- return;74- }75+const waitForCustomStreamsEnd = customStreams => customStreams76+ .filter(({value, type, direction}) => shouldWaitForCustomStream(value, type, direction))77+ .map(({value}) => finished(value));78 76- return type === 'filePath' || (direction === 'output' && value !== process.stdout && value !== process.stderr)77- ? finished(value)78- : Promise.race([processDone, throwOnStreamError(value)]);79-};79+const throwOnCustomStreamsError = customStreams => customStreams80+ .filter(({value, type, direction}) => !shouldWaitForCustomStream(value, type, direction))81+ .map(({value}) => throwOnStreamError(value));82 81-const throwIfStreamError = (stream, processDone) => stream === null82- ? undefined83- : Promise.race([processDone, throwOnStreamError(stream)]);83+const shouldWaitForCustomStream = (value, type, direction) => type === 'filePath'84+ || (direction === 'output' && value !== process.stdout && value !== process.stderr);85 86+const throwIfStreamError = stream => stream === null ? [] : [throwOnStreamError(stream)];87+88 const throwOnStreamError = async stream => {89 const [error] = await once(stream, 'error');90 throw error;91 };92 93 // 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.93-const cleanupStdioStreams = (stdioStreams, error) => {94- for (const stdioStream of stdioStreams) {95- if (stdioStream.autoDestroy) {96- stdioStream.value.destroy(error);96+const cleanupStdioStreams = (customStreams, error) => {97+ for (const customStream of customStreams) {98+ if (customStream.autoDestroy) {99+ customStream.value.destroy(error);100 }101 }102 };103 104 // Retrieve result of child process: exit code, signal, error, streams (stdout/stderr/all)105 export 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);114+115 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});118 119 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 lines9 import {makeError} from './lib/error.js';10 import {handleInputAsync, pipeOutputAsync} from './lib/stdio/async.js';11 import {handleInputSync, pipeOutputSync} from './lib/stdio/sync.js';12 import {normalizeStdioNode} from './lib/stdio/normalize.js';13-import {spawnedKill, spawnedCancel, setupTimeout, validateTimeout, setExitHandler} from './lib/kill.js';13+import {spawnedKill, spawnedCancel, validateTimeout} from './lib/kill.js';14 import {addPipeMethods} from './lib/pipe.js';15 import {getSpawnedResult, makeAllStream} from './lib/stream.js';16-import {mergePromise, getSpawnedPromise} from './lib/promise.js';16+import {mergePromise} from './lib/promise.js';17 import {joinCommand, parseCommand, parseTemplates, getEscapedCommand} from './lib/command.js';18 import {logCommand, verboseDefault} from './lib/verbose.js';19 20 const DEFAULT_MAX_BUFFER = 1000 * 1000 * 100;40 unmodified lines61 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 lines126 mergePromise(dummySpawned, errorPromise);127 return dummySpawned;128 }129 129- const context = {isCanceled: false};130+ const context = {isCanceled: false, timedOut: false};131 132 spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));133 spawned.cancel = spawnedCancel.bind(null, spawned, context);134 8 unmodified lines143 return spawned;144 }145 146 const 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);149-147 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 lines165 all,166 command,167 escapedCommand,168 options,172- timedOut,169+ timedOut: context.timedOut,170 isCanceled,171 });172 173 if (!options.reject) {157 unmodified lines