You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1236 lines
28 KiB

4 years ago
  1. /**
  2. * Module dependencies.
  3. */
  4. var EventEmitter = require('events').EventEmitter;
  5. var spawn = require('child_process').spawn;
  6. var path = require('path');
  7. var dirname = path.dirname;
  8. var basename = path.basename;
  9. var fs = require('fs');
  10. /**
  11. * Inherit `Command` from `EventEmitter.prototype`.
  12. */
  13. require('util').inherits(Command, EventEmitter);
  14. /**
  15. * Expose the root command.
  16. */
  17. exports = module.exports = new Command();
  18. /**
  19. * Expose `Command`.
  20. */
  21. exports.Command = Command;
  22. /**
  23. * Expose `Option`.
  24. */
  25. exports.Option = Option;
  26. /**
  27. * Initialize a new `Option` with the given `flags` and `description`.
  28. *
  29. * @param {String} flags
  30. * @param {String} description
  31. * @api public
  32. */
  33. function Option(flags, description) {
  34. this.flags = flags;
  35. this.required = flags.indexOf('<') >= 0;
  36. this.optional = flags.indexOf('[') >= 0;
  37. this.bool = flags.indexOf('-no-') === -1;
  38. flags = flags.split(/[ ,|]+/);
  39. if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();
  40. this.long = flags.shift();
  41. this.description = description || '';
  42. }
  43. /**
  44. * Return option name.
  45. *
  46. * @return {String}
  47. * @api private
  48. */
  49. Option.prototype.name = function() {
  50. return this.long
  51. .replace('--', '')
  52. .replace('no-', '');
  53. };
  54. /**
  55. * Return option name, in a camelcase format that can be used
  56. * as a object attribute key.
  57. *
  58. * @return {String}
  59. * @api private
  60. */
  61. Option.prototype.attributeName = function() {
  62. return camelcase(this.name());
  63. };
  64. /**
  65. * Check if `arg` matches the short or long flag.
  66. *
  67. * @param {String} arg
  68. * @return {Boolean}
  69. * @api private
  70. */
  71. Option.prototype.is = function(arg) {
  72. return this.short === arg || this.long === arg;
  73. };
  74. /**
  75. * Initialize a new `Command`.
  76. *
  77. * @param {String} name
  78. * @api public
  79. */
  80. function Command(name) {
  81. this.commands = [];
  82. this.options = [];
  83. this._execs = {};
  84. this._allowUnknownOption = false;
  85. this._args = [];
  86. this._name = name || '';
  87. }
  88. /**
  89. * Add command `name`.
  90. *
  91. * The `.action()` callback is invoked when the
  92. * command `name` is specified via __ARGV__,
  93. * and the remaining arguments are applied to the
  94. * function for access.
  95. *
  96. * When the `name` is "*" an un-matched command
  97. * will be passed as the first arg, followed by
  98. * the rest of __ARGV__ remaining.
  99. *
  100. * Examples:
  101. *
  102. * program
  103. * .version('0.0.1')
  104. * .option('-C, --chdir <path>', 'change the working directory')
  105. * .option('-c, --config <path>', 'set config path. defaults to ./deploy.conf')
  106. * .option('-T, --no-tests', 'ignore test hook')
  107. *
  108. * program
  109. * .command('setup')
  110. * .description('run remote setup commands')
  111. * .action(function() {
  112. * console.log('setup');
  113. * });
  114. *
  115. * program
  116. * .command('exec <cmd>')
  117. * .description('run the given remote command')
  118. * .action(function(cmd) {
  119. * console.log('exec "%s"', cmd);
  120. * });
  121. *
  122. * program
  123. * .command('teardown <dir> [otherDirs...]')
  124. * .description('run teardown commands')
  125. * .action(function(dir, otherDirs) {
  126. * console.log('dir "%s"', dir);
  127. * if (otherDirs) {
  128. * otherDirs.forEach(function (oDir) {
  129. * console.log('dir "%s"', oDir);
  130. * });
  131. * }
  132. * });
  133. *
  134. * program
  135. * .command('*')
  136. * .description('deploy the given env')
  137. * .action(function(env) {
  138. * console.log('deploying "%s"', env);
  139. * });
  140. *
  141. * program.parse(process.argv);
  142. *
  143. * @param {String} name
  144. * @param {String} [desc] for git-style sub-commands
  145. * @return {Command} the new command
  146. * @api public
  147. */
  148. Command.prototype.command = function(name, desc, opts) {
  149. if (typeof desc === 'object' && desc !== null) {
  150. opts = desc;
  151. desc = null;
  152. }
  153. opts = opts || {};
  154. var args = name.split(/ +/);
  155. var cmd = new Command(args.shift());
  156. if (desc) {
  157. cmd.description(desc);
  158. this.executables = true;
  159. this._execs[cmd._name] = true;
  160. if (opts.isDefault) this.defaultExecutable = cmd._name;
  161. }
  162. cmd._noHelp = !!opts.noHelp;
  163. this.commands.push(cmd);
  164. cmd.parseExpectedArgs(args);
  165. cmd.parent = this;
  166. if (desc) return this;
  167. return cmd;
  168. };
  169. /**
  170. * Define argument syntax for the top-level command.
  171. *
  172. * @api public
  173. */
  174. Command.prototype.arguments = function(desc) {
  175. return this.parseExpectedArgs(desc.split(/ +/));
  176. };
  177. /**
  178. * Add an implicit `help [cmd]` subcommand
  179. * which invokes `--help` for the given command.
  180. *
  181. * @api private
  182. */
  183. Command.prototype.addImplicitHelpCommand = function() {
  184. this.command('help [cmd]', 'display help for [cmd]');
  185. };
  186. /**
  187. * Parse expected `args`.
  188. *
  189. * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`.
  190. *
  191. * @param {Array} args
  192. * @return {Command} for chaining
  193. * @api public
  194. */
  195. Command.prototype.parseExpectedArgs = function(args) {
  196. if (!args.length) return;
  197. var self = this;
  198. args.forEach(function(arg) {
  199. var argDetails = {
  200. required: false,
  201. name: '',
  202. variadic: false
  203. };
  204. switch (arg[0]) {
  205. case '<':
  206. argDetails.required = true;
  207. argDetails.name = arg.slice(1, -1);
  208. break;
  209. case '[':
  210. argDetails.name = arg.slice(1, -1);
  211. break;
  212. }
  213. if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') {
  214. argDetails.variadic = true;
  215. argDetails.name = argDetails.name.slice(0, -3);
  216. }
  217. if (argDetails.name) {
  218. self._args.push(argDetails);
  219. }
  220. });
  221. return this;
  222. };
  223. /**
  224. * Register callback `fn` for the command.
  225. *
  226. * Examples:
  227. *
  228. * program
  229. * .command('help')
  230. * .description('display verbose help')
  231. * .action(function() {
  232. * // output help here
  233. * });
  234. *
  235. * @param {Function} fn
  236. * @return {Command} for chaining
  237. * @api public
  238. */
  239. Command.prototype.action = function(fn) {
  240. var self = this;
  241. var listener = function(args, unknown) {
  242. // Parse any so-far unknown options
  243. args = args || [];
  244. unknown = unknown || [];
  245. var parsed = self.parseOptions(unknown);
  246. // Output help if necessary
  247. outputHelpIfNecessary(self, parsed.unknown);
  248. // If there are still any unknown options, then we simply
  249. // die, unless someone asked for help, in which case we give it
  250. // to them, and then we die.
  251. if (parsed.unknown.length > 0) {
  252. self.unknownOption(parsed.unknown[0]);
  253. }
  254. // Leftover arguments need to be pushed back. Fixes issue #56
  255. if (parsed.args.length) args = parsed.args.concat(args);
  256. self._args.forEach(function(arg, i) {
  257. if (arg.required && args[i] == null) {
  258. self.missingArgument(arg.name);
  259. } else if (arg.variadic) {
  260. if (i !== self._args.length - 1) {
  261. self.variadicArgNotLast(arg.name);
  262. }
  263. args[i] = args.splice(i);
  264. }
  265. });
  266. // Always append ourselves to the end of the arguments,
  267. // to make sure we match the number of arguments the user
  268. // expects
  269. if (self._args.length) {
  270. args[self._args.length] = self;
  271. } else {
  272. args.push(self);
  273. }
  274. fn.apply(self, args);
  275. };
  276. var parent = this.parent || this;
  277. var name = parent === this ? '*' : this._name;
  278. parent.on('command:' + name, listener);
  279. if (this._alias) parent.on('command:' + this._alias, listener);
  280. return this;
  281. };
  282. /**
  283. * Define option with `flags`, `description` and optional
  284. * coercion `fn`.
  285. *
  286. * The `flags` string should contain both the short and long flags,
  287. * separated by comma, a pipe or space. The following are all valid
  288. * all will output this way when `--help` is used.
  289. *
  290. * "-p, --pepper"
  291. * "-p|--pepper"
  292. * "-p --pepper"
  293. *
  294. * Examples:
  295. *
  296. * // simple boolean defaulting to false
  297. * program.option('-p, --pepper', 'add pepper');
  298. *
  299. * --pepper
  300. * program.pepper
  301. * // => Boolean
  302. *
  303. * // simple boolean defaulting to true
  304. * program.option('-C, --no-cheese', 'remove cheese');
  305. *
  306. * program.cheese
  307. * // => true
  308. *
  309. * --no-cheese
  310. * program.cheese
  311. * // => false
  312. *
  313. * // required argument
  314. * program.option('-C, --chdir <path>', 'change the working directory');
  315. *
  316. * --chdir /tmp
  317. * program.chdir
  318. * // => "/tmp"
  319. *
  320. * // optional argument
  321. * program.option('-c, --cheese [type]', 'add cheese [marble]');
  322. *
  323. * @param {String} flags
  324. * @param {String} description
  325. * @param {Function|*} [fn] or default
  326. * @param {*} [defaultValue]
  327. * @return {Command} for chaining
  328. * @api public
  329. */
  330. Command.prototype.option = function(flags, description, fn, defaultValue) {
  331. var self = this,
  332. option = new Option(flags, description),
  333. oname = option.name(),
  334. name = option.attributeName();
  335. // default as 3rd arg
  336. if (typeof fn !== 'function') {
  337. if (fn instanceof RegExp) {
  338. var regex = fn;
  339. fn = function(val, def) {
  340. var m = regex.exec(val);
  341. return m ? m[0] : def;
  342. };
  343. } else {
  344. defaultValue = fn;
  345. fn = null;
  346. }
  347. }
  348. // preassign default value only for --no-*, [optional], or <required>
  349. if (!option.bool || option.optional || option.required) {
  350. // when --no-* we make sure default is true
  351. if (!option.bool) defaultValue = true;
  352. // preassign only if we have a default
  353. if (defaultValue !== undefined) {
  354. self[name] = defaultValue;
  355. option.defaultValue = defaultValue;
  356. }
  357. }
  358. // register the option
  359. this.options.push(option);
  360. // when it's passed assign the value
  361. // and conditionally invoke the callback
  362. this.on('option:' + oname, function(val) {
  363. // coercion
  364. if (val !== null && fn) {
  365. val = fn(val, self[name] === undefined ? defaultValue : self[name]);
  366. }
  367. // unassigned or bool
  368. if (typeof self[name] === 'boolean' || typeof self[name] === 'undefined') {
  369. // if no value, bool true, and we have a default, then use it!
  370. if (val == null) {
  371. self[name] = option.bool
  372. ? defaultValue || true
  373. : false;
  374. } else {
  375. self[name] = val;
  376. }
  377. } else if (val !== null) {
  378. // reassign
  379. self[name] = val;
  380. }
  381. });
  382. return this;
  383. };
  384. /**
  385. * Allow unknown options on the command line.
  386. *
  387. * @param {Boolean} arg if `true` or omitted, no error will be thrown
  388. * for unknown options.
  389. * @api public
  390. */
  391. Command.prototype.allowUnknownOption = function(arg) {
  392. this._allowUnknownOption = arguments.length === 0 || arg;
  393. return this;
  394. };
  395. /**
  396. * Parse `argv`, settings options and invoking commands when defined.
  397. *
  398. * @param {Array} argv
  399. * @return {Command} for chaining
  400. * @api public
  401. */
  402. Command.prototype.parse = function(argv) {
  403. // implicit help
  404. if (this.executables) this.addImplicitHelpCommand();
  405. // store raw args
  406. this.rawArgs = argv;
  407. // guess name
  408. this._name = this._name || basename(argv[1], '.js');
  409. // github-style sub-commands with no sub-command
  410. if (this.executables && argv.length < 3 && !this.defaultExecutable) {
  411. // this user needs help
  412. argv.push('--help');
  413. }
  414. // process argv
  415. var parsed = this.parseOptions(this.normalize(argv.slice(2)));
  416. var args = this.args = parsed.args;
  417. var result = this.parseArgs(this.args, parsed.unknown);
  418. // executable sub-commands
  419. var name = result.args[0];
  420. var aliasCommand = null;
  421. // check alias of sub commands
  422. if (name) {
  423. aliasCommand = this.commands.filter(function(command) {
  424. return command.alias() === name;
  425. })[0];
  426. }
  427. if (this._execs[name] && typeof this._execs[name] !== 'function') {
  428. return this.executeSubCommand(argv, args, parsed.unknown);
  429. } else if (aliasCommand) {
  430. // is alias of a subCommand
  431. args[0] = aliasCommand._name;
  432. return this.executeSubCommand(argv, args, parsed.unknown);
  433. } else if (this.defaultExecutable) {
  434. // use the default subcommand
  435. args.unshift(this.defaultExecutable);
  436. return this.executeSubCommand(argv, args, parsed.unknown);
  437. }
  438. return result;
  439. };
  440. /**
  441. * Execute a sub-command executable.
  442. *
  443. * @param {Array} argv
  444. * @param {Array} args
  445. * @param {Array} unknown
  446. * @api private
  447. */
  448. Command.prototype.executeSubCommand = function(argv, args, unknown) {
  449. args = args.concat(unknown);
  450. if (!args.length) this.help();
  451. if (args[0] === 'help' && args.length === 1) this.help();
  452. // <cmd> --help
  453. if (args[0] === 'help') {
  454. args[0] = args[1];
  455. args[1] = '--help';
  456. }
  457. // executable
  458. var f = argv[1];
  459. // name of the subcommand, link `pm-install`
  460. var bin = basename(f, '.js') + '-' + args[0];
  461. // In case of globally installed, get the base dir where executable
  462. // subcommand file should be located at
  463. var baseDir,
  464. link = fs.lstatSync(f).isSymbolicLink() ? fs.readlinkSync(f) : f;
  465. // when symbolink is relative path
  466. if (link !== f && link.charAt(0) !== '/') {
  467. link = path.join(dirname(f), link);
  468. }
  469. baseDir = dirname(link);
  470. // prefer local `./<bin>` to bin in the $PATH
  471. var localBin = path.join(baseDir, bin);
  472. // whether bin file is a js script with explicit `.js` extension
  473. var isExplicitJS = false;
  474. if (exists(localBin + '.js')) {
  475. bin = localBin + '.js';
  476. isExplicitJS = true;
  477. } else if (exists(localBin)) {
  478. bin = localBin;
  479. }
  480. args = args.slice(1);
  481. var proc;
  482. if (process.platform !== 'win32') {
  483. if (isExplicitJS) {
  484. args.unshift(bin);
  485. // add executable arguments to spawn
  486. args = (process.execArgv || []).concat(args);
  487. proc = spawn(process.argv[0], args, { stdio: 'inherit', customFds: [0, 1, 2] });
  488. } else {
  489. proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] });
  490. }
  491. } else {
  492. args.unshift(bin);
  493. proc = spawn(process.execPath, args, { stdio: 'inherit' });
  494. }
  495. var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
  496. signals.forEach(function(signal) {
  497. process.on(signal, function() {
  498. if (proc.killed === false && proc.exitCode === null) {
  499. proc.kill(signal);
  500. }
  501. });
  502. });
  503. proc.on('close', process.exit.bind(process));
  504. proc.on('error', function(err) {
  505. if (err.code === 'ENOENT') {
  506. console.error('\n %s(1) does not exist, try --help\n', bin);
  507. } else if (err.code === 'EACCES') {
  508. console.error('\n %s(1) not executable. try chmod or run with root\n', bin);
  509. }
  510. process.exit(1);
  511. });
  512. // Store the reference to the child process
  513. this.runningCommand = proc;
  514. };
  515. /**
  516. * Normalize `args`, splitting joined short flags. For example
  517. * the arg "-abc" is equivalent to "-a -b -c".
  518. * This also normalizes equal sign and splits "--abc=def" into "--abc def".
  519. *
  520. * @param {Array} args
  521. * @return {Array}
  522. * @api private
  523. */
  524. Command.prototype.normalize = function(args) {
  525. var ret = [],
  526. arg,
  527. lastOpt,
  528. index;
  529. for (var i = 0, len = args.length; i < len; ++i) {
  530. arg = args[i];
  531. if (i > 0) {
  532. lastOpt = this.optionFor(args[i - 1]);
  533. }
  534. if (arg === '--') {
  535. // Honor option terminator
  536. ret = ret.concat(args.slice(i));
  537. break;
  538. } else if (lastOpt && lastOpt.required) {
  539. ret.push(arg);
  540. } else if (arg.length > 1 && arg[0] === '-' && arg[1] !== '-') {
  541. arg.slice(1).split('').forEach(function(c) {
  542. ret.push('-' + c);
  543. });
  544. } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {
  545. ret.push(arg.slice(0, index), arg.slice(index + 1));
  546. } else {
  547. ret.push(arg);
  548. }
  549. }
  550. return ret;
  551. };
  552. /**
  553. * Parse command `args`.
  554. *
  555. * When listener(s) are available those
  556. * callbacks are invoked, otherwise the "*"
  557. * event is emitted and those actions are invoked.
  558. *
  559. * @param {Array} args
  560. * @return {Command} for chaining
  561. * @api private
  562. */
  563. Command.prototype.parseArgs = function(args, unknown) {
  564. var name;
  565. if (args.length) {
  566. name = args[0];
  567. if (this.listeners('command:' + name).length) {
  568. this.emit('command:' + args.shift(), args, unknown);
  569. } else {
  570. this.emit('command:*', args);
  571. }
  572. } else {
  573. outputHelpIfNecessary(this, unknown);
  574. // If there were no args and we have unknown options,
  575. // then they are extraneous and we need to error.
  576. if (unknown.length > 0) {
  577. this.unknownOption(unknown[0]);
  578. }
  579. if (this.commands.length === 0 &&
  580. this._args.filter(function(a) { return a.required }).length === 0) {
  581. this.emit('command:*');
  582. }
  583. }
  584. return this;
  585. };
  586. /**
  587. * Return an option matching `arg` if any.
  588. *
  589. * @param {String} arg
  590. * @return {Option}
  591. * @api private
  592. */
  593. Command.prototype.optionFor = function(arg) {
  594. for (var i = 0, len = this.options.length; i < len; ++i) {
  595. if (this.options[i].is(arg)) {
  596. return this.options[i];
  597. }
  598. }
  599. };
  600. /**
  601. * Parse options from `argv` returning `argv`
  602. * void of these options.
  603. *
  604. * @param {Array} argv
  605. * @return {Array}
  606. * @api public
  607. */
  608. Command.prototype.parseOptions = function(argv) {
  609. var args = [],
  610. len = argv.length,
  611. literal,
  612. option,
  613. arg;
  614. var unknownOptions = [];
  615. // parse options
  616. for (var i = 0; i < len; ++i) {
  617. arg = argv[i];
  618. // literal args after --
  619. if (literal) {
  620. args.push(arg);
  621. continue;
  622. }
  623. if (arg === '--') {
  624. literal = true;
  625. continue;
  626. }
  627. // find matching Option
  628. option = this.optionFor(arg);
  629. // option is defined
  630. if (option) {
  631. // requires arg
  632. if (option.required) {
  633. arg = argv[++i];
  634. if (arg == null) return this.optionMissingArgument(option);
  635. this.emit('option:' + option.name(), arg);
  636. // optional arg
  637. } else if (option.optional) {
  638. arg = argv[i + 1];
  639. if (arg == null || (arg[0] === '-' && arg !== '-')) {
  640. arg = null;
  641. } else {
  642. ++i;
  643. }
  644. this.emit('option:' + option.name(), arg);
  645. // bool
  646. } else {
  647. this.emit('option:' + option.name());
  648. }
  649. continue;
  650. }
  651. // looks like an option
  652. if (arg.length > 1 && arg[0] === '-') {
  653. unknownOptions.push(arg);
  654. // If the next argument looks like it might be
  655. // an argument for this option, we pass it on.
  656. // If it isn't, then it'll simply be ignored
  657. if ((i + 1) < argv.length && argv[i + 1][0] !== '-') {
  658. unknownOptions.push(argv[++i]);
  659. }
  660. continue;
  661. }
  662. // arg
  663. args.push(arg);
  664. }
  665. return { args: args, unknown: unknownOptions };
  666. };
  667. /**
  668. * Return an object containing options as key-value pairs
  669. *
  670. * @return {Object}
  671. * @api public
  672. */
  673. Command.prototype.opts = function() {
  674. var result = {},
  675. len = this.options.length;
  676. for (var i = 0; i < len; i++) {
  677. var key = this.options[i].attributeName();
  678. result[key] = key === this._versionOptionName ? this._version : this[key];
  679. }
  680. return result;
  681. };
  682. /**
  683. * Argument `name` is missing.
  684. *
  685. * @param {String} name
  686. * @api private
  687. */
  688. Command.prototype.missingArgument = function(name) {
  689. console.error();
  690. console.error(" error: missing required argument `%s'", name);
  691. console.error();
  692. process.exit(1);
  693. };
  694. /**
  695. * `Option` is missing an argument, but received `flag` or nothing.
  696. *
  697. * @param {String} option
  698. * @param {String} flag
  699. * @api private
  700. */
  701. Command.prototype.optionMissingArgument = function(option, flag) {
  702. console.error();
  703. if (flag) {
  704. console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag);
  705. } else {
  706. console.error(" error: option `%s' argument missing", option.flags);
  707. }
  708. console.error();
  709. process.exit(1);
  710. };
  711. /**
  712. * Unknown option `flag`.
  713. *
  714. * @param {String} flag
  715. * @api private
  716. */
  717. Command.prototype.unknownOption = function(flag) {
  718. if (this._allowUnknownOption) return;
  719. console.error();
  720. console.error(" error: unknown option `%s'", flag);
  721. console.error();
  722. process.exit(1);
  723. };
  724. /**
  725. * Variadic argument with `name` is not the last argument as required.
  726. *
  727. * @param {String} name
  728. * @api private
  729. */
  730. Command.prototype.variadicArgNotLast = function(name) {
  731. console.error();
  732. console.error(" error: variadic arguments must be last `%s'", name);
  733. console.error();
  734. process.exit(1);
  735. };
  736. /**
  737. * Set the program version to `str`.
  738. *
  739. * This method auto-registers the "-V, --version" flag
  740. * which will print the version number when passed.
  741. *
  742. * @param {String} str
  743. * @param {String} [flags]
  744. * @return {Command} for chaining
  745. * @api public
  746. */
  747. Command.prototype.version = function(str, flags) {
  748. if (arguments.length === 0) return this._version;
  749. this._version = str;
  750. flags = flags || '-V, --version';
  751. var versionOption = new Option(flags, 'output the version number');
  752. this._versionOptionName = versionOption.long.substr(2) || 'version';
  753. this.options.push(versionOption);
  754. this.on('option:' + this._versionOptionName, function() {
  755. process.stdout.write(str + '\n');
  756. process.exit(0);
  757. });
  758. return this;
  759. };
  760. /**
  761. * Set the description to `str`.
  762. *
  763. * @param {String} str
  764. * @param {Object} argsDescription
  765. * @return {String|Command}
  766. * @api public
  767. */
  768. Command.prototype.description = function(str, argsDescription) {
  769. if (arguments.length === 0) return this._description;
  770. this._description = str;
  771. this._argsDescription = argsDescription;
  772. return this;
  773. };
  774. /**
  775. * Set an alias for the command
  776. *
  777. * @param {String} alias
  778. * @return {String|Command}
  779. * @api public
  780. */
  781. Command.prototype.alias = function(alias) {
  782. var command = this;
  783. if (this.commands.length !== 0) {
  784. command = this.commands[this.commands.length - 1];
  785. }
  786. if (arguments.length === 0) return command._alias;
  787. if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
  788. command._alias = alias;
  789. return this;
  790. };
  791. /**
  792. * Set / get the command usage `str`.
  793. *
  794. * @param {String} str
  795. * @return {String|Command}
  796. * @api public
  797. */
  798. Command.prototype.usage = function(str) {
  799. var args = this._args.map(function(arg) {
  800. return humanReadableArgName(arg);
  801. });
  802. var usage = '[options]' +
  803. (this.commands.length ? ' [command]' : '') +
  804. (this._args.length ? ' ' + args.join(' ') : '');
  805. if (arguments.length === 0) return this._usage || usage;
  806. this._usage = str;
  807. return this;
  808. };
  809. /**
  810. * Get or set the name of the command
  811. *
  812. * @param {String} str
  813. * @return {String|Command}
  814. * @api public
  815. */
  816. Command.prototype.name = function(str) {
  817. if (arguments.length === 0) return this._name;
  818. this._name = str;
  819. return this;
  820. };
  821. /**
  822. * Return prepared commands.
  823. *
  824. * @return {Array}
  825. * @api private
  826. */
  827. Command.prototype.prepareCommands = function() {
  828. return this.commands.filter(function(cmd) {
  829. return !cmd._noHelp;
  830. }).map(function(cmd) {
  831. var args = cmd._args.map(function(arg) {
  832. return humanReadableArgName(arg);
  833. }).join(' ');
  834. return [
  835. cmd._name +
  836. (cmd._alias ? '|' + cmd._alias : '') +
  837. (cmd.options.length ? ' [options]' : '') +
  838. (args ? ' ' + args : ''),
  839. cmd._description
  840. ];
  841. });
  842. };
  843. /**
  844. * Return the largest command length.
  845. *
  846. * @return {Number}
  847. * @api private
  848. */
  849. Command.prototype.largestCommandLength = function() {
  850. var commands = this.prepareCommands();
  851. return commands.reduce(function(max, command) {
  852. return Math.max(max, command[0].length);
  853. }, 0);
  854. };
  855. /**
  856. * Return the largest option length.
  857. *
  858. * @return {Number}
  859. * @api private
  860. */
  861. Command.prototype.largestOptionLength = function() {
  862. var options = [].slice.call(this.options);
  863. options.push({
  864. flags: '-h, --help'
  865. });
  866. return options.reduce(function(max, option) {
  867. return Math.max(max, option.flags.length);
  868. }, 0);
  869. };
  870. /**
  871. * Return the largest arg length.
  872. *
  873. * @return {Number}
  874. * @api private
  875. */
  876. Command.prototype.largestArgLength = function() {
  877. return this._args.reduce(function(max, arg) {
  878. return Math.max(max, arg.name.length);
  879. }, 0);
  880. };
  881. /**
  882. * Return the pad width.
  883. *
  884. * @return {Number}
  885. * @api private
  886. */
  887. Command.prototype.padWidth = function() {
  888. var width = this.largestOptionLength();
  889. if (this._argsDescription && this._args.length) {
  890. if (this.largestArgLength() > width) {
  891. width = this.largestArgLength();
  892. }
  893. }
  894. if (this.commands && this.commands.length) {
  895. if (this.largestCommandLength() > width) {
  896. width = this.largestCommandLength();
  897. }
  898. }
  899. return width;
  900. };
  901. /**
  902. * Return help for options.
  903. *
  904. * @return {String}
  905. * @api private
  906. */
  907. Command.prototype.optionHelp = function() {
  908. var width = this.padWidth();
  909. // Append the help information
  910. return this.options.map(function(option) {
  911. return pad(option.flags, width) + ' ' + option.description +
  912. ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + option.defaultValue + ')' : '');
  913. }).concat([pad('-h, --help', width) + ' ' + 'output usage information'])
  914. .join('\n');
  915. };
  916. /**
  917. * Return command help documentation.
  918. *
  919. * @return {String}
  920. * @api private
  921. */
  922. Command.prototype.commandHelp = function() {
  923. if (!this.commands.length) return '';
  924. var commands = this.prepareCommands();
  925. var width = this.padWidth();
  926. return [
  927. ' Commands:',
  928. '',
  929. commands.map(function(cmd) {
  930. var desc = cmd[1] ? ' ' + cmd[1] : '';
  931. return (desc ? pad(cmd[0], width) : cmd[0]) + desc;
  932. }).join('\n').replace(/^/gm, ' '),
  933. ''
  934. ].join('\n');
  935. };
  936. /**
  937. * Return program help documentation.
  938. *
  939. * @return {String}
  940. * @api private
  941. */
  942. Command.prototype.helpInformation = function() {
  943. var desc = [];
  944. if (this._description) {
  945. desc = [
  946. ' ' + this._description,
  947. ''
  948. ];
  949. var argsDescription = this._argsDescription;
  950. if (argsDescription && this._args.length) {
  951. var width = this.padWidth();
  952. desc.push(' Arguments:');
  953. desc.push('');
  954. this._args.forEach(function(arg) {
  955. desc.push(' ' + pad(arg.name, width) + ' ' + argsDescription[arg.name]);
  956. });
  957. desc.push('');
  958. }
  959. }
  960. var cmdName = this._name;
  961. if (this._alias) {
  962. cmdName = cmdName + '|' + this._alias;
  963. }
  964. var usage = [
  965. '',
  966. ' Usage: ' + cmdName + ' ' + this.usage(),
  967. ''
  968. ];
  969. var cmds = [];
  970. var commandHelp = this.commandHelp();
  971. if (commandHelp) cmds = [commandHelp];
  972. var options = [
  973. ' Options:',
  974. '',
  975. '' + this.optionHelp().replace(/^/gm, ' '),
  976. ''
  977. ];
  978. return usage
  979. .concat(desc)
  980. .concat(options)
  981. .concat(cmds)
  982. .concat([''])
  983. .join('\n');
  984. };
  985. /**
  986. * Output help information for this command
  987. *
  988. * @api public
  989. */
  990. Command.prototype.outputHelp = function(cb) {
  991. if (!cb) {
  992. cb = function(passthru) {
  993. return passthru;
  994. };
  995. }
  996. process.stdout.write(cb(this.helpInformation()));
  997. this.emit('--help');
  998. };
  999. /**
  1000. * Output help information and exit.
  1001. *
  1002. * @api public
  1003. */
  1004. Command.prototype.help = function(cb) {
  1005. this.outputHelp(cb);
  1006. process.exit();
  1007. };
  1008. /**
  1009. * Camel-case the given `flag`
  1010. *
  1011. * @param {String} flag
  1012. * @return {String}
  1013. * @api private
  1014. */
  1015. function camelcase(flag) {
  1016. return flag.split('-').reduce(function(str, word) {
  1017. return str + word[0].toUpperCase() + word.slice(1);
  1018. });
  1019. }
  1020. /**
  1021. * Pad `str` to `width`.
  1022. *
  1023. * @param {String} str
  1024. * @param {Number} width
  1025. * @return {String}
  1026. * @api private
  1027. */
  1028. function pad(str, width) {
  1029. var len = Math.max(0, width - str.length);
  1030. return str + Array(len + 1).join(' ');
  1031. }
  1032. /**
  1033. * Output help information if necessary
  1034. *
  1035. * @param {Command} command to output help for
  1036. * @param {Array} array of options to search for -h or --help
  1037. * @api private
  1038. */
  1039. function outputHelpIfNecessary(cmd, options) {
  1040. options = options || [];
  1041. for (var i = 0; i < options.length; i++) {
  1042. if (options[i] === '--help' || options[i] === '-h') {
  1043. cmd.outputHelp();
  1044. process.exit(0);
  1045. }
  1046. }
  1047. }
  1048. /**
  1049. * Takes an argument an returns its human readable equivalent for help usage.
  1050. *
  1051. * @param {Object} arg
  1052. * @return {String}
  1053. * @api private
  1054. */
  1055. function humanReadableArgName(arg) {
  1056. var nameOutput = arg.name + (arg.variadic === true ? '...' : '');
  1057. return arg.required
  1058. ? '<' + nameOutput + '>'
  1059. : '[' + nameOutput + ']';
  1060. }
  1061. // for versions before node v0.8 when there weren't `fs.existsSync`
  1062. function exists(file) {
  1063. try {
  1064. if (fs.statSync(file).isFile()) {
  1065. return true;
  1066. }
  1067. } catch (e) {
  1068. return false;
  1069. }
  1070. }