Skip to content

Commit

Permalink
Disable process.exit calls using .exitProcess(false)
Browse files Browse the repository at this point in the history
  • Loading branch information
cianclarke committed Oct 29, 2014
1 parent b8d3472 commit 2d68c5b
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 4 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -574,6 +574,11 @@ yargs.showHelp();

Later on, ```argv``` can be retrived with ```yargs.argv```

.exitProcess(enable)
----------------------------------

By default, yargs exits the process when the user passes a help flag, uses the `.version` functionality or when validation fails. Calling `.exitProcess(false)` disables this behavior, enabling further actions after yargs have been validated.

.parse(args)
------------

Expand Down
24 changes: 20 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,11 @@ function Argv (processArgs, cwd) {
}
console.error(failMessage);
}
process.exit(1);
if (exitProcess){
process.exit(1);
}else{
throw new Error(msg);
}
}
}

Expand Down Expand Up @@ -306,7 +310,15 @@ function Argv (processArgs, cwd) {
showHelpOnFail = enabled;
return self;
};


var exitProcess = true;
self.exitProcess = function (enabled) {
if (typeof enabled !== 'boolean') {
enabled = true;
}
exitProcess = enabled;
return self;
};

self.help = function () {
if (arguments.length > 0) {
Expand Down Expand Up @@ -459,11 +471,15 @@ function Argv (processArgs, cwd) {
Object.keys(argv).forEach(function(key) {
if (key === helpOpt) {
self.showHelp(console.log);
process.exit(0);
if (exitProcess){
process.exit(0);
}
}
else if (key === versionOpt) {
process.stdout.write(version);
process.exit(0);
if (exitProcess){
process.exit(0);
}
}
});

Expand Down
22 changes: 22 additions & 0 deletions test/usage.js
Original file line number Diff line number Diff line change
Expand Up @@ -723,6 +723,28 @@ describe('usage', function () {
]);
});
});

describe('exitProcess', function () {
it('should not call process.exit on error if disabled', function () {
var opts = {
foo: { desc: 'foo option', alias: 'f' },
};

var r = checkUsage(function () {
return yargs(['--foo'])
.exitProcess(false)
.usage('Usage: $0 [options]')
.options(opts)
.demand(['foo'])
.argv;
});
r.should.have.property('result');
r.result.should.have.property('_').with.length(0);
r.should.have.property('errors');
r.should.have.property('logs').with.length(0);
r.should.have.property('exit').and.be.false;
});
});

it('should succeed when rebase', function () {
yargs.rebase('/home/chevex', '/home/chevex/foo/bar/baz').should.equal('./foo/bar/baz');
Expand Down

0 comments on commit 2d68c5b

Please sign in to comment.