Merge branch 'integration'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by TJ Holowaychuk · committed by TJ Holowaychuk · parents 62a74c1, 8f2a305 · Browse files · 3 files·+210 added−28 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+210 added−28 removed
- tests:+109 added−0 removed
- other:+101 added−28 removed
Provenance
- Commit
901a521- Tree
4c581b5- Author
TJ Holowaychuk <tj@vision-media.ca>- Committer
TJ Holowaychuk <tj@vision-media.ca>- Parent 1
62a74c1- Parent 2
8f2a305
3 files changed+210 added−28 removed
modified:examples/deploy+13 added-6 removed
13 unmodified lines14 15 program16 .command('setup [env]')17 .description('run setup commands for all envs')18+ .option("-s, --setup_mode [mode]", "Which setup mode to use")18- .action(function(env){19+ .action(function(env, options){20+ var mode = options.setup_mode || "normal";21 env = env || 'all';20- console.log('setup for %s env(s)', env);22+ console.log('setup for %s env(s) with %s mode', env, mode);23 });24 25 program26 .command('exec <cmd>')27 .description('execute the given remote cmd')28+ .option("-e, --exec_mode <mode>", "Which exec mode to use")26- .action(function(cmd){27- console.log('exec "%s"', cmd);29+ .action(function(cmd, options){30+ console.log('exec "%s" using %s mode', cmd, options.exec_mode);31+ }).on('--help', function() {32+ console.log(' Examples:');33+ console.log();34+ console.log(' $ deploy exec sequential');35+ console.log(' $ deploy exec async');36+ console.log();37 });38 39 program40 .command('*')1 unmodified line42 console.log('deploying "%s"', env);43 });44 45 program.parse(process.argv);37-38-modified:lib/commander.js+88 added-22 removed
197 unmodified lines198 */199 200 Command.prototype.action = function(fn){201 var self = this;202- this.parent.on(this.name, function(args){202+ this.parent.on(this.name, function(args, unknown){ 203+ // Parse any so-far unknown options204+ unknown = unknown || [];205+ var parsed = self.parseOptions(unknown);206+ 207+ // Output help if necessary208+ outputHelpIfNecessary(self, parsed.unknown);209+ 210+ // If there are still any unknown options, then we simply 211+ // die, unless someone asked for help, in which case we give it212+ // to them, and then we die.213+ if (parsed.unknown.length > 0) { 214+ self.unknownOption(parsed.unknown[0]);215+ }216+ 217 self.args.forEach(function(arg, i){218 if (arg.required && null == args[i]) {219 self.missingArgument(arg.name);220 }221 });222+ 223+ // Always append ourselves to the end of the arguments,224+ // to make sure we match the number of arguments the user225+ // expects226+ if (self.args.length) {227+ args[self.args.length] = self;228+ } else {229+ args.push(self);230+ }231+ 232 fn.apply(this, args);233 });234 return this;235 };107 unmodified lines343 // guess name344 if (!this.name) this.name = basename(argv[1]);345 346 // process argv323- this.args = this.parseOptions(this.normalize(argv));324- return this.parseArgs(this.args);347+ var parsed = this.parseOptions(this.normalize(argv.slice(2)));348+ this.args = parsed.args;349+ return this.parseArgs(this.args, parsed.unknown);350 };351 352 /**353 * Normalize `args`, splitting joined short flags. For example33 unmodified lines387 * @return {Command} for chaining388 * @api private389 */390 366-Command.prototype.parseArgs = function(args){391+Command.prototype.parseArgs = function(args, unknown){392 var cmds = this.commands393 , len = cmds.length394 , name;395 396 if (args.length) {397 name = args[0];398 if (this.listeners(name).length) {374- this.emit(args.shift(), args);399+ this.emit(args.shift(), args, unknown);400 } else {401 this.emit('*', args);402 }403+ } else {404+ outputHelpIfNecessary(this, unknown);405+ 406+ // If there were no args and we have unknown options,407+ // then they are extraneous and we need to error.408+ if (unknown.length > 0) { 409+ this.unknownOption(unknown[0]);410+ }411 }412 413 return this;414 };24 unmodified lines439 */440 441 Command.prototype.parseOptions = function(argv){442 var args = []410- , argv = argv.slice(2)443 , len = argv.length444 , literal445 , option446 , arg;447 448+ var unknownOptions = [];449+450 // parse options451 for (var i = 0; i < len; ++i) {452 arg = argv[i];453 36 unmodified lines490 }491 492 // looks like an option493 if (arg.length > 1 && '-' == arg[0]) {460- this.unknownOption(arg);494+ unknownOptions.push(arg);495+ 496+ // If the next argument looks like it might be497+ // an argument for this option, we pass it on.498+ // If it isn't, then it'll simply be ignored499+ if (argv[i+1] && '-' != argv[i+1][0]) {500+ unknownOptions.push(argv[++i]);501+ }502+ continue;503 }504 505 // arg506 args.push(arg);507 }466-467- return args;508+ 509+ return { args: args, unknown: unknownOptions };510 };511 512 /**513 * Argument `name` is missing.88 unmodified lines602 * @api public603 */604 605 Command.prototype.usage = function(str){606+ var args = this.args.map(function(arg){607+ return arg.required608+ ? '<' + arg.name + '>'609+ : '[' + arg.name + ']';610+ });611+612 var usage = '[options'613 + (this.commands.length ? '] [command' : '')566- + ']';614+ + ']'615+ + (this.args.length ? ' ' + args : '');616 if (0 == arguments.length) return this._usage || usage;617 this._usage = str;618+619 return this;620 };621 622 /**17 unmodified lines640 */641 642 Command.prototype.optionHelp = function(){643 var width = this.largestOptionLength();644+ 645+ // Prepend the help information646+ return [pad('-h, --help', width) + ' ' + 'output usage information']594- return this.options.map(function(option){595- return pad(option.flags, width)596- + ' ' + option.description;597- }).join('\n');647+ .concat(this.options.map(function(option){648+ return pad(option.flags, width)649+ + ' ' + option.description;650+ }))651+ .join('\n');652 };653 654 /**655 * Return command help documentation.13 unmodified lines669 return arg.required670 ? '<' + arg.name + '>'671 : '[' + arg.name + ']';672 }).join(' ');673+619- return cmd.name + ' ' + args674+ return cmd.name 675+ + (cmd.options.length 676+ ? ' [options]'677+ : '') + ' ' + args678 + (cmd.description()679 ? '\n' + cmd.description()680 : '');681 }).join('\n\n').replace(/^/gm, ' ')288 unmodified lines970 return str + Array(len + 1).join(' ');971 }972 973 /**916- * Default -h, --help option.974+ * Output help information if necessary975+ *976+ * @param {Command} command to output help for977+ * @param {Array} array of options to search for -h or --help978+ * @api private979 */980 919-exports.option('-h, --help', 'output usage information');920-exports.on('help', function(){921- process.stdout.write(this.helpInformation());922- exports.emit('--help');923- process.exit(0);924-});981+function outputHelpIfNecessary(cmd, options) {982+ options = options || [];983+ for (var i = 0; i < options.length; i++) {984+ if (options[i] == '--help' || options[i] == '-h') {985+ process.stdout.write(cmd.helpInformation());986+ cmd.emit('--help');987+ process.exit(0);988+ }989+ }990+}added:test/test.options.commands.js+109 added
1+/**2+ * Module dependencies.3+ */4+5+var program = require('../')6+ , should = require('should');7+8+program9+ .version('0.0.1')10+ .option('-C, --chdir <path>', 'change the working directory')11+ .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')12+ .option('-T, --no-tests', 'ignore test hook')13+14+var envValue = "";15+var cmdValue = "";16+var customHelp = false;17+18+program19+ .command('setup [env]')20+ .description('run setup commands for all envs')21+ .option("-s, --setup_mode [mode]", "Which setup mode to use")22+ .option("-o, --host [host]", "Host to use")23+ .action(function(env, options){24+ var mode = options.setup_mode || "normal";25+ env = env || 'all';26+ 27+ envValue = env;28+ });29+30+program31+ .command('exec <cmd>')32+ .description('execute the given remote cmd')33+ .option("-e, --exec_mode <mode>", "Which exec mode to use")34+ .option("-t, --target [target]", "Target to use")35+ .action(function(cmd, options){36+ cmdValue = cmd;37+ }).on("--help", function(){38+ customHelp = true;39+ });40+41+program42+ .command('*')43+ .action(function(env){44+ console.log('deploying "%s"', env);45+ });46+ 47+program.parse(['node', 'test', '--config', 'conf']);48+program.config.should.equal("conf");49+program.commands[0].should.not.have.property.setup_mode;50+program.commands[1].should.not.have.property.exec_mode;51+envValue.should.be.null;52+cmdValue.should.be.null;53+54+program.parse(['node', 'test', '--config', 'conf1', 'setup', '--setup_mode', 'mode3', 'env1']);55+program.config.should.equal("conf1");56+program.commands[0].setup_mode.should.equal("mode3");57+program.commands[0].should.not.have.property.host;58+envValue.should.equal("env1");59+60+program.parse(['node', 'test', '--config', 'conf2', 'setup', '--setup_mode', 'mode3', '-o', 'host1', 'env2']);61+program.config.should.equal("conf2");62+program.commands[0].setup_mode.should.equal("mode3");63+program.commands[0].host.should.equal("host1");64+envValue.should.equal("env2");65+66+program.parse(['node', 'test', '--config', 'conf3', 'setup', '-s', 'mode4', 'env3']);67+program.config.should.equal("conf3");68+program.commands[0].setup_mode.should.equal("mode4");69+envValue.should.equal("env3");70+71+program.parse(['node', 'test', '--config', 'conf4', 'exec', '--exec_mode', 'mode1', 'exec1']);72+program.config.should.equal("conf4");73+program.commands[1].exec_mode.should.equal("mode1");74+program.commands[1].should.not.have.property.target;75+cmdValue.should.equal("exec1");76+77+program.parse(['node', 'test', '--config', 'conf5', 'exec', '-e', 'mode2', 'exec2']);78+program.config.should.equal("conf5");79+program.commands[1].exec_mode.should.equal("mode2");80+cmdValue.should.equal("exec2");81+82+program.parse(['node', 'test', '--config', 'conf6', 'exec', '--target', 'target1', '-e', 'mode2', 'exec3']);83+program.config.should.equal("conf6");84+program.commands[1].exec_mode.should.equal("mode2");85+program.commands[1].target.should.equal("target1");86+cmdValue.should.equal("exec3");87+88+// Make sure we still catch errors with required values for options89+var exceptionOccurred = false;90+var oldProcessExit = process.exit;91+var oldConsoleError = console.error;92+process.exit = function() { exceptionOccurred = true; throw new Error(); };93+console.error = function() {};94+95+try {96+ program.parse(['node', 'test', '--config', 'conf6', 'exec', '--help']);97+} catch(ex) {98+ program.config.should.equal("conf6");99+}100+101+try {102+ program.parse(['node', 'test', '--config', 'conf', 'exec', '-t', 'target1', 'exec1', '-e']);103+}104+catch(ex) {105+}106+107+process.exit = oldProcessExit;108+exceptionOccurred.should.be.true;109+customHelp.should.be.true;