Skip to content

Commit

Permalink
Allow boolean flag with .demand()
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisn committed Jun 23, 2014
1 parent 13ed545 commit e855af4
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 3 deletions.
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -372,7 +372,7 @@ Set `argv[key]` to `value` if no option was specified on `process.argv`.
Optionally `.default()` can take an object that maps keys to default values.
.demand(key, [msg])
.demand(key, [boolean | msg])
------------
If `key` is a string, show the usage information and exit if `key` wasn't
Expand All @@ -383,9 +383,12 @@ up in `argv._`.
If `key` is an Array, demand each element.
If `msg` is supplied, it will be printed when the argument is missing,
If a `msg` string is given, it will be printed when the argument is missing,
instead of the standard error message. This is especially helpful for the non-option arguments in `argv._`.
If a `boolean` value is given, it controls whether the option is demanded;
this is useful when using `.options()` to specify command line parameters.
.requiresArg(key)
-----------------
Expand Down
7 changes: 6 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,12 @@ function Argv (processArgs, cwd) {
});
}
else {
demanded[keys] = { msg: msg };
if (typeof msg === 'string') {
demanded[keys] = { msg: msg };
}
else if (msg === true || typeof msg === 'undefined') {
demanded[keys] = { msg: null };
}
}

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

it('should allow demand option with boolean flag', function () {
var r = checkUsage(function () {
return yargs('-y 10 -z 20'.split(' '))
.usage('Usage: $0 -x NUM [-y NUM]')
.options({
'x': { description: 'an option', demand: true },
'y': { description: 'another option', demand: false }
})
.argv;
});
r.result.should.have.property('y', 10);
r.result.should.have.property('z', 20);
r.result.should.have.property('_').with.length(0);
r.errors.join('\n').split(/\n/).should.deep.equal([
'Usage: ./usage -x NUM [-y NUM]',
'',
'Options:',
' -x an option [required]',
' -y another option',
'',
'Missing required arguments: x'
]);
r.logs.should.have.length(0);
r.exit.should.be.ok;
});

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

0 comments on commit e855af4

Please sign in to comment.