From a7b57d96bedecf78210b8284de968b2d7ebf881b Mon Sep 17 00:00:00 2001 From: ehmicky Date: Mon, 10 Jun 2019 02:57:23 -0700 Subject: [PATCH] Refactor `kill()` (#272) --- index.js | 33 +++++++++++++++++++-------------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/index.js b/index.js index 23969bb822..34bf68b89f 100644 --- a/index.js +++ b/index.js @@ -213,6 +213,23 @@ function joinCommand(file, args = []) { return [file, ...args].join(' '); } +function spawnedKill(kill, signal = 'SIGTERM', options = {}) { + const killResult = kill(signal); + setKillTimeout(kill, signal, options, killResult); + return killResult; +} + +function setKillTimeout(kill, signal, options, killResult) { + if (!shouldForceKill(signal, options, killResult)) { + return; + } + + const forceKillAfter = Number.isInteger(options.forceKillAfter) ? + options.forceKillAfter : + 5000; + setTimeout(() => kill('SIGKILL'), forceKillAfter).unref(); +} + function shouldForceKill(signal, options, killResult) { return ((typeof signal === 'string' && signal.toUpperCase() === 'SIGTERM') || @@ -239,20 +256,8 @@ const execa = (file, args, options) => { })); } - const originalKill = spawned.kill.bind(spawned); - spawned.kill = (signal = 'SIGTERM', options = {}) => { - const killResult = originalKill(signal); - if (shouldForceKill(signal, options, killResult)) { - const forceKillAfter = Number.isInteger(options.forceKillAfter) ? - options.forceKillAfter : - 5000; - setTimeout(() => { - originalKill('SIGKILL'); - }, forceKillAfter).unref(); - } - - return killResult; - }; + const kill = spawned.kill.bind(spawned); + spawned.kill = spawnedKill.bind(null, kill); // #115 let removeExitHandler;