Skip to content

Commit

Permalink
Implies: conditional demands
Browse files Browse the repository at this point in the history
  • Loading branch information
Alex Ford committed Nov 22, 2013
1 parent 046b93b commit 6134619
Show file tree
Hide file tree
Showing 3 changed files with 95 additions and 1 deletion.
10 changes: 10 additions & 0 deletions example/implies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/env node

var argv = require('../index')
.usage('Usage: $0 -x [num] -y [num]')
.implies('x', 'y')
.argv;

if (argv.x) {
console.log(argv.x / argv.y);
}
26 changes: 26 additions & 0 deletions example/implies_hash.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
#!/usr/bin/env node

var argv = require('../index')
.usage('Usage: $0 -x [num] -y [num] -w [msg] -h [msg]')
.implies({
x: 'y',
w: '--no-h',
1: 'h'
})
.argv;

if (argv.x) {
console.log('x / y : ' + (argv.x / argv.y));
}

if (argv.y) {
console.log('y: ' + argv.y);
}

if (argv.w) {
console.log('w: ' +argv.w);
}

if (argv.h) {
console.log('h: ' +argv.h);
}
60 changes: 59 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,18 @@ function Argv (processArgs, cwd) {

return self;
};


var implied = {};
self.implies = function (key, value) {
if (typeof key === 'object') {
Object.keys(key).forEach(function (k) {
self.implies(k, key[k]);
});
} else {
implied[key] = value;
}
};

var usage;
self.usage = function (msg, opts) {
if (!opts && typeof msg === 'object') {
Expand Down Expand Up @@ -388,6 +399,53 @@ function Argv (processArgs, cwd) {
fail(err)
}
});

var implyFail = [];
Object.keys(implied).forEach(function (key) {
var num, origKey = key, value = implied[key];

// convert string '1' to number 1
var num = Number(key);
key = isNaN(num) ? key : num;

if (typeof key === 'number') {
// check length of argv._
key = argv._.length >= key;
} else if (key.match(/^--no-.+/)) {
// check if key doesn't exist
key = key.match(/^--no-(.+)/)[1];
key = !argv[key];
} else {
// check if key exists
key = argv[key];
}

num = Number(value);
value = isNaN(num) ? value : num;

if (typeof value === 'number') {
value = argv._.length >= value;
} else if (value.match(/^--no-.+/)) {
value = value.match(/^--no-(.+)/)[1];
value = !argv[value];
} else {
value = argv[value];
}

if (key && !value) {
implyFail.push(origKey);
}
});

if (implyFail.length) {
var msg = 'Implications failed:\n';

implyFail.forEach(function (key) {
msg += (' ' + key + ' -> ' + implied[key] + '\n');
});

fail(msg);
}

return argv;
}
Expand Down

0 comments on commit 6134619

Please sign in to comment.