From a21317c4973738e5c526d096bb8409ad61da514c Mon Sep 17 00:00:00 2001 From: just-boris Date: Thu, 17 Sep 2015 16:20:17 +0300 Subject: [PATCH] refactor process exit interceptor * patch process.exit only if we have streams needed to be flushed before exit * preserve exit code while awaiting streams --- mocha-multi.js | 74 ++++++++++++++++---------------------------------- 1 file changed, 23 insertions(+), 51 deletions(-) diff --git a/mocha-multi.js b/mocha-multi.js index 6bd0ec0..6fede95 100644 --- a/mocha-multi.js +++ b/mocha-multi.js @@ -11,30 +11,6 @@ module.exports = MochaMulti var stdout = process.stdout; var stderr = process.stderr; -// Should we hijack process.exit to wait for streams to close? -var shouldExit = false; - -// HAAAACK -// if mocha is being run as commandline program -// force mocha to call our fake process.exit -// -// This has to happen on require to be early -// enough to affect the code in _mocha -try { - var program = require('mocha/node_modules/commander'); - if (program.name == 'mocha' && ('exit' in program)) { - shouldExit = program.exit; - program.exit = true; - } -} catch (ex) {} - -// Capture the exit code and preserve it -var exit = process.exit; -process.exit = function(code) { - var quit = exit.bind(process, code); - process.on('exit', quit); -} - function MochaMulti(runner, options) { var setup; var reporters = (options && options.reporterOptions); @@ -53,33 +29,10 @@ function MochaMulti(runner, options) { // Remove nulls streams = streams.filter(identity); - if (!shouldExit) { - debug('not hijacking exit') - return; + //we actually need to wait streams only if they are present + if(streams.length > 0) { + awaitStreamsOnExit(streams); } - - // Wait for streams, then exit - runner.on('end', function() { - debug('Shutting down...') - - var num = streams.length; - streams.forEach(function(stream) { - stream.end(function() { - num -= 1; - onClose(); - }); - }); - onClose(); - - function onClose() { - if (num === 0) { - if (! program.watch) { - debug('Exiting.'); - exit(); - } - } - } - }) } var msgs = { @@ -94,7 +47,7 @@ function bombOut(id) { var args = Array.prototype.slice.call(arguments, 0); args[0] = 'ERROR: ' + msgs[id]; stderr.write(util.format.apply(util, args) + "\n"); - exit(1); + process.exit(1); } function parseSetup() { @@ -135,6 +88,25 @@ function initReportersAndStreams(runner, setup) { }) } +function awaitStreamsOnExit(streams) { + var exit = process.exit; + var num = streams.length; + process.exit = function(code) { + var quit = exit.bind(process, code); + streams.forEach(function(stream) { + stream.end(function() { + num--; + onClose(); + }); + }); + function onClose() { + if(num === 0) { + quit(); + } + } + }; +} + function resolveReporter(name) { // Cribbed from Mocha.prototype.reporter() var reporter;