Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor process exit interceptor #12

Merged
merged 1 commit into from
Sep 21, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
74 changes: 23 additions & 51 deletions mocha-multi.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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 = {
Expand All @@ -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() {
Expand Down Expand Up @@ -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;
Expand Down