Skip to content
Myr

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 22abcff, 6f0558d · Browse files · 6 files+351 added−37 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+351 added−37 removed

  • tests:+230 added−0 removed
  • other:+121 added−37 removed

6 files+351 added−37 removed

modified:examples/deploy+13 added-6 removed
13 unmodified lines
1415program16 .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 });2425program26 .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 });3839program40 .command('*')
1 unmodified line
42 console.log('deploying "%s"', env);43 });4445program.parse(process.argv);3738
modified:lib/commander.js+97 added-30 removed
197 unmodified lines
198 */199200Command.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 lines
343 // guess name344 if (!this.name) this.name = basename(argv[1]);345346 // 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};351352/**353 * Normalize `args`, splitting joined short flags. For example
33 unmodified lines
387 * @return {Command} for chaining388 * @api private389 */390366Command.prototype.parseArgs = function(args){391Command.prototype.parseArgs = function(args, unknown){392 var cmds = this.commands393 , len = cmds.length394 , name;395396 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 }412413 return this;414};
24 unmodified lines
439 */440441Command.prototype.parseOptions = function(argv){442 var args = []410 , argv = argv.slice(2)443 , len = argv.length444 , literal445 , option446 , arg;447448 var unknownOptions = [];449450 // parse options451 for (var i = 0; i < len; ++i) {452 arg = argv[i];453
36 unmodified lines
490 }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 }466467 return args;508 509 return { args: args, unknown: unknownOptions };510};511512/**513 * Argument `name` is missing.
88 unmodified lines
602 * @api public603 */604605Command.prototype.usage = function(str){606 var args = this.args.map(function(arg){607 return arg.required608 ? '<' + arg.name + '>'609 : '[' + arg.name + ']';610 });611612 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;618619 return this;620};621622/**
17 unmodified lines
640 */641642Command.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};653654/**655 * Return command help documentation.
13 unmodified lines
669 return arg.required670 ? '<' + arg.name + '>'671 : '[' + arg.name + ']';672 }).join(' ');673619 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, ' ')
29 unmodified lines
711 * @api private712 */713714Command.prototype.promptForNumber = function(str, fn){715 var self = this;657 this.promptSingleLine(str, function(val){716 this.promptSingleLine(str, function parseNumber(val){717 val = Number(val);659 if (isNaN(val)) return program.promptForNumber(str + '(must be a number) ', fn);718 if (isNaN(val)) return self.promptSingleLine(str + '(must be a number) ', parseNumber);719 fn(val);720 });721};722
6 unmodified lines
729 */730731Command.prototype.promptForDate = function(str, fn){732 var self = this;674 this.promptSingleLine(str, function(val){733 this.promptSingleLine(str, function parseDate(val){734 val = new Date(val);676 if (isNaN(val.getTime())) return self.promptForDate(str + '(must be a date) ', fn);735 if (isNaN(val.getTime())) return self.promptSingleLine(str + '(must be a date) ', parseDate);736 fn(val);737 });738};739
25 unmodified lines
765 * @api private766 */767768Command.prototype.promptMultiLine = function(str, fn){710 var buf = '';769 var buf = [];770 console.log(str);771 process.stdin.setEncoding('utf8');772 process.stdin.on('data', function(val){714 if ('\n' == val) {773 if ('\n' == val || '\r\n' == val) {774 process.stdin.removeAllListeners('data');716 fn(buf);775 fn(buf.join('\n'));776 } else {718 buf += val;777 buf.push(val.trimRight());778 }779 }).resume();780};781
189 unmodified lines
971 return str + Array(len + 1).join(' ');972}973974/**916 * Default -h, --help option.975 * Output help information if necessary976 *977 * @param {Command} command to output help for978 * @param {Array} array of options to search for -h or --help979 * @api private980 */981919exports.option('-h, --help', 'output usage information');920exports.on('help', function(){921 exports.emit('--help');922 process.stdout.write(this.helpInformation());923 process.exit(0);924});982function outputHelpIfNecessary(cmd, options) {983 options = options || [];984 for (var i = 0; i < options.length; i++) {985 if (options[i] == '--help' || options[i] == '-h') {986 process.stdout.write(cmd.helpInformation());987 cmd.emit('--help');988 process.exit(0);989 }990 }991}
added:test/test.options.commands.js+109 added
1/**2 * Module dependencies.3 */45var program = require('../')6 , should = require('should');78program9 .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')1314var envValue = "";15var cmdValue = "";16var customHelp = false;1718program19 .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 });2930program31 .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 });4041program42 .command('*')43 .action(function(env){44 console.log('deploying "%s"', env);45 });46 47program.parse(['node', 'test', '--config', 'conf']);48program.config.should.equal("conf");49program.commands[0].should.not.have.property.setup_mode;50program.commands[1].should.not.have.property.exec_mode;51envValue.should.be.null;52cmdValue.should.be.null;5354program.parse(['node', 'test', '--config', 'conf1', 'setup', '--setup_mode', 'mode3', 'env1']);55program.config.should.equal("conf1");56program.commands[0].setup_mode.should.equal("mode3");57program.commands[0].should.not.have.property.host;58envValue.should.equal("env1");5960program.parse(['node', 'test', '--config', 'conf2', 'setup', '--setup_mode', 'mode3', '-o', 'host1', 'env2']);61program.config.should.equal("conf2");62program.commands[0].setup_mode.should.equal("mode3");63program.commands[0].host.should.equal("host1");64envValue.should.equal("env2");6566program.parse(['node', 'test', '--config', 'conf3', 'setup', '-s', 'mode4', 'env3']);67program.config.should.equal("conf3");68program.commands[0].setup_mode.should.equal("mode4");69envValue.should.equal("env3");7071program.parse(['node', 'test', '--config', 'conf4', 'exec', '--exec_mode', 'mode1', 'exec1']);72program.config.should.equal("conf4");73program.commands[1].exec_mode.should.equal("mode1");74program.commands[1].should.not.have.property.target;75cmdValue.should.equal("exec1");7677program.parse(['node', 'test', '--config', 'conf5', 'exec', '-e', 'mode2', 'exec2']);78program.config.should.equal("conf5");79program.commands[1].exec_mode.should.equal("mode2");80cmdValue.should.equal("exec2");8182program.parse(['node', 'test', '--config', 'conf6', 'exec', '--target', 'target1', '-e', 'mode2', 'exec3']);83program.config.should.equal("conf6");84program.commands[1].exec_mode.should.equal("mode2");85program.commands[1].target.should.equal("target1");86cmdValue.should.equal("exec3");8788// Make sure we still catch errors with required values for options89var exceptionOccurred = false;90var oldProcessExit = process.exit;91var oldConsoleError = console.error;92process.exit = function() { exceptionOccurred = true; throw new Error(); };93console.error = function() {};9495try {96 program.parse(['node', 'test', '--config', 'conf6', 'exec', '--help']);97} catch(ex) {98 program.config.should.equal("conf6");99}100101try {102 program.parse(['node', 'test', '--config', 'conf', 'exec', '-t', 'target1', 'exec1', '-e']);103}104catch(ex) {105}106107process.exit = oldProcessExit;108exceptionOccurred.should.be.true;109customHelp.should.be.true;
added:test/test.prompt.js+121 added
1/**2 * Module dependencies.3 */45var events = require('events')6 , program = require('../')7 , should = require('should');89//mock stdin on process10var stdin = new events.EventEmitter();11stdin.setEncoding = stdin.resume = function() {};12stdin.write = function(data) { stdin.emit('data', data); };13process.__defineGetter__('stdin', function() { return stdin });1415//mock stdout on process16var stdout = new events.EventEmitter();17stdout.write = function(data) { this.emit('data', data) };18stdout.expect = function(expected, fn) {19 var actual = '';20 this.once('data', function(data){ actual = data; });21 fn();22 actual.should.equal(expected);23}24//var realOut = process.stdout;25process.__defineGetter__('stdout', function() { return stdout });2627var count = 0;28var test = function(expected) {29 count++;30 return function(actual) {31 count--;32 if(expected instanceof Date) {33 //need something better :(34 //using `new Date(date.toString())` round trip35 //loosing some precision for .getTime()36 actual.should.be.an.instanceof(Date);37 } else {38 actual.should.equal(expected);39 }40 }41}4243process.on('exit', function(){44 count.should.equal(0);45})4647/* Single Line String Prompt Tests */48var prompt = 'hello '49 , expected = 'world';5051// simple single line string 52stdout.expect(prompt, function(){53 program.prompt(prompt, test(expected));54 stdin.write(expected); 55})56// with trim57stdout.expect(prompt, function(){58 program.prompt(prompt, test(expected));59 stdin.write(' ' + expected + ' '); 60})61// newline62stdout.expect(prompt, function(){63 program.prompt(prompt, test(''));64 stdin.write('\n'); 65})6667/* Multiline Tests*/68var prompt = 'A multiline';69stdout.expect(prompt + '\n', function() {70 program.prompt(prompt, test('hello world\n and what a world\nit could be'));71 stdin.write('hello world\n');72 stdin.write(' and what a world\n');73 stdin.write('it could be\n');74 stdin.write('\n');75})7677/* Date Prompt Tests */78var prompt = 'A date '79 , expected = new Date();80 81// simple date82stdout.expect(prompt, function(){83 program.prompt(prompt, Date, test(expected));84 stdin.write(expected.toString()); 85})86// not a date twice87stdout.expect(prompt, function() {88 program.prompt(prompt, Date, test(expected));89 90 stdout.expect(prompt + '(must be a date) ', function() {91 stdin.write('blue'); 92 })93 stdout.expect(prompt + '(must be a date) ', function() {94 stdin.write('blue'); 95 })96 stdin.write(expected.toString()); 97})9899/* Number Prompt Tests*/100var prompt = 'A number '101 , expected = 12;102 103//simple number104stdout.expect(prompt, function(){105 program.prompt(prompt, Number, test(expected));106 stdin.write(expected.toString()); 107})108109// not a number twice110stdout.expect(prompt, function() {111 program.prompt(prompt, Number, test(expected));112 113 stdout.expect(prompt + '(must be a number) ', function() {114 stdin.write('blue'); 115 })116 stdout.expect(prompt + '(must be a number) ', function() {117 stdin.write('blue'); 118 })119 stdin.write(expected.toString()); 120})121
modified:History.md+10 added
modified:package.json+1 added-1 removed