5 var EventEmitter = require('events').EventEmitter;
6 var spawn = require('child_process').spawn;
7 var path = require('path');
8 var dirname = path.dirname;
9 var basename = path.basename;
10 var fs = require('fs');
13 * Inherit `Command` from `EventEmitter.prototype`.
16 require('util').inherits(Command, EventEmitter);
19 * Expose the root command.
22 exports = module.exports = new Command();
28 exports.Command = Command;
34 exports.Option = Option;
37 * Initialize a new `Option` with the given `flags` and `description`.
39 * @param {String} flags
40 * @param {String} description
44 function Option(flags, description) {
46 this.required = flags.indexOf('<') >= 0;
47 this.optional = flags.indexOf('[') >= 0;
48 this.bool = flags.indexOf('-no-') === -1;
49 flags = flags.split(/[ ,|]+/);
50 if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();
51 this.long = flags.shift();
52 this.description = description || '';
62 Option.prototype.name = function() {
69 * Return option name, in a camelcase format that can be used
70 * as a object attribute key.
76 Option.prototype.attributeName = function() {
77 return camelcase(this.name());
81 * Check if `arg` matches the short or long flag.
88 Option.prototype.is = function(arg) {
89 return this.short === arg || this.long === arg;
93 * Initialize a new `Command`.
95 * @param {String} name
99 function Command(name) {
103 this._allowUnknownOption = false;
105 this._name = name || '';
109 * Add command `name`.
111 * The `.action()` callback is invoked when the
112 * command `name` is specified via __ARGV__,
113 * and the remaining arguments are applied to the
114 * function for access.
116 * When the `name` is "*" an un-matched command
117 * will be passed as the first arg, followed by
118 * the rest of __ARGV__ remaining.
124 * .option('-C, --chdir <path>', 'change the working directory')
125 * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
126 * .option('-T, --no-tests', 'ignore test hook')
130 * .description('run remote setup commands')
131 * .action(function() {
132 * console.log('setup');
136 * .command('exec <cmd>')
137 * .description('run the given remote command')
138 * .action(function(cmd) {
139 * console.log('exec "%s"', cmd);
143 * .command('teardown <dir> [otherDirs...]')
144 * .description('run teardown commands')
145 * .action(function(dir, otherDirs) {
146 * console.log('dir "%s"', dir);
148 * otherDirs.forEach(function (oDir) {
149 * console.log('dir "%s"', oDir);
156 * .description('deploy the given env')
157 * .action(function(env) {
158 * console.log('deploying "%s"', env);
161 * program.parse(process.argv);
163 * @param {String} name
164 * @param {String} [desc] for git-style sub-commands
165 * @return {Command} the new command
169 Command.prototype.command = function(name, desc, opts) {
170 if (typeof desc === 'object' && desc !== null) {
175 var args = name.split(/ +/);
176 var cmd = new Command(args.shift());
179 cmd.description(desc);
180 this.executables = true;
181 this._execs[cmd._name] = true;
182 if (opts.isDefault) this.defaultExecutable = cmd._name;
184 cmd._noHelp = !!opts.noHelp;
185 this.commands.push(cmd);
186 cmd.parseExpectedArgs(args);
189 if (desc) return this;
194 * Define argument syntax for the top-level command.
199 Command.prototype.arguments = function(desc) {
200 return this.parseExpectedArgs(desc.split(/ +/));
204 * Add an implicit `help [cmd]` subcommand
205 * which invokes `--help` for the given command.
210 Command.prototype.addImplicitHelpCommand = function() {
211 this.command('help [cmd]', 'display help for [cmd]');
215 * Parse expected `args`.
217 * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
219 * @param {Array} args
220 * @return {Command} for chaining
224 Command.prototype.parseExpectedArgs = function(args) {
225 if (!args.length) return;
227 args.forEach(function(arg) {
236 argDetails.required = true;
237 argDetails.name = arg.slice(1, -1);
240 argDetails.name = arg.slice(1, -1);
244 if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
245 argDetails.variadic = true;
246 argDetails.name = argDetails.name.slice(0, -3);
248 if (argDetails.name) {
249 self._args.push(argDetails);
256 * Register callback `fn` for the command.
262 * .description('display verbose help')
263 * .action(function() {
264 * // output help here
267 * @param {Function} fn
268 * @return {Command} for chaining
272 Command.prototype.action = function(fn) {
274 var listener = function(args, unknown) {
275 // Parse any so-far unknown options
277 unknown = unknown || [];
279 var parsed = self.parseOptions(unknown);
281 // Output help if necessary
282 outputHelpIfNecessary(self, parsed.unknown);
284 // If there are still any unknown options, then we simply
285 // die, unless someone asked for help, in which case we give it
286 // to them, and then we die.
287 if (parsed.unknown.length > 0) {
288 self.unknownOption(parsed.unknown[0]);
291 // Leftover arguments need to be pushed back. Fixes issue #56
292 if (parsed.args.length) args = parsed.args.concat(args);
294 self._args.forEach(function(arg, i) {
295 if (arg.required && args[i] == null) {
296 self.missingArgument(arg.name);
297 } else if (arg.variadic) {
298 if (i !== self._args.length - 1) {
299 self.variadicArgNotLast(arg.name);
302 args[i] = args.splice(i);
306 // Always append ourselves to the end of the arguments,
307 // to make sure we match the number of arguments the user
309 if (self._args.length) {
310 args[self._args.length] = self;
315 fn.apply(self, args);
317 var parent = this.parent || this;
318 var name = parent === this ? '*' : this._name;
319 parent.on('command:' + name, listener);
320 if (this._alias) parent.on('command:' + this._alias, listener);
325 * Define option with `flags`, `description` and optional
328 * The `flags` string should contain both the short and long flags,
329 * separated by comma, a pipe or space. The following are all valid
330 * all will output this way when `--help` is used.
338 * // simple boolean defaulting to false
339 * program.option('-p, --pepper', 'add pepper');
345 * // simple boolean defaulting to true
346 * program.option('-C, --no-cheese', 'remove cheese');
355 * // required argument
356 * program.option('-C, --chdir <path>', 'change the working directory');
362 * // optional argument
363 * program.option('-c, --cheese [type]', 'add cheese [marble]');
365 * @param {String} flags
366 * @param {String} description
367 * @param {Function|*} [fn] or default
368 * @param {*} [defaultValue]
369 * @return {Command} for chaining
373 Command.prototype.option = function(flags, description, fn, defaultValue) {
375 option = new Option(flags, description),
376 oname = option.name(),
377 name = option.attributeName();
379 // default as 3rd arg
380 if (typeof fn !== 'function') {
381 if (fn instanceof RegExp) {
383 fn = function(val, def) {
384 var m = regex.exec(val);
385 return m ? m[0] : def;
393 // preassign default value only for --no-*, [optional], or <required>
394 if (!option.bool || option.optional || option.required) {
395 // when --no-* we make sure default is true
396 if (!option.bool) defaultValue = true;
397 // preassign only if we have a default
398 if (defaultValue !== undefined) {
399 self[name] = defaultValue;
400 option.defaultValue = defaultValue;
404 // register the option
405 this.options.push(option);
407 // when it's passed assign the value
408 // and conditionally invoke the callback
409 this.on('option:' + oname, function(val) {
411 if (val !== null && fn) {
412 val = fn(val, self[name] === undefined ? defaultValue : self[name]);
415 // unassigned or bool
416 if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') {
417 // if no value, bool true, and we have a default, then use it!
419 self[name] = option.bool
420 ? defaultValue || true
425 } else if (val !== null) {
435 * Allow unknown options on the command line.
437 * @param {Boolean} arg if `true` or omitted, no error will be thrown
438 * for unknown options.
441 Command.prototype.allowUnknownOption = function(arg) {
442 this._allowUnknownOption = arguments.length === 0 || arg;
447 * Parse `argv`, settings options and invoking commands when defined.
449 * @param {Array} argv
450 * @return {Command} for chaining
454 Command.prototype.parse = function(argv) {
456 if (this.executables) this.addImplicitHelpCommand();
462 this._name = this._name || basename(argv[1], '.js');
464 // github-style sub-commands with no sub-command
465 if (this.executables && argv.length < 3 && !this.defaultExecutable) {
466 // this user needs help
471 var parsed = this.parseOptions(this.normalize(argv.slice(2)));
472 var args = this.args = parsed.args;
474 var result = this.parseArgs(this.args, parsed.unknown);
476 // executable sub-commands
477 var name = result.args[0];
479 var aliasCommand = null;
480 // check alias of sub commands
482 aliasCommand = this.commands.filter(function(command) {
483 return command.alias() === name;
487 if (this._execs[name] === true) {
488 return this.executeSubCommand(argv, args, parsed.unknown);
489 } else if (aliasCommand) {
490 // is alias of a subCommand
491 args[0] = aliasCommand._name;
492 return this.executeSubCommand(argv, args, parsed.unknown);
493 } else if (this.defaultExecutable) {
494 // use the default subcommand
495 args.unshift(this.defaultExecutable);
496 return this.executeSubCommand(argv, args, parsed.unknown);
503 * Execute a sub-command executable.
505 * @param {Array} argv
506 * @param {Array} args
507 * @param {Array} unknown
511 Command.prototype.executeSubCommand = function(argv, args, unknown) {
512 args = args.concat(unknown);
514 if (!args.length) this.help();
515 if (args[0] === 'help' && args.length === 1) this.help();
518 if (args[0] === 'help') {
525 // name of the subcommand, link `pm-install`
526 var bin = basename(f, path.extname(f)) + '-' + args[0];
528 // In case of globally installed, get the base dir where executable
529 // subcommand file should be located at
532 var resolvedLink = fs.realpathSync(f);
534 baseDir = dirname(resolvedLink);
536 // prefer local `./<bin>` to bin in the $PATH
537 var localBin = path.join(baseDir, bin);
539 // whether bin file is a js script with explicit `.js` or `.ts` extension
540 var isExplicitJS = false;
541 if (exists(localBin + '.js')) {
542 bin = localBin + '.js';
544 } else if (exists(localBin + '.ts')) {
545 bin = localBin + '.ts';
547 } else if (exists(localBin)) {
551 args = args.slice(1);
554 if (process.platform !== 'win32') {
557 // add executable arguments to spawn
558 args = (process.execArgv || []).concat(args);
560 proc = spawn(process.argv[0], args, { stdio: 'inherit', customFds: [0, 1, 2] });
562 proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] });
566 proc = spawn(process.execPath, args, { stdio: 'inherit' });
569 var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
570 signals.forEach(function(signal) {
571 process.on(signal, function() {
572 if (proc.killed === false && proc.exitCode === null) {
577 proc.on('close', process.exit.bind(process));
578 proc.on('error', function(err) {
579 if (err.code === 'ENOENT') {
580 console.error('error: %s(1) does not exist, try --help', bin);
581 } else if (err.code === 'EACCES') {
582 console.error('error: %s(1) not executable. try chmod or run with root', bin);
587 // Store the reference to the child process
588 this.runningCommand = proc;
592 * Normalize `args`, splitting joined short flags. For example
593 * the arg "-abc" is equivalent to "-a -b -c".
594 * This also normalizes equal sign and splits "--abc=def" into "--abc def".
596 * @param {Array} args
601 Command.prototype.normalize = function(args) {
607 for (var i = 0, len = args.length; i < len; ++i) {
610 lastOpt = this.optionFor(args[i - 1]);
614 // Honor option terminator
615 ret = ret.concat(args.slice(i));
617 } else if (lastOpt && lastOpt.required) {
619 } else if (arg.length > 1 && arg[0] === '-' && arg[1] !== '-') {
620 arg.slice(1).split('').forEach(function(c) {
623 } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {
624 ret.push(arg.slice(0, index), arg.slice(index + 1));
634 * Parse command `args`.
636 * When listener(s) are available those
637 * callbacks are invoked, otherwise the "*"
638 * event is emitted and those actions are invoked.
640 * @param {Array} args
641 * @return {Command} for chaining
645 Command.prototype.parseArgs = function(args, unknown) {
650 if (this.listeners('command:' + name).length) {
651 this.emit('command:' + args.shift(), args, unknown);
653 this.emit('command:*', args);
656 outputHelpIfNecessary(this, unknown);
658 // If there were no args and we have unknown options,
659 // then they are extraneous and we need to error.
660 if (unknown.length > 0) {
661 this.unknownOption(unknown[0]);
663 if (this.commands.length === 0 &&
664 this._args.filter(function(a) { return a.required; }).length === 0) {
665 this.emit('command:*');
673 * Return an option matching `arg` if any.
675 * @param {String} arg
680 Command.prototype.optionFor = function(arg) {
681 for (var i = 0, len = this.options.length; i < len; ++i) {
682 if (this.options[i].is(arg)) {
683 return this.options[i];
689 * Parse options from `argv` returning `argv`
690 * void of these options.
692 * @param {Array} argv
697 Command.prototype.parseOptions = function(argv) {
704 var unknownOptions = [];
707 for (var i = 0; i < len; ++i) {
710 // literal args after --
721 // find matching Option
722 option = this.optionFor(arg);
727 if (option.required) {
729 if (arg == null) return this.optionMissingArgument(option);
730 this.emit('option:' + option.name(), arg);
732 } else if (option.optional) {
734 if (arg == null || (arg[0] === '-' && arg !== '-')) {
739 this.emit('option:' + option.name(), arg);
742 this.emit('option:' + option.name());
747 // looks like an option
748 if (arg.length > 1 && arg[0] === '-') {
749 unknownOptions.push(arg);
751 // If the next argument looks like it might be
752 // an argument for this option, we pass it on.
753 // If it isn't, then it'll simply be ignored
754 if ((i + 1) < argv.length && argv[i + 1][0] !== '-') {
755 unknownOptions.push(argv[++i]);
764 return { args: args, unknown: unknownOptions };
768 * Return an object containing options as key-value pairs
773 Command.prototype.opts = function() {
775 len = this.options.length;
777 for (var i = 0; i < len; i++) {
778 var key = this.options[i].attributeName();
779 result[key] = key === this._versionOptionName ? this._version : this[key];
785 * Argument `name` is missing.
787 * @param {String} name
791 Command.prototype.missingArgument = function(name) {
792 console.error("error: missing required argument `%s'", name);
797 * `Option` is missing an argument, but received `flag` or nothing.
799 * @param {String} option
800 * @param {String} flag
804 Command.prototype.optionMissingArgument = function(option, flag) {
806 console.error("error: option `%s' argument missing, got `%s'", option.flags, flag);
808 console.error("error: option `%s' argument missing", option.flags);
814 * Unknown option `flag`.
816 * @param {String} flag
820 Command.prototype.unknownOption = function(flag) {
821 if (this._allowUnknownOption) return;
822 console.error("error: unknown option `%s'", flag);
827 * Variadic argument with `name` is not the last argument as required.
829 * @param {String} name
833 Command.prototype.variadicArgNotLast = function(name) {
834 console.error("error: variadic arguments must be last `%s'", name);
839 * Set the program version to `str`.
841 * This method auto-registers the "-V, --version" flag
842 * which will print the version number when passed.
844 * @param {String} str
845 * @param {String} [flags]
846 * @return {Command} for chaining
850 Command.prototype.version = function(str, flags) {
851 if (arguments.length === 0) return this._version;
853 flags = flags || '-V, --version';
854 var versionOption = new Option(flags, 'output the version number');
855 this._versionOptionName = versionOption.long.substr(2) || 'version';
856 this.options.push(versionOption);
857 this.on('option:' + this._versionOptionName, function() {
858 process.stdout.write(str + '\n');
865 * Set the description to `str`.
867 * @param {String} str
868 * @param {Object} argsDescription
869 * @return {String|Command}
873 Command.prototype.description = function(str, argsDescription) {
874 if (arguments.length === 0) return this._description;
875 this._description = str;
876 this._argsDescription = argsDescription;
881 * Set an alias for the command
883 * @param {String} alias
884 * @return {String|Command}
888 Command.prototype.alias = function(alias) {
890 if (this.commands.length !== 0) {
891 command = this.commands[this.commands.length - 1];
894 if (arguments.length === 0) return command._alias;
896 if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
898 command._alias = alias;
903 * Set / get the command usage `str`.
905 * @param {String} str
906 * @return {String|Command}
910 Command.prototype.usage = function(str) {
911 var args = this._args.map(function(arg) {
912 return humanReadableArgName(arg);
915 var usage = '[options]' +
916 (this.commands.length ? ' [command]' : '') +
917 (this._args.length ? ' ' + args.join(' ') : '');
919 if (arguments.length === 0) return this._usage || usage;
926 * Get or set the name of the command
928 * @param {String} str
929 * @return {String|Command}
933 Command.prototype.name = function(str) {
934 if (arguments.length === 0) return this._name;
940 * Return prepared commands.
946 Command.prototype.prepareCommands = function() {
947 return this.commands.filter(function(cmd) {
949 }).map(function(cmd) {
950 var args = cmd._args.map(function(arg) {
951 return humanReadableArgName(arg);
956 (cmd._alias ? '|' + cmd._alias : '') +
957 (cmd.options.length ? ' [options]' : '') +
958 (args ? ' ' + args : ''),
965 * Return the largest command length.
971 Command.prototype.largestCommandLength = function() {
972 var commands = this.prepareCommands();
973 return commands.reduce(function(max, command) {
974 return Math.max(max, command[0].length);
979 * Return the largest option length.
985 Command.prototype.largestOptionLength = function() {
986 var options = [].slice.call(this.options);
990 return options.reduce(function(max, option) {
991 return Math.max(max, option.flags.length);
996 * Return the largest arg length.
1002 Command.prototype.largestArgLength = function() {
1003 return this._args.reduce(function(max, arg) {
1004 return Math.max(max, arg.name.length);
1009 * Return the pad width.
1015 Command.prototype.padWidth = function() {
1016 var width = this.largestOptionLength();
1017 if (this._argsDescription && this._args.length) {
1018 if (this.largestArgLength() > width) {
1019 width = this.largestArgLength();
1023 if (this.commands && this.commands.length) {
1024 if (this.largestCommandLength() > width) {
1025 width = this.largestCommandLength();
1033 * Return help for options.
1039 Command.prototype.optionHelp = function() {
1040 var width = this.padWidth();
1042 // Append the help information
1043 return this.options.map(function(option) {
1044 return pad(option.flags, width) + ' ' + option.description +
1045 ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');
1046 }).concat([pad('-h, --help', width) + ' ' + 'output usage information'])
1051 * Return command help documentation.
1057 Command.prototype.commandHelp = function() {
1058 if (!this.commands.length) return '';
1060 var commands = this.prepareCommands();
1061 var width = this.padWidth();
1065 commands.map(function(cmd) {
1066 var desc = cmd[1] ? ' ' + cmd[1] : '';
1067 return (desc ? pad(cmd[0], width) : cmd[0]) + desc;
1068 }).join('\n').replace(/^/gm, ' '),
1074 * Return program help documentation.
1080 Command.prototype.helpInformation = function() {
1082 if (this._description) {
1088 var argsDescription = this._argsDescription;
1089 if (argsDescription && this._args.length) {
1090 var width = this.padWidth();
1091 desc.push('Arguments:');
1093 this._args.forEach(function(arg) {
1094 desc.push(' ' + pad(arg.name, width) + ' ' + argsDescription[arg.name]);
1100 var cmdName = this._name;
1102 cmdName = cmdName + '|' + this._alias;
1105 'Usage: ' + cmdName + ' ' + this.usage(),
1110 var commandHelp = this.commandHelp();
1111 if (commandHelp) cmds = [commandHelp];
1115 '' + this.optionHelp().replace(/^/gm, ' '),
1127 * Output help information for this command
1132 Command.prototype.outputHelp = function(cb) {
1134 cb = function(passthru) {
1138 process.stdout.write(cb(this.helpInformation()));
1139 this.emit('--help');
1143 * Output help information and exit.
1148 Command.prototype.help = function(cb) {
1149 this.outputHelp(cb);
1154 * Camel-case the given `flag`
1156 * @param {String} flag
1161 function camelcase(flag) {
1162 return flag.split('-').reduce(function(str, word) {
1163 return str + word[0].toUpperCase() + word.slice(1);
1168 * Pad `str` to `width`.
1170 * @param {String} str
1171 * @param {Number} width
1176 function pad(str, width) {
1177 var len = Math.max(0, width - str.length);
1178 return str + Array(len + 1).join(' ');
1182 * Output help information if necessary
1184 * @param {Command} command to output help for
1185 * @param {Array} array of options to search for -h or --help
1189 function outputHelpIfNecessary(cmd, options) {
1190 options = options || [];
1191 for (var i = 0; i < options.length; i++) {
1192 if (options[i] === '--help' || options[i] === '-h') {
1200 * Takes an argument an returns its human readable equivalent for help usage.
1202 * @param {Object} arg
1207 function humanReadableArgName(arg) {
1208 var nameOutput = arg.name + (arg.variadic === true ? '...' : '');
1211 ? '<' + nameOutput + '>'
1212 : '[' + nameOutput + ']';
1215 // for versions before node v0.8 when there weren't `fs.existsSync`
1216 function exists(file) {
1218 if (fs.statSync(file).isFile()) {