Skip to content
Myr

Release 1.1.0

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 · parent 21b4169 · Browse files · 4 files+1135 added−1132 removed
This commit

State

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

Diff stats

4 files+1135 added−1132 removed

  • other:+1135 added−1132 removed

4 files+1135 added−1132 removed

deleted:lib/commander.js-1130 removed
1/*!2 * commander3 * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>4 * MIT Licensed5 */67/**8 * Module dependencies.9 */1011var EventEmitter = require('events').EventEmitter12 , spawn = require('child_process').spawn13 , keypress = require('keypress')14 , fs = require('fs')15 , exists = fs.existsSync16 , path = require('path')17 , tty = require('tty')18 , dirname = path.dirname19 , basename = path.basename;2021/**22 * Expose the root command.23 */2425exports = module.exports = new Command;2627/**28 * Expose `Command`.29 */3031exports.Command = Command;3233/**34 * Expose `Option`.35 */3637exports.Option = Option;3839/**40 * Initialize a new `Option` with the given `flags` and `description`.41 *42 * @param {String} flags43 * @param {String} description44 * @api public45 */4647function Option(flags, description) {48 this.flags = flags;49 this.required = ~flags.indexOf('<');50 this.optional = ~flags.indexOf('[');51 this.bool = !~flags.indexOf('-no-');52 flags = flags.split(/[ ,|]+/);53 if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();54 this.long = flags.shift();55 this.description = description || '';56}5758/**59 * Return option name.60 *61 * @return {String}62 * @api private63 */6465Option.prototype.name = function(){66 return this.long67 .replace('--', '')68 .replace('no-', '');69};7071/**72 * Check if `arg` matches the short or long flag.73 *74 * @param {String} arg75 * @return {Boolean}76 * @api private77 */7879Option.prototype.is = function(arg){80 return arg == this.short81 || arg == this.long;82};8384/**85 * Initialize a new `Command`.86 *87 * @param {String} name88 * @api public89 */9091function Command(name) {92 this.commands = [];93 this.options = [];94 this.args = [];95 this._name = name;96}9798/**99 * Inherit from `EventEmitter.prototype`.100 */101102Command.prototype.__proto__ = EventEmitter.prototype;103104/**105 * Add command `name`.106 *107 * The `.action()` callback is invoked when the108 * command `name` is specified via __ARGV__,109 * and the remaining arguments are applied to the110 * function for access.111 *112 * When the `name` is "*" an un-matched command113 * will be passed as the first arg, followed by114 * the rest of __ARGV__ remaining.115 *116 * Examples:117 *118 * program119 * .version('0.0.1')120 * .option('-C, --chdir <path>', 'change the working directory')121 * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')122 * .option('-T, --no-tests', 'ignore test hook')123 * 124 * program125 * .command('setup')126 * .description('run remote setup commands')127 * .action(function(){128 * console.log('setup');129 * });130 * 131 * program132 * .command('exec <cmd>')133 * .description('run the given remote command')134 * .action(function(cmd){135 * console.log('exec "%s"', cmd);136 * });137 * 138 * program139 * .command('*')140 * .description('deploy the given env')141 * .action(function(env){142 * console.log('deploying "%s"', env);143 * });144 * 145 * program.parse(process.argv);146 *147 * @param {String} name148 * @param {String} [desc]149 * @return {Command} the new command150 * @api public151 */152153Command.prototype.command = function(name, desc){154 var args = name.split(/ +/);155 var cmd = new Command(args.shift());156 if (desc) cmd.description(desc);157 if (desc) this.executables = true;158 this.commands.push(cmd);159 cmd.parseExpectedArgs(args);160 cmd.parent = this;161 if (desc) return this;162 return cmd;163};164165/**166 * Add an implicit `help [cmd]` subcommand167 * which invokes `--help` for the given command.168 *169 * @api private170 */171172Command.prototype.addImplicitHelpCommand = function() {173 this.command('help [cmd]', 'display help for [cmd]');174};175176/**177 * Parse expected `args`.178 *179 * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.180 *181 * @param {Array} args182 * @return {Command} for chaining183 * @api public184 */185186Command.prototype.parseExpectedArgs = function(args){187 if (!args.length) return;188 var self = this;189 args.forEach(function(arg){190 switch (arg[0]) {191 case '<':192 self.args.push({ required: true, name: arg.slice(1, -1) });193 break;194 case '[':195 self.args.push({ required: false, name: arg.slice(1, -1) });196 break;197 }198 });199 return this;200};201202/**203 * Register callback `fn` for the command.204 *205 * Examples:206 *207 * program208 * .command('help')209 * .description('display verbose help')210 * .action(function(){211 * // output help here212 * });213 *214 * @param {Function} fn215 * @return {Command} for chaining216 * @api public217 */218219Command.prototype.action = function(fn){220 var self = this;221 this.parent.on(this._name, function(args, unknown){ 222 // Parse any so-far unknown options223 unknown = unknown || [];224 var parsed = self.parseOptions(unknown);225 226 // Output help if necessary227 outputHelpIfNecessary(self, parsed.unknown);228 229 // If there are still any unknown options, then we simply 230 // die, unless someone asked for help, in which case we give it231 // to them, and then we die.232 if (parsed.unknown.length > 0) { 233 self.unknownOption(parsed.unknown[0]);234 }235 236 // Leftover arguments need to be pushed back. Fixes issue #56237 if (parsed.args.length) args = parsed.args.concat(args);238 239 self.args.forEach(function(arg, i){240 if (arg.required && null == args[i]) {241 self.missingArgument(arg.name);242 }243 });244 245 // Always append ourselves to the end of the arguments,246 // to make sure we match the number of arguments the user247 // expects248 if (self.args.length) {249 args[self.args.length] = self;250 } else {251 args.push(self);252 }253 254 fn.apply(this, args);255 });256 return this;257};258259/**260 * Define option with `flags`, `description` and optional261 * coercion `fn`. 262 *263 * The `flags` string should contain both the short and long flags,264 * separated by comma, a pipe or space. The following are all valid265 * all will output this way when `--help` is used.266 *267 * "-p, --pepper"268 * "-p|--pepper"269 * "-p --pepper"270 *271 * Examples:272 *273 * // simple boolean defaulting to false274 * program.option('-p, --pepper', 'add pepper');275 *276 * --pepper277 * program.pepper278 * // => Boolean279 *280 * // simple boolean defaulting to false281 * program.option('-C, --no-cheese', 'remove cheese');282 *283 * program.cheese284 * // => true285 *286 * --no-cheese287 * program.cheese288 * // => true289 *290 * // required argument291 * program.option('-C, --chdir <path>', 'change the working directory');292 *293 * --chdir /tmp294 * program.chdir295 * // => "/tmp"296 *297 * // optional argument298 * program.option('-c, --cheese [type]', 'add cheese [marble]');299 *300 * @param {String} flags301 * @param {String} description302 * @param {Function|Mixed} fn or default303 * @param {Mixed} defaultValue304 * @return {Command} for chaining305 * @api public306 */307308Command.prototype.option = function(flags, description, fn, defaultValue){309 var self = this310 , option = new Option(flags, description)311 , oname = option.name()312 , name = camelcase(oname);313314 // default as 3rd arg315 if ('function' != typeof fn) defaultValue = fn, fn = null;316317 // preassign default value only for --no-*, [optional], or <required>318 if (false == option.bool || option.optional || option.required) {319 // when --no-* we make sure default is true320 if (false == option.bool) defaultValue = true;321 // preassign only if we have a default322 if (undefined !== defaultValue) self[name] = defaultValue;323 }324325 // register the option326 this.options.push(option);327328 // when it's passed assign the value329 // and conditionally invoke the callback330 this.on(oname, function(val){331 // coercion332 if (null != val && fn) val = fn(val);333334 // unassigned or bool335 if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) {336 // if no value, bool true, and we have a default, then use it!337 if (null == val) {338 self[name] = option.bool339 ? defaultValue || true340 : false;341 } else {342 self[name] = val;343 }344 } else if (null !== val) {345 // reassign346 self[name] = val;347 }348 });349350 return this;351};352353/**354 * Parse `argv`, settings options and invoking commands when defined.355 *356 * @param {Array} argv357 * @return {Command} for chaining358 * @api public359 */360361Command.prototype.parse = function(argv){362 // implicit help363 if (this.executables) this.addImplicitHelpCommand();364365 // store raw args366 this.rawArgs = argv;367368 // guess name369 this._name = this._name || basename(argv[1]);370371 // process argv372 var parsed = this.parseOptions(this.normalize(argv.slice(2)));373 var args = this.args = parsed.args;374 375 // executable sub-commands, skip .parseArgs()376 if (this.executables) return this.executeSubCommand(argv, args, parsed.unknown);377378 return this.parseArgs(this.args, parsed.unknown);379};380381/**382 * Execute a sub-command executable.383 *384 * @param {Array} argv385 * @param {Array} args386 * @param {Array} unknown387 * @api private388 */389390Command.prototype.executeSubCommand = function(argv, args, unknown) {391 args = args.concat(unknown);392393 if (!args.length) this.help();394 if ('help' == args[0] && 1 == args.length) this.help();395396 // <cmd> --help397 if ('help' == args[0]) {398 args[0] = args[1];399 args[1] = '--help';400 }401402 // executable403 var dir = dirname(argv[1]);404 var bin = basename(argv[1]) + '-' + args[0];405406 // check for ./<bin> first407 var local = path.join(dir, bin);408 if (exists(local)) bin = local;409410 // run it411 args = args.slice(1);412 var proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] });413 proc.on('exit', function(code){414 if (code == 127) {415 console.error('\n %s(1) does not exist\n', bin);416 }417 });418};419420/**421 * Normalize `args`, splitting joined short flags. For example422 * the arg "-abc" is equivalent to "-a -b -c".423 * This also normalizes equal sign and splits "--abc=def" into "--abc def".424 *425 * @param {Array} args426 * @return {Array}427 * @api private428 */429430Command.prototype.normalize = function(args){431 var ret = []432 , arg433 , index;434435 for (var i = 0, len = args.length; i < len; ++i) {436 arg = args[i];437 if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) {438 arg.slice(1).split('').forEach(function(c){439 ret.push('-' + c);440 });441 } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {442 ret.push(arg.slice(0, index), arg.slice(index + 1));443 } else {444 ret.push(arg);445 }446 }447448 return ret;449};450451/**452 * Parse command `args`.453 *454 * When listener(s) are available those455 * callbacks are invoked, otherwise the "*"456 * event is emitted and those actions are invoked.457 *458 * @param {Array} args459 * @return {Command} for chaining460 * @api private461 */462463Command.prototype.parseArgs = function(args, unknown){464 var cmds = this.commands465 , len = cmds.length466 , name;467468 if (args.length) {469 name = args[0];470 if (this.listeners(name).length) {471 this.emit(args.shift(), args, unknown);472 } else {473 this.emit('*', args);474 }475 } else {476 outputHelpIfNecessary(this, unknown);477 478 // If there were no args and we have unknown options,479 // then they are extraneous and we need to error.480 if (unknown.length > 0) { 481 this.unknownOption(unknown[0]);482 }483 }484485 return this;486};487488/**489 * Return an option matching `arg` if any.490 *491 * @param {String} arg492 * @return {Option}493 * @api private494 */495496Command.prototype.optionFor = function(arg){497 for (var i = 0, len = this.options.length; i < len; ++i) {498 if (this.options[i].is(arg)) {499 return this.options[i];500 }501 }502};503504/**505 * Parse options from `argv` returning `argv`506 * void of these options.507 *508 * @param {Array} argv509 * @return {Array}510 * @api public511 */512513Command.prototype.parseOptions = function(argv){514 var args = []515 , len = argv.length516 , literal517 , option518 , arg;519520 var unknownOptions = [];521522 // parse options523 for (var i = 0; i < len; ++i) {524 arg = argv[i];525526 // literal args after --527 if ('--' == arg) {528 literal = true;529 continue;530 }531532 if (literal) {533 args.push(arg);534 continue;535 }536537 // find matching Option538 option = this.optionFor(arg);539540 // option is defined541 if (option) {542 // requires arg543 if (option.required) {544 arg = argv[++i];545 if (null == arg) return this.optionMissingArgument(option);546 if ('-' == arg[0]) return this.optionMissingArgument(option, arg);547 this.emit(option.name(), arg);548 // optional arg549 } else if (option.optional) {550 arg = argv[i+1];551 if (null == arg || '-' == arg[0]) {552 arg = null;553 } else {554 ++i;555 }556 this.emit(option.name(), arg);557 // bool558 } else {559 this.emit(option.name());560 }561 continue;562 }563 564 // looks like an option565 if (arg.length > 1 && '-' == arg[0]) {566 unknownOptions.push(arg);567 568 // If the next argument looks like it might be569 // an argument for this option, we pass it on.570 // If it isn't, then it'll simply be ignored571 if (argv[i+1] && '-' != argv[i+1][0]) {572 unknownOptions.push(argv[++i]);573 }574 continue;575 }576 577 // arg578 args.push(arg);579 }580 581 return { args: args, unknown: unknownOptions };582};583584/**585 * Argument `name` is missing.586 *587 * @param {String} name588 * @api private589 */590591Command.prototype.missingArgument = function(name){592 console.error();593 console.error(" error: missing required argument `%s'", name);594 console.error();595 process.exit(1);596};597598/**599 * `Option` is missing an argument, but received `flag` or nothing.600 *601 * @param {String} option602 * @param {String} flag603 * @api private604 */605606Command.prototype.optionMissingArgument = function(option, flag){607 console.error();608 if (flag) {609 console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag);610 } else {611 console.error(" error: option `%s' argument missing", option.flags);612 }613 console.error();614 process.exit(1);615};616617/**618 * Unknown option `flag`.619 *620 * @param {String} flag621 * @api private622 */623624Command.prototype.unknownOption = function(flag){625 console.error();626 console.error(" error: unknown option `%s'", flag);627 console.error();628 process.exit(1);629};630631632/**633 * Set the program version to `str`.634 *635 * This method auto-registers the "-V, --version" flag636 * which will print the version number when passed.637 *638 * @param {String} str639 * @param {String} flags640 * @return {Command} for chaining641 * @api public642 */643644Command.prototype.version = function(str, flags){645 if (0 == arguments.length) return this._version;646 this._version = str;647 flags = flags || '-V, --version';648 this.option(flags, 'output the version number');649 this.on('version', function(){650 console.log(str);651 process.exit(0);652 });653 return this;654};655656/**657 * Set the description `str`.658 *659 * @param {String} str660 * @return {String|Command}661 * @api public662 */663664Command.prototype.description = function(str){665 if (0 == arguments.length) return this._description;666 this._description = str;667 return this;668};669670/**671 * Set / get the command usage `str`.672 *673 * @param {String} str674 * @return {String|Command}675 * @api public676 */677678Command.prototype.usage = function(str){679 var args = this.args.map(function(arg){680 return arg.required681 ? '<' + arg.name + '>'682 : '[' + arg.name + ']';683 });684685 var usage = '[options'686 + (this.commands.length ? '] [command' : '')687 + ']'688 + (this.args.length ? ' ' + args : '');689 if (0 == arguments.length) return this._usage || usage;690 this._usage = str;691692 return this;693};694695/**696 * Return the largest option length.697 *698 * @return {Number}699 * @api private700 */701702Command.prototype.largestOptionLength = function(){703 return this.options.reduce(function(max, option){704 return Math.max(max, option.flags.length);705 }, 0);706};707708/**709 * Return help for options.710 *711 * @return {String}712 * @api private713 */714715Command.prototype.optionHelp = function(){716 var width = this.largestOptionLength();717 718 // Prepend the help information719 return [pad('-h, --help', width) + ' ' + 'output usage information']720 .concat(this.options.map(function(option){721 return pad(option.flags, width)722 + ' ' + option.description;723 }))724 .join('\n');725};726727/**728 * Return command help documentation.729 *730 * @return {String}731 * @api private732 */733734Command.prototype.commandHelp = function(){735 if (!this.commands.length) return '';736 return [737 ''738 , ' Commands:'739 , ''740 , this.commands.map(function(cmd){741 var args = cmd.args.map(function(arg){742 return arg.required743 ? '<' + arg.name + '>'744 : '[' + arg.name + ']';745 }).join(' ');746747 return pad(cmd._name748 + (cmd.options.length 749 ? ' [options]'750 : '') + ' ' + args, 18)751 + (cmd.description()752 ? ' ' + cmd.description()753 : '');754 }).join('\n').replace(/^/gm, ' ')755 , ''756 ].join('\n');757};758759/**760 * Return program help documentation.761 *762 * @return {String}763 * @api private764 */765766Command.prototype.helpInformation = function(){767 return [768 ''769 , ' Usage: ' + this._name + ' ' + this.usage()770 , '' + this.commandHelp()771 , ' Options:'772 , ''773 , '' + this.optionHelp().replace(/^/gm, ' ')774 , ''775 , ''776 ].join('\n');777};778779/**780 * Prompt for a `Number`.781 *782 * @param {String} str783 * @param {Function} fn784 * @api private785 */786787Command.prototype.promptForNumber = function(str, fn){788 var self = this;789 this.promptSingleLine(str, function parseNumber(val){790 val = Number(val);791 if (isNaN(val)) return self.promptSingleLine(str + '(must be a number) ', parseNumber);792 fn(val);793 });794};795796/**797 * Prompt for a `Date`.798 *799 * @param {String} str800 * @param {Function} fn801 * @api private802 */803804Command.prototype.promptForDate = function(str, fn){805 var self = this;806 this.promptSingleLine(str, function parseDate(val){807 val = new Date(val);808 if (isNaN(val.getTime())) return self.promptSingleLine(str + '(must be a date) ', parseDate);809 fn(val);810 });811};812813/**814 * Single-line prompt.815 *816 * @param {String} str817 * @param {Function} fn818 * @api private819 */820821Command.prototype.promptSingleLine = function(str, fn){822 if ('function' == typeof arguments[2]) {823 return this['promptFor' + (fn.name || fn)](str, arguments[2]);824 }825826 process.stdout.write(str);827 process.stdin.setEncoding('utf8');828 process.stdin.once('data', function(val){829 fn(val.trim());830 }).resume();831};832833/**834 * Multi-line prompt.835 *836 * @param {String} str837 * @param {Function} fn838 * @api private839 */840841Command.prototype.promptMultiLine = function(str, fn){842 var buf = [];843 console.log(str);844 process.stdin.setEncoding('utf8');845 process.stdin.on('data', function(val){846 if ('\n' == val || '\r\n' == val) {847 process.stdin.removeAllListeners('data');848 fn(buf.join('\n'));849 } else {850 buf.push(val.trimRight());851 }852 }).resume();853};854855/**856 * Prompt `str` and callback `fn(val)`857 *858 * Commander supports single-line and multi-line prompts.859 * To issue a single-line prompt simply add white-space860 * to the end of `str`, something like "name: ", whereas861 * for a multi-line prompt omit this "description:".862 *863 *864 * Examples:865 *866 * program.prompt('Username: ', function(name){867 * console.log('hi %s', name);868 * });869 * 870 * program.prompt('Description:', function(desc){871 * console.log('description was "%s"', desc.trim());872 * });873 *874 * @param {String|Object} str875 * @param {Function} fn876 * @api public877 */878879Command.prototype.prompt = function(str, fn){880 var self = this;881882 if ('string' == typeof str) {883 if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments);884 this.promptMultiLine(str, fn);885 } else {886 var keys = Object.keys(str)887 , obj = {};888889 function next() {890 var key = keys.shift()891 , label = str[key];892893 if (!key) return fn(obj);894 self.prompt(label, function(val){895 obj[key] = val;896 next();897 });898 }899900 next();901 }902};903904/**905 * Prompt for password with `str`, `mask` char and callback `fn(val)`.906 *907 * The mask string defaults to '', aka no output is908 * written while typing, you may want to use "*" etc.909 *910 * Examples:911 *912 * program.password('Password: ', function(pass){913 * console.log('got "%s"', pass);914 * process.stdin.destroy();915 * });916 *917 * program.password('Password: ', '*', function(pass){918 * console.log('got "%s"', pass);919 * process.stdin.destroy();920 * });921 *922 * @param {String} str923 * @param {String} mask924 * @param {Function} fn925 * @api public926 */927928Command.prototype.password = function(str, mask, fn){929 var self = this930 , buf = '';931932 // default mask933 if ('function' == typeof mask) {934 fn = mask;935 mask = '';936 }937938 keypress(process.stdin);939940 function setRawMode(mode) {941 if (process.stdin.setRawMode) {942 process.stdin.setRawMode(mode);943 } else {944 tty.setRawMode(mode);945 }946 };947 setRawMode(true);948 process.stdout.write(str);949950 // keypress951 process.stdin.on('keypress', function(c, key){952 if (key && 'enter' == key.name) {953 console.log();954 process.stdin.pause();955 process.stdin.removeAllListeners('keypress');956 setRawMode(false);957 if (!buf.trim().length) return self.password(str, mask, fn);958 fn(buf);959 return;960 }961962 if (key && key.ctrl && 'c' == key.name) {963 console.log('%s', buf);964 process.exit();965 }966967 process.stdout.write(mask);968 buf += c;969 }).resume();970};971972/**973 * Confirmation prompt with `str` and callback `fn(bool)`974 *975 * Examples:976 *977 * program.confirm('continue? ', function(ok){978 * console.log(' got %j', ok);979 * process.stdin.destroy();980 * });981 *982 * @param {String} str983 * @param {Function} fn984 * @api public985 */986987988Command.prototype.confirm = function(str, fn, verbose){989 var self = this;990 this.prompt(str, function(ok){991 if (!ok.trim()) {992 if (!verbose) str += '(yes or no) ';993 return self.confirm(str, fn, true);994 }995 fn(parseBool(ok));996 });997};998999/**1000 * Choice prompt with `list` of items and callback `fn(index, item)`1001 *1002 * Examples:1003 *1004 * var list = ['tobi', 'loki', 'jane', 'manny', 'luna'];1005 * 1006 * console.log('Choose the coolest pet:');1007 * program.choose(list, function(i){1008 * console.log('you chose %d "%s"', i, list[i]);1009 * process.stdin.destroy();1010 * });1011 *1012 * @param {Array} list1013 * @param {Number|Function} index or fn1014 * @param {Function} fn1015 * @api public1016 */10171018Command.prototype.choose = function(list, index, fn){1019 var self = this1020 , hasDefault = 'number' == typeof index;10211022 if (!hasDefault) {1023 fn = index;1024 index = null;1025 }10261027 list.forEach(function(item, i){1028 if (hasDefault && i == index) {1029 console.log('* %d) %s', i + 1, item);1030 } else {1031 console.log(' %d) %s', i + 1, item);1032 }1033 });10341035 function again() {1036 self.prompt(' : ', function(val){1037 val = parseInt(val, 10) - 1;1038 if (hasDefault && isNaN(val)) val = index;10391040 if (null == list[val]) {1041 again();1042 } else {1043 fn(val, list[val]);1044 }1045 });1046 }10471048 again();1049};105010511052/**1053 * Output help information for this command1054 *1055 * @api public1056 */10571058Command.prototype.outputHelp = function(){1059 process.stdout.write(this.helpInformation());1060 this.emit('--help');1061};10621063/**1064 * Output help information and exit.1065 *1066 * @api public1067 */10681069Command.prototype.help = function(){1070 this.outputHelp();1071 process.exit();1072};10731074/**1075 * Camel-case the given `flag`1076 *1077 * @param {String} flag1078 * @return {String}1079 * @api private1080 */10811082function camelcase(flag) {1083 return flag.split('-').reduce(function(str, word){1084 return str + word[0].toUpperCase() + word.slice(1);1085 });1086}10871088/**1089 * Parse a boolean `str`.1090 *1091 * @param {String} str1092 * @return {Boolean}1093 * @api private1094 */10951096function parseBool(str) {1097 return /^y|yes|ok|true$/i.test(str);1098}10991100/**1101 * Pad `str` to `width`.1102 *1103 * @param {String} str1104 * @param {Number} width1105 * @return {String}1106 * @api private1107 */11081109function pad(str, width) {1110 var len = Math.max(0, width - str.length);1111 return str + Array(len + 1).join(' ');1112}11131114/**1115 * Output help information if necessary1116 *1117 * @param {Command} command to output help for1118 * @param {Array} array of options to search for -h or --help1119 * @api private1120 */11211122function outputHelpIfNecessary(cmd, options) {1123 options = options || [];1124 for (var i = 0; i < options.length; i++) {1125 if (options[i] == '--help' || options[i] == '-h') {1126 cmd.outputHelp();1127 process.exit(0);1128 }1129 }1130}
modified:History.md+5 added
modified:index.js+1129 added-1 removed
1/*!2 * commander3 * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>4 * MIT Licensed5 */62module.exports = require('./lib/commander');7/**8 * Module dependencies.9 */1011var EventEmitter = require('events').EventEmitter12 , spawn = require('child_process').spawn13 , keypress = require('keypress')14 , fs = require('fs')15 , exists = fs.existsSync16 , path = require('path')17 , tty = require('tty')18 , dirname = path.dirname19 , basename = path.basename;2021/**22 * Expose the root command.23 */2425exports = module.exports = new Command;2627/**28 * Expose `Command`.29 */3031exports.Command = Command;3233/**34 * Expose `Option`.35 */3637exports.Option = Option;3839/**40 * Initialize a new `Option` with the given `flags` and `description`.41 *42 * @param {String} flags43 * @param {String} description44 * @api public45 */4647function Option(flags, description) {48 this.flags = flags;49 this.required = ~flags.indexOf('<');50 this.optional = ~flags.indexOf('[');51 this.bool = !~flags.indexOf('-no-');52 flags = flags.split(/[ ,|]+/);53 if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();54 this.long = flags.shift();55 this.description = description || '';56}5758/**59 * Return option name.60 *61 * @return {String}62 * @api private63 */6465Option.prototype.name = function(){66 return this.long67 .replace('--', '')68 .replace('no-', '');69};7071/**72 * Check if `arg` matches the short or long flag.73 *74 * @param {String} arg75 * @return {Boolean}76 * @api private77 */7879Option.prototype.is = function(arg){80 return arg == this.short81 || arg == this.long;82};8384/**85 * Initialize a new `Command`.86 *87 * @param {String} name88 * @api public89 */9091function Command(name) {92 this.commands = [];93 this.options = [];94 this.args = [];95 this._name = name;96}9798/**99 * Inherit from `EventEmitter.prototype`.100 */101102Command.prototype.__proto__ = EventEmitter.prototype;103104/**105 * Add command `name`.106 *107 * The `.action()` callback is invoked when the108 * command `name` is specified via __ARGV__,109 * and the remaining arguments are applied to the110 * function for access.111 *112 * When the `name` is "*" an un-matched command113 * will be passed as the first arg, followed by114 * the rest of __ARGV__ remaining.115 *116 * Examples:117 *118 * program119 * .version('0.0.1')120 * .option('-C, --chdir <path>', 'change the working directory')121 * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')122 * .option('-T, --no-tests', 'ignore test hook')123 * 124 * program125 * .command('setup')126 * .description('run remote setup commands')127 * .action(function(){128 * console.log('setup');129 * });130 * 131 * program132 * .command('exec <cmd>')133 * .description('run the given remote command')134 * .action(function(cmd){135 * console.log('exec "%s"', cmd);136 * });137 * 138 * program139 * .command('*')140 * .description('deploy the given env')141 * .action(function(env){142 * console.log('deploying "%s"', env);143 * });144 * 145 * program.parse(process.argv);146 *147 * @param {String} name148 * @param {String} [desc]149 * @return {Command} the new command150 * @api public151 */152153Command.prototype.command = function(name, desc){154 var args = name.split(/ +/);155 var cmd = new Command(args.shift());156 if (desc) cmd.description(desc);157 if (desc) this.executables = true;158 this.commands.push(cmd);159 cmd.parseExpectedArgs(args);160 cmd.parent = this;161 if (desc) return this;162 return cmd;163};164165/**166 * Add an implicit `help [cmd]` subcommand167 * which invokes `--help` for the given command.168 *169 * @api private170 */171172Command.prototype.addImplicitHelpCommand = function() {173 this.command('help [cmd]', 'display help for [cmd]');174};175176/**177 * Parse expected `args`.178 *179 * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.180 *181 * @param {Array} args182 * @return {Command} for chaining183 * @api public184 */185186Command.prototype.parseExpectedArgs = function(args){187 if (!args.length) return;188 var self = this;189 args.forEach(function(arg){190 switch (arg[0]) {191 case '<':192 self.args.push({ required: true, name: arg.slice(1, -1) });193 break;194 case '[':195 self.args.push({ required: false, name: arg.slice(1, -1) });196 break;197 }198 });199 return this;200};201202/**203 * Register callback `fn` for the command.204 *205 * Examples:206 *207 * program208 * .command('help')209 * .description('display verbose help')210 * .action(function(){211 * // output help here212 * });213 *214 * @param {Function} fn215 * @return {Command} for chaining216 * @api public217 */218219Command.prototype.action = function(fn){220 var self = this;221 this.parent.on(this._name, function(args, unknown){ 222 // Parse any so-far unknown options223 unknown = unknown || [];224 var parsed = self.parseOptions(unknown);225 226 // Output help if necessary227 outputHelpIfNecessary(self, parsed.unknown);228 229 // If there are still any unknown options, then we simply 230 // die, unless someone asked for help, in which case we give it231 // to them, and then we die.232 if (parsed.unknown.length > 0) { 233 self.unknownOption(parsed.unknown[0]);234 }235 236 // Leftover arguments need to be pushed back. Fixes issue #56237 if (parsed.args.length) args = parsed.args.concat(args);238 239 self.args.forEach(function(arg, i){240 if (arg.required && null == args[i]) {241 self.missingArgument(arg.name);242 }243 });244 245 // Always append ourselves to the end of the arguments,246 // to make sure we match the number of arguments the user247 // expects248 if (self.args.length) {249 args[self.args.length] = self;250 } else {251 args.push(self);252 }253 254 fn.apply(this, args);255 });256 return this;257};258259/**260 * Define option with `flags`, `description` and optional261 * coercion `fn`. 262 *263 * The `flags` string should contain both the short and long flags,264 * separated by comma, a pipe or space. The following are all valid265 * all will output this way when `--help` is used.266 *267 * "-p, --pepper"268 * "-p|--pepper"269 * "-p --pepper"270 *271 * Examples:272 *273 * // simple boolean defaulting to false274 * program.option('-p, --pepper', 'add pepper');275 *276 * --pepper277 * program.pepper278 * // => Boolean279 *280 * // simple boolean defaulting to false281 * program.option('-C, --no-cheese', 'remove cheese');282 *283 * program.cheese284 * // => true285 *286 * --no-cheese287 * program.cheese288 * // => true289 *290 * // required argument291 * program.option('-C, --chdir <path>', 'change the working directory');292 *293 * --chdir /tmp294 * program.chdir295 * // => "/tmp"296 *297 * // optional argument298 * program.option('-c, --cheese [type]', 'add cheese [marble]');299 *300 * @param {String} flags301 * @param {String} description302 * @param {Function|Mixed} fn or default303 * @param {Mixed} defaultValue304 * @return {Command} for chaining305 * @api public306 */307308Command.prototype.option = function(flags, description, fn, defaultValue){309 var self = this310 , option = new Option(flags, description)311 , oname = option.name()312 , name = camelcase(oname);313314 // default as 3rd arg315 if ('function' != typeof fn) defaultValue = fn, fn = null;316317 // preassign default value only for --no-*, [optional], or <required>318 if (false == option.bool || option.optional || option.required) {319 // when --no-* we make sure default is true320 if (false == option.bool) defaultValue = true;321 // preassign only if we have a default322 if (undefined !== defaultValue) self[name] = defaultValue;323 }324325 // register the option326 this.options.push(option);327328 // when it's passed assign the value329 // and conditionally invoke the callback330 this.on(oname, function(val){331 // coercion332 if (null != val && fn) val = fn(val);333334 // unassigned or bool335 if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) {336 // if no value, bool true, and we have a default, then use it!337 if (null == val) {338 self[name] = option.bool339 ? defaultValue || true340 : false;341 } else {342 self[name] = val;343 }344 } else if (null !== val) {345 // reassign346 self[name] = val;347 }348 });349350 return this;351};352353/**354 * Parse `argv`, settings options and invoking commands when defined.355 *356 * @param {Array} argv357 * @return {Command} for chaining358 * @api public359 */360361Command.prototype.parse = function(argv){362 // implicit help363 if (this.executables) this.addImplicitHelpCommand();364365 // store raw args366 this.rawArgs = argv;367368 // guess name369 this._name = this._name || basename(argv[1]);370371 // process argv372 var parsed = this.parseOptions(this.normalize(argv.slice(2)));373 var args = this.args = parsed.args;374 375 // executable sub-commands, skip .parseArgs()376 if (this.executables) return this.executeSubCommand(argv, args, parsed.unknown);377378 return this.parseArgs(this.args, parsed.unknown);379};380381/**382 * Execute a sub-command executable.383 *384 * @param {Array} argv385 * @param {Array} args386 * @param {Array} unknown387 * @api private388 */389390Command.prototype.executeSubCommand = function(argv, args, unknown) {391 args = args.concat(unknown);392393 if (!args.length) this.help();394 if ('help' == args[0] && 1 == args.length) this.help();395396 // <cmd> --help397 if ('help' == args[0]) {398 args[0] = args[1];399 args[1] = '--help';400 }401402 // executable403 var dir = dirname(argv[1]);404 var bin = basename(argv[1]) + '-' + args[0];405406 // check for ./<bin> first407 var local = path.join(dir, bin);408 if (exists(local)) bin = local;409410 // run it411 args = args.slice(1);412 var proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] });413 proc.on('exit', function(code){414 if (code == 127) {415 console.error('\n %s(1) does not exist\n', bin);416 }417 });418};419420/**421 * Normalize `args`, splitting joined short flags. For example422 * the arg "-abc" is equivalent to "-a -b -c".423 * This also normalizes equal sign and splits "--abc=def" into "--abc def".424 *425 * @param {Array} args426 * @return {Array}427 * @api private428 */429430Command.prototype.normalize = function(args){431 var ret = []432 , arg433 , index;434435 for (var i = 0, len = args.length; i < len; ++i) {436 arg = args[i];437 if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) {438 arg.slice(1).split('').forEach(function(c){439 ret.push('-' + c);440 });441 } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {442 ret.push(arg.slice(0, index), arg.slice(index + 1));443 } else {444 ret.push(arg);445 }446 }447448 return ret;449};450451/**452 * Parse command `args`.453 *454 * When listener(s) are available those455 * callbacks are invoked, otherwise the "*"456 * event is emitted and those actions are invoked.457 *458 * @param {Array} args459 * @return {Command} for chaining460 * @api private461 */462463Command.prototype.parseArgs = function(args, unknown){464 var cmds = this.commands465 , len = cmds.length466 , name;467468 if (args.length) {469 name = args[0];470 if (this.listeners(name).length) {471 this.emit(args.shift(), args, unknown);472 } else {473 this.emit('*', args);474 }475 } else {476 outputHelpIfNecessary(this, unknown);477 478 // If there were no args and we have unknown options,479 // then they are extraneous and we need to error.480 if (unknown.length > 0) { 481 this.unknownOption(unknown[0]);482 }483 }484485 return this;486};487488/**489 * Return an option matching `arg` if any.490 *491 * @param {String} arg492 * @return {Option}493 * @api private494 */495496Command.prototype.optionFor = function(arg){497 for (var i = 0, len = this.options.length; i < len; ++i) {498 if (this.options[i].is(arg)) {499 return this.options[i];500 }501 }502};503504/**505 * Parse options from `argv` returning `argv`506 * void of these options.507 *508 * @param {Array} argv509 * @return {Array}510 * @api public511 */512513Command.prototype.parseOptions = function(argv){514 var args = []515 , len = argv.length516 , literal517 , option518 , arg;519520 var unknownOptions = [];521522 // parse options523 for (var i = 0; i < len; ++i) {524 arg = argv[i];525526 // literal args after --527 if ('--' == arg) {528 literal = true;529 continue;530 }531532 if (literal) {533 args.push(arg);534 continue;535 }536537 // find matching Option538 option = this.optionFor(arg);539540 // option is defined541 if (option) {542 // requires arg543 if (option.required) {544 arg = argv[++i];545 if (null == arg) return this.optionMissingArgument(option);546 if ('-' == arg[0]) return this.optionMissingArgument(option, arg);547 this.emit(option.name(), arg);548 // optional arg549 } else if (option.optional) {550 arg = argv[i+1];551 if (null == arg || '-' == arg[0]) {552 arg = null;553 } else {554 ++i;555 }556 this.emit(option.name(), arg);557 // bool558 } else {559 this.emit(option.name());560 }561 continue;562 }563 564 // looks like an option565 if (arg.length > 1 && '-' == arg[0]) {566 unknownOptions.push(arg);567 568 // If the next argument looks like it might be569 // an argument for this option, we pass it on.570 // If it isn't, then it'll simply be ignored571 if (argv[i+1] && '-' != argv[i+1][0]) {572 unknownOptions.push(argv[++i]);573 }574 continue;575 }576 577 // arg578 args.push(arg);579 }580 581 return { args: args, unknown: unknownOptions };582};583584/**585 * Argument `name` is missing.586 *587 * @param {String} name588 * @api private589 */590591Command.prototype.missingArgument = function(name){592 console.error();593 console.error(" error: missing required argument `%s'", name);594 console.error();595 process.exit(1);596};597598/**599 * `Option` is missing an argument, but received `flag` or nothing.600 *601 * @param {String} option602 * @param {String} flag603 * @api private604 */605606Command.prototype.optionMissingArgument = function(option, flag){607 console.error();608 if (flag) {609 console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag);610 } else {611 console.error(" error: option `%s' argument missing", option.flags);612 }613 console.error();614 process.exit(1);615};616617/**618 * Unknown option `flag`.619 *620 * @param {String} flag621 * @api private622 */623624Command.prototype.unknownOption = function(flag){625 console.error();626 console.error(" error: unknown option `%s'", flag);627 console.error();628 process.exit(1);629};630631632/**633 * Set the program version to `str`.634 *635 * This method auto-registers the "-V, --version" flag636 * which will print the version number when passed.637 *638 * @param {String} str639 * @param {String} flags640 * @return {Command} for chaining641 * @api public642 */643644Command.prototype.version = function(str, flags){645 if (0 == arguments.length) return this._version;646 this._version = str;647 flags = flags || '-V, --version';648 this.option(flags, 'output the version number');649 this.on('version', function(){650 console.log(str);651 process.exit(0);652 });653 return this;654};655656/**657 * Set the description `str`.658 *659 * @param {String} str660 * @return {String|Command}661 * @api public662 */663664Command.prototype.description = function(str){665 if (0 == arguments.length) return this._description;666 this._description = str;667 return this;668};669670/**671 * Set / get the command usage `str`.672 *673 * @param {String} str674 * @return {String|Command}675 * @api public676 */677678Command.prototype.usage = function(str){679 var args = this.args.map(function(arg){680 return arg.required681 ? '<' + arg.name + '>'682 : '[' + arg.name + ']';683 });684685 var usage = '[options'686 + (this.commands.length ? '] [command' : '')687 + ']'688 + (this.args.length ? ' ' + args : '');689 if (0 == arguments.length) return this._usage || usage;690 this._usage = str;691692 return this;693};694695/**696 * Return the largest option length.697 *698 * @return {Number}699 * @api private700 */701702Command.prototype.largestOptionLength = function(){703 return this.options.reduce(function(max, option){704 return Math.max(max, option.flags.length);705 }, 0);706};707708/**709 * Return help for options.710 *711 * @return {String}712 * @api private713 */714715Command.prototype.optionHelp = function(){716 var width = this.largestOptionLength();717 718 // Prepend the help information719 return [pad('-h, --help', width) + ' ' + 'output usage information']720 .concat(this.options.map(function(option){721 return pad(option.flags, width)722 + ' ' + option.description;723 }))724 .join('\n');725};726727/**728 * Return command help documentation.729 *730 * @return {String}731 * @api private732 */733734Command.prototype.commandHelp = function(){735 if (!this.commands.length) return '';736 return [737 ''738 , ' Commands:'739 , ''740 , this.commands.map(function(cmd){741 var args = cmd.args.map(function(arg){742 return arg.required743 ? '<' + arg.name + '>'744 : '[' + arg.name + ']';745 }).join(' ');746747 return pad(cmd._name748 + (cmd.options.length 749 ? ' [options]'750 : '') + ' ' + args, 18)751 + (cmd.description()752 ? ' ' + cmd.description()753 : '');754 }).join('\n').replace(/^/gm, ' ')755 , ''756 ].join('\n');757};758759/**760 * Return program help documentation.761 *762 * @return {String}763 * @api private764 */765766Command.prototype.helpInformation = function(){767 return [768 ''769 , ' Usage: ' + this._name + ' ' + this.usage()770 , '' + this.commandHelp()771 , ' Options:'772 , ''773 , '' + this.optionHelp().replace(/^/gm, ' ')774 , ''775 , ''776 ].join('\n');777};778779/**780 * Prompt for a `Number`.781 *782 * @param {String} str783 * @param {Function} fn784 * @api private785 */786787Command.prototype.promptForNumber = function(str, fn){788 var self = this;789 this.promptSingleLine(str, function parseNumber(val){790 val = Number(val);791 if (isNaN(val)) return self.promptSingleLine(str + '(must be a number) ', parseNumber);792 fn(val);793 });794};795796/**797 * Prompt for a `Date`.798 *799 * @param {String} str800 * @param {Function} fn801 * @api private802 */803804Command.prototype.promptForDate = function(str, fn){805 var self = this;806 this.promptSingleLine(str, function parseDate(val){807 val = new Date(val);808 if (isNaN(val.getTime())) return self.promptSingleLine(str + '(must be a date) ', parseDate);809 fn(val);810 });811};812813/**814 * Single-line prompt.815 *816 * @param {String} str817 * @param {Function} fn818 * @api private819 */820821Command.prototype.promptSingleLine = function(str, fn){822 if ('function' == typeof arguments[2]) {823 return this['promptFor' + (fn.name || fn)](str, arguments[2]);824 }825826 process.stdout.write(str);827 process.stdin.setEncoding('utf8');828 process.stdin.once('data', function(val){829 fn(val.trim());830 }).resume();831};832833/**834 * Multi-line prompt.835 *836 * @param {String} str837 * @param {Function} fn838 * @api private839 */840841Command.prototype.promptMultiLine = function(str, fn){842 var buf = [];843 console.log(str);844 process.stdin.setEncoding('utf8');845 process.stdin.on('data', function(val){846 if ('\n' == val || '\r\n' == val) {847 process.stdin.removeAllListeners('data');848 fn(buf.join('\n'));849 } else {850 buf.push(val.trimRight());851 }852 }).resume();853};854855/**856 * Prompt `str` and callback `fn(val)`857 *858 * Commander supports single-line and multi-line prompts.859 * To issue a single-line prompt simply add white-space860 * to the end of `str`, something like "name: ", whereas861 * for a multi-line prompt omit this "description:".862 *863 *864 * Examples:865 *866 * program.prompt('Username: ', function(name){867 * console.log('hi %s', name);868 * });869 * 870 * program.prompt('Description:', function(desc){871 * console.log('description was "%s"', desc.trim());872 * });873 *874 * @param {String|Object} str875 * @param {Function} fn876 * @api public877 */878879Command.prototype.prompt = function(str, fn){880 var self = this;881882 if ('string' == typeof str) {883 if (/ $/.test(str)) return this.promptSingleLine.apply(this, arguments);884 this.promptMultiLine(str, fn);885 } else {886 var keys = Object.keys(str)887 , obj = {};888889 function next() {890 var key = keys.shift()891 , label = str[key];892893 if (!key) return fn(obj);894 self.prompt(label, function(val){895 obj[key] = val;896 next();897 });898 }899900 next();901 }902};903904/**905 * Prompt for password with `str`, `mask` char and callback `fn(val)`.906 *907 * The mask string defaults to '', aka no output is908 * written while typing, you may want to use "*" etc.909 *910 * Examples:911 *912 * program.password('Password: ', function(pass){913 * console.log('got "%s"', pass);914 * process.stdin.destroy();915 * });916 *917 * program.password('Password: ', '*', function(pass){918 * console.log('got "%s"', pass);919 * process.stdin.destroy();920 * });921 *922 * @param {String} str923 * @param {String} mask924 * @param {Function} fn925 * @api public926 */927928Command.prototype.password = function(str, mask, fn){929 var self = this930 , buf = '';931932 // default mask933 if ('function' == typeof mask) {934 fn = mask;935 mask = '';936 }937938 keypress(process.stdin);939940 function setRawMode(mode) {941 if (process.stdin.setRawMode) {942 process.stdin.setRawMode(mode);943 } else {944 tty.setRawMode(mode);945 }946 };947 setRawMode(true);948 process.stdout.write(str);949950 // keypress951 process.stdin.on('keypress', function(c, key){952 if (key && 'enter' == key.name) {953 console.log();954 process.stdin.pause();955 process.stdin.removeAllListeners('keypress');956 setRawMode(false);957 if (!buf.trim().length) return self.password(str, mask, fn);958 fn(buf);959 return;960 }961962 if (key && key.ctrl && 'c' == key.name) {963 console.log('%s', buf);964 process.exit();965 }966967 process.stdout.write(mask);968 buf += c;969 }).resume();970};971972/**973 * Confirmation prompt with `str` and callback `fn(bool)`974 *975 * Examples:976 *977 * program.confirm('continue? ', function(ok){978 * console.log(' got %j', ok);979 * process.stdin.destroy();980 * });981 *982 * @param {String} str983 * @param {Function} fn984 * @api public985 */986987988Command.prototype.confirm = function(str, fn, verbose){989 var self = this;990 this.prompt(str, function(ok){991 if (!ok.trim()) {992 if (!verbose) str += '(yes or no) ';993 return self.confirm(str, fn, true);994 }995 fn(parseBool(ok));996 });997};998999/**1000 * Choice prompt with `list` of items and callback `fn(index, item)`1001 *1002 * Examples:1003 *1004 * var list = ['tobi', 'loki', 'jane', 'manny', 'luna'];1005 * 1006 * console.log('Choose the coolest pet:');1007 * program.choose(list, function(i){1008 * console.log('you chose %d "%s"', i, list[i]);1009 * process.stdin.destroy();1010 * });1011 *1012 * @param {Array} list1013 * @param {Number|Function} index or fn1014 * @param {Function} fn1015 * @api public1016 */10171018Command.prototype.choose = function(list, index, fn){1019 var self = this1020 , hasDefault = 'number' == typeof index;10211022 if (!hasDefault) {1023 fn = index;1024 index = null;1025 }10261027 list.forEach(function(item, i){1028 if (hasDefault && i == index) {1029 console.log('* %d) %s', i + 1, item);1030 } else {1031 console.log(' %d) %s', i + 1, item);1032 }1033 });10341035 function again() {1036 self.prompt(' : ', function(val){1037 val = parseInt(val, 10) - 1;1038 if (hasDefault && isNaN(val)) val = index;10391040 if (null == list[val]) {1041 again();1042 } else {1043 fn(val, list[val]);1044 }1045 });1046 }10471048 again();1049};105010511052/**1053 * Output help information for this command1054 *1055 * @api public1056 */10571058Command.prototype.outputHelp = function(){1059 process.stdout.write(this.helpInformation());1060 this.emit('--help');1061};10621063/**1064 * Output help information and exit.1065 *1066 * @api public1067 */10681069Command.prototype.help = function(){1070 this.outputHelp();1071 process.exit();1072};10731074/**1075 * Camel-case the given `flag`1076 *1077 * @param {String} flag1078 * @return {String}1079 * @api private1080 */10811082function camelcase(flag) {1083 return flag.split('-').reduce(function(str, word){1084 return str + word[0].toUpperCase() + word.slice(1);1085 });1086}10871088/**1089 * Parse a boolean `str`.1090 *1091 * @param {String} str1092 * @return {Boolean}1093 * @api private1094 */10951096function parseBool(str) {1097 return /^y|yes|ok|true$/i.test(str);1098}10991100/**1101 * Pad `str` to `width`.1102 *1103 * @param {String} str1104 * @param {Number} width1105 * @return {String}1106 * @api private1107 */11081109function pad(str, width) {1110 var len = Math.max(0, width - str.length);1111 return str + Array(len + 1).join(' ');1112}11131114/**1115 * Output help information if necessary1116 *1117 * @param {Command} command to output help for1118 * @param {Array} array of options to search for -h or --help1119 * @api private1120 */11211122function outputHelpIfNecessary(cmd, options) {1123 options = options || [];1124 for (var i = 0; i < options.length; i++) {1125 if (options[i] == '--help' || options[i] == '-h') {1126 cmd.outputHelp();1127 process.exit(0);1128 }1129 }1130}
modified:package.json+1 added-1 removed