Add support for variadic arguments
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Fixes #53
authored by Jeremy Whitlock · committed by Jeremy Whitlock · parent db67c89 · Browse files · 3 files·+160 added−9 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+160 added−9 removed
- tests:+61 added−0 removed
- other:+99 added−9 removed
Provenance
- Commit
a150a21- Tree
bcb7197- Author
Jeremy Whitlock <jwhitlock@apache.org>- Committer
Jeremy Whitlock <jwhitlock@apache.org>- Parent
db67c89
3 files changed+160 added−9 removed
added:test/test.variadic.args.js+61 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061/** * Module dependencies. */
var program = require('../') , should = require('should') , util = require('util') , programArgs = ['node', 'test', 'mycommand', 'arg0', 'arg1', 'arg2', 'arg3'] , requiredArg , variadicArg;
program .version('0.0.1') .command('mycommand <requiredArg> [variadicArg...]') .action(function (arg0, arg1) { requiredArg = arg0; variadicArg = arg1; });
program.parse(programArgs);
requiredArg.should.eql('arg0');variadicArg.should.eql(['arg1', 'arg2', 'arg3']);
program.args[0].should.eql('arg0');program.args[1].should.eql(['arg1', 'arg2', 'arg3']);
program .version('0.0.1') .command('mycommand <variadicArg...> [optionalArg]') .action(function (arg0, arg1) {
});
// Make sure we still catch errors with required values for optionsvar consoleErrors = [];var oldProcessExit = process.exit;var oldConsoleError = console.error;var errorMessage;
process.exit = function() { throw new Error(consoleErrors.join('\n')); };console.error = function() { consoleErrors.push(util.format.apply(util, arguments));};
try { program.parse(programArgs);
should.fail(null, null, 'An Error should had been thrown above');} catch (err) { errorMessage = err.message;}
process.exit = oldProcessExit;console.error = oldConsoleError;
[ '', ' error: variadic arguments must be last `variadicArg\'', ''].join('\n').should.eql(errorMessage);modified:index.js+67 added-8 removed
125 unmodified lines126 * console.log('exec "%s"', cmd);127 * });128 *129 * program130+ * .command('teardown <dir> [otherDirs...]')131+ * .description('run teardown commands')132+ * .action(function(dir, otherDirs) {133+ * console.log('dir "%s"', dir);134+ * if (otherDirs) {135+ * otherDirs.forEach(function (oDir) {136+ * console.log('dir "%s"', oDir);137+ * });138+ * }139+ * });140+ *141+ * program142 * .command('*')143 * .description('deploy the given env')144 * .action(function(env) {145 * console.log('deploying "%s"', env);44 unmodified lines190 Command.prototype.parseExpectedArgs = function(args) {191 if (!args.length) return;192 var self = this;193 args.forEach(function(arg) {194+ var argDetails = {195+ required: false,196+ name: '',197+ variadic: false198+ };199+200 switch (arg[0]) {201 case '<':184- self._args.push({ required: true, name: arg.slice(1, -1) });202+ argDetails.required = true;203+ argDetails.name = arg.slice(1, -1);204 break;205 case '[':187- self._args.push({ required: false, name: arg.slice(1, -1) });206+ argDetails.name = arg.slice(1, -1);207 break;208 }209+210+ if (argDetails.name.indexOf('...') === argDetails.name.length - 3) {211+ argDetails.variadic = true;212+ argDetails.name = argDetails.name.slice(0, -3);213+ }214+215+ if (argDetails.name) {216+ self._args.push(argDetails);217+ }218 });219 return this;220 };221 38 unmodified lines260 261 self._args.forEach(function(arg, i) {262 if (arg.required && null == args[i]) {263 self.missingArgument(arg.name);264+ } else if (arg.variadic) {265+ if (i !== self._args.length - 1) {266+ self.variadicArgNotLast(arg.name);267+ }268+269+ args[i] = args.slice(i);270 }271 });272 273 // Always append ourselves to the end of the arguments,422 unmodified lines696 console.error();697 process.exit(1);698 };699 700+/**701+ * Variadic argument with `name` is not the last argument as required.702+ *703+ * @param {String} name704+ * @api private705+ */706 707+Command.prototype.variadicArgNotLast = function(name) {708+ console.error();709+ console.error(" error: variadic arguments must be last `%s'", name);710+ console.error();711+ process.exit(1);712+};713+714 /**715 * Set the program version to `str`.716 *717 * This method auto-registers the "-V, --version" flag54 unmodified lines772 */773 774 Command.prototype.usage = function(str) {775 var args = this._args.map(function(arg) {729- return arg.required730- ? '<' + arg.name + '>'731- : '[' + arg.name + ']';776+ return humanReadableArgName(arg);777 });778 779 var usage = '[options]'780 + (this.commands.length ? ' [command]' : '')59 unmodified lines840 if (!this.commands.length) return '';841 842 var commands = this.commands.map(function(cmd) {843 var args = cmd._args.map(function(arg) {799- return arg.required800- ? '<' + arg.name + '>'801- : '[' + arg.name + ']';844+ return humanReadableArgName(arg);845 }).join(' ');846 847 return [848 cmd._name113 unmodified lines962 process.exit(0);963 }964 }965 }966+967+/**968+ * Takes an argument an returns its human readable equivalent for help usage.969+ *970+ * @param {Object} arg971+ * @return {String}972+ * @api private973+ */974+975+function humanReadableArgName(arg) {976+ var nameOutput = arg.name + (arg.variadic === true ? '...' : '');977+978+ return arg.required979+ ? '<' + nameOutput + '>'980+ : '[' + nameOutput + ']'981+}modified:Readme.md+32 added-1 removed
36 unmodified lines37 ```38 39 Short flags may be passed as a single arg, for example `-abc` is equivalent to `-a -b -c`. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc.40 41+## Variadic arguments42+43+ The last argument of a command can be variadic, and only the last argument. To make an argument variadic you have to44+ append `...` to the argument name. Here is an example:45+46+```js47+#!/usr/bin/env node48+49+/**50+ * Module dependencies.51+ */52+53+var program = require('commander');54+55+program56+ .version('0.0.1')57+ .command('rmdir <dir> [otherDirs...]')58+ .action(function (dir, otherDirs) {59+ console.log('rmdir %s', dir);60+ if (otherDirs) {61+ otherDirs.forEach(function (oDir) {62+ console.log('rmdir %s', oDir);63+ });64+ }65+ })66+ .parse(process.argv);67+```68+69+ An `Array` is used for the value of a variadic argument. This applies to `program.args` as well as the argument passed70+ to your action as demonstrated above.71+72 ## Automated --help73 74 The help information is auto-generated based on the information commander already knows about your program, so the following `--help` info is for free:75 132 unmodified lines208 - [progress bars](https://github.com/visionmedia/node-progress)209 - [more progress bars](https://github.com/substack/node-multimeter)210 - [examples](https://github.com/visionmedia/commander.js/tree/master/examples)211 181-## License 212+## License213 214 (The MIT License)215 216 Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>19 unmodified lines