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.

index.js 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224
  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] === true) {
  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, path.extname(f)) + '-' + 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. var resolvedLink = fs.realpathSync(f);
  465. baseDir = dirname(resolvedLink);
  466. // prefer local `./<bin>` to bin in the $PATH
  467. var localBin = path.join(baseDir, bin);
  468. // whether bin file is a js script with explicit `.js` or `.ts` extension
  469. var isExplicitJS = false;
  470. if (exists(localBin + '.js')) {
  471. bin = localBin + '.js';
  472. isExplicitJS = true;
  473. } else if (exists(localBin + '.ts')) {
  474. bin = localBin + '.ts';
  475. isExplicitJS = true;
  476. } else if (exists(localBin)) {
  477. bin = localBin;
  478. }
  479. args = args.slice(1);
  480. var proc;
  481. if (process.platform !== 'win32') {
  482. if (isExplicitJS) {
  483. args.unshift(bin);
  484. // add executable arguments to spawn
  485. args = (process.execArgv || []).concat(args);
  486. proc = spawn(process.argv[0], args, { stdio: 'inherit', customFds: [0, 1, 2] });
  487. } else {
  488. proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] });
  489. }
  490. } else {
  491. args.unshift(bin);
  492. proc = spawn(process.execPath, args, { stdio: 'inherit' });
  493. }
  494. var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
  495. signals.forEach(function(signal) {
  496. process.on(signal, function() {
  497. if (proc.killed === false && proc.exitCode === null) {
  498. proc.kill(signal);
  499. }
  500. });
  501. });
  502. proc.on('close', process.exit.bind(process));
  503. proc.on('error', function(err) {
  504. if (err.code === 'ENOENT') {
  505. console.error('error: %s(1) does not exist, try --help', bin);
  506. } else if (err.code === 'EACCES') {
  507. console.error('error: %s(1) not executable. try chmod or run with root', bin);
  508. }
  509. process.exit(1);
  510. });
  511. // Store the reference to the child process
  512. this.runningCommand = proc;
  513. };
  514. /**
  515. * Normalize `args`, splitting joined short flags. For example
  516. * the arg "-abc" is equivalent to "-a -b -c".
  517. * This also normalizes equal sign and splits "--abc=def" into "--abc def".
  518. *
  519. * @param {Array} args
  520. * @return {Array}
  521. * @api private
  522. */
  523. Command.prototype.normalize = function(args) {
  524. var ret = [],
  525. arg,
  526. lastOpt,
  527. index;
  528. for (var i = 0, len = args.length; i < len; ++i) {
  529. arg = args[i];
  530. if (i > 0) {
  531. lastOpt = this.optionFor(args[i - 1]);
  532. }
  533. if (arg === '--') {
  534. // Honor option terminator
  535. ret = ret.concat(args.slice(i));
  536. break;
  537. } else if (lastOpt && lastOpt.required) {
  538. ret.push(arg);
  539. } else if (arg.length > 1 && arg[0] === '-' && arg[1] !== '-') {
  540. arg.slice(1).split('').forEach(function(c) {
  541. ret.push('-' + c);
  542. });
  543. } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {
  544. ret.push(arg.slice(0, index), arg.slice(index + 1));
  545. } else {
  546. ret.push(arg);
  547. }
  548. }
  549. return ret;
  550. };
  551. /**
  552. * Parse command `args`.
  553. *
  554. * When listener(s) are available those
  555. * callbacks are invoked, otherwise the "*"
  556. * event is emitted and those actions are invoked.
  557. *
  558. * @param {Array} args
  559. * @return {Command} for chaining
  560. * @api private
  561. */
  562. Command.prototype.parseArgs = function(args, unknown) {
  563. var name;
  564. if (args.length) {
  565. name = args[0];
  566. if (this.listeners('command:' + name).length) {
  567. this.emit('command:' + args.shift(), args, unknown);
  568. } else {
  569. this.emit('command:*', args);
  570. }
  571. } else {
  572. outputHelpIfNecessary(this, unknown);
  573. // If there were no args and we have unknown options,
  574. // then they are extraneous and we need to error.
  575. if (unknown.length > 0) {
  576. this.unknownOption(unknown[0]);
  577. }
  578. if (this.commands.length === 0 &&
  579. this._args.filter(function(a) { return a.required; }).length === 0) {
  580. this.emit('command:*');
  581. }
  582. }
  583. return this;
  584. };
  585. /**
  586. * Return an option matching `arg` if any.
  587. *
  588. * @param {String} arg
  589. * @return {Option}
  590. * @api private
  591. */
  592. Command.prototype.optionFor = function(arg) {
  593. for (var i = 0, len = this.options.length; i < len; ++i) {
  594. if (this.options[i].is(arg)) {
  595. return this.options[i];
  596. }
  597. }
  598. };
  599. /**
  600. * Parse options from `argv` returning `argv`
  601. * void of these options.
  602. *
  603. * @param {Array} argv
  604. * @return {Array}
  605. * @api public
  606. */
  607. Command.prototype.parseOptions = function(argv) {
  608. var args = [],
  609. len = argv.length,
  610. literal,
  611. option,
  612. arg;
  613. var unknownOptions = [];
  614. // parse options
  615. for (var i = 0; i < len; ++i) {
  616. arg = argv[i];
  617. // literal args after --
  618. if (literal) {
  619. args.push(arg);
  620. continue;
  621. }
  622. if (arg === '--') {
  623. literal = true;
  624. continue;
  625. }
  626. // find matching Option
  627. option = this.optionFor(arg);
  628. // option is defined
  629. if (option) {
  630. // requires arg
  631. if (option.required) {
  632. arg = argv[++i];
  633. if (arg == null) return this.optionMissingArgument(option);
  634. this.emit('option:' + option.name(), arg);
  635. // optional arg
  636. } else if (option.optional) {
  637. arg = argv[i + 1];
  638. if (arg == null || (arg[0] === '-' && arg !== '-')) {
  639. arg = null;
  640. } else {
  641. ++i;
  642. }
  643. this.emit('option:' + option.name(), arg);
  644. // bool
  645. } else {
  646. this.emit('option:' + option.name());
  647. }
  648. continue;
  649. }
  650. // looks like an option
  651. if (arg.length > 1 && arg[0] === '-') {
  652. unknownOptions.push(arg);
  653. // If the next argument looks like it might be
  654. // an argument for this option, we pass it on.
  655. // If it isn't, then it'll simply be ignored
  656. if ((i + 1) < argv.length && argv[i + 1][0] !== '-') {
  657. unknownOptions.push(argv[++i]);
  658. }
  659. continue;
  660. }
  661. // arg
  662. args.push(arg);
  663. }
  664. return { args: args, unknown: unknownOptions };
  665. };
  666. /**
  667. * Return an object containing options as key-value pairs
  668. *
  669. * @return {Object}
  670. * @api public
  671. */
  672. Command.prototype.opts = function() {
  673. var result = {},
  674. len = this.options.length;
  675. for (var i = 0; i < len; i++) {
  676. var key = this.options[i].attributeName();
  677. result[key] = key === this._versionOptionName ? this._version : this[key];
  678. }
  679. return result;
  680. };
  681. /**
  682. * Argument `name` is missing.
  683. *
  684. * @param {String} name
  685. * @api private
  686. */
  687. Command.prototype.missingArgument = function(name) {
  688. console.error("error: missing required argument `%s'", name);
  689. process.exit(1);
  690. };
  691. /**
  692. * `Option` is missing an argument, but received `flag` or nothing.
  693. *
  694. * @param {String} option
  695. * @param {String} flag
  696. * @api private
  697. */
  698. Command.prototype.optionMissingArgument = function(option, flag) {
  699. if (flag) {
  700. console.error("error: option `%s' argument missing, got `%s'", option.flags, flag);
  701. } else {
  702. console.error("error: option `%s' argument missing", option.flags);
  703. }
  704. process.exit(1);
  705. };
  706. /**
  707. * Unknown option `flag`.
  708. *
  709. * @param {String} flag
  710. * @api private
  711. */
  712. Command.prototype.unknownOption = function(flag) {
  713. if (this._allowUnknownOption) return;
  714. console.error("error: unknown option `%s'", flag);
  715. process.exit(1);
  716. };
  717. /**
  718. * Variadic argument with `name` is not the last argument as required.
  719. *
  720. * @param {String} name
  721. * @api private
  722. */
  723. Command.prototype.variadicArgNotLast = function(name) {
  724. console.error("error: variadic arguments must be last `%s'", name);
  725. process.exit(1);
  726. };
  727. /**
  728. * Set the program version to `str`.
  729. *
  730. * This method auto-registers the "-V, --version" flag
  731. * which will print the version number when passed.
  732. *
  733. * @param {String} str
  734. * @param {String} [flags]
  735. * @return {Command} for chaining
  736. * @api public
  737. */
  738. Command.prototype.version = function(str, flags) {
  739. if (arguments.length === 0) return this._version;
  740. this._version = str;
  741. flags = flags || '-V, --version';
  742. var versionOption = new Option(flags, 'output the version number');
  743. this._versionOptionName = versionOption.long.substr(2) || 'version';
  744. this.options.push(versionOption);
  745. this.on('option:' + this._versionOptionName, function() {
  746. process.stdout.write(str + '\n');
  747. process.exit(0);
  748. });
  749. return this;
  750. };
  751. /**
  752. * Set the description to `str`.
  753. *
  754. * @param {String} str
  755. * @param {Object} argsDescription
  756. * @return {String|Command}
  757. * @api public
  758. */
  759. Command.prototype.description = function(str, argsDescription) {
  760. if (arguments.length === 0) return this._description;
  761. this._description = str;
  762. this._argsDescription = argsDescription;
  763. return this;
  764. };
  765. /**
  766. * Set an alias for the command
  767. *
  768. * @param {String} alias
  769. * @return {String|Command}
  770. * @api public
  771. */
  772. Command.prototype.alias = function(alias) {
  773. var command = this;
  774. if (this.commands.length !== 0) {
  775. command = this.commands[this.commands.length - 1];
  776. }
  777. if (arguments.length === 0) return command._alias;
  778. if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
  779. command._alias = alias;
  780. return this;
  781. };
  782. /**
  783. * Set / get the command usage `str`.
  784. *
  785. * @param {String} str
  786. * @return {String|Command}
  787. * @api public
  788. */
  789. Command.prototype.usage = function(str) {
  790. var args = this._args.map(function(arg) {
  791. return humanReadableArgName(arg);
  792. });
  793. var usage = '[options]' +
  794. (this.commands.length ? ' [command]' : '') +
  795. (this._args.length ? ' ' + args.join(' ') : '');
  796. if (arguments.length === 0) return this._usage || usage;
  797. this._usage = str;
  798. return this;
  799. };
  800. /**
  801. * Get or set the name of the command
  802. *
  803. * @param {String} str
  804. * @return {String|Command}
  805. * @api public
  806. */
  807. Command.prototype.name = function(str) {
  808. if (arguments.length === 0) return this._name;
  809. this._name = str;
  810. return this;
  811. };
  812. /**
  813. * Return prepared commands.
  814. *
  815. * @return {Array}
  816. * @api private
  817. */
  818. Command.prototype.prepareCommands = function() {
  819. return this.commands.filter(function(cmd) {
  820. return !cmd._noHelp;
  821. }).map(function(cmd) {
  822. var args = cmd._args.map(function(arg) {
  823. return humanReadableArgName(arg);
  824. }).join(' ');
  825. return [
  826. cmd._name +
  827. (cmd._alias ? '|' + cmd._alias : '') +
  828. (cmd.options.length ? ' [options]' : '') +
  829. (args ? ' ' + args : ''),
  830. cmd._description
  831. ];
  832. });
  833. };
  834. /**
  835. * Return the largest command length.
  836. *
  837. * @return {Number}
  838. * @api private
  839. */
  840. Command.prototype.largestCommandLength = function() {
  841. var commands = this.prepareCommands();
  842. return commands.reduce(function(max, command) {
  843. return Math.max(max, command[0].length);
  844. }, 0);
  845. };
  846. /**
  847. * Return the largest option length.
  848. *
  849. * @return {Number}
  850. * @api private
  851. */
  852. Command.prototype.largestOptionLength = function() {
  853. var options = [].slice.call(this.options);
  854. options.push({
  855. flags: '-h, --help'
  856. });
  857. return options.reduce(function(max, option) {
  858. return Math.max(max, option.flags.length);
  859. }, 0);
  860. };
  861. /**
  862. * Return the largest arg length.
  863. *
  864. * @return {Number}
  865. * @api private
  866. */
  867. Command.prototype.largestArgLength = function() {
  868. return this._args.reduce(function(max, arg) {
  869. return Math.max(max, arg.name.length);
  870. }, 0);
  871. };
  872. /**
  873. * Return the pad width.
  874. *
  875. * @return {Number}
  876. * @api private
  877. */
  878. Command.prototype.padWidth = function() {
  879. var width = this.largestOptionLength();
  880. if (this._argsDescription && this._args.length) {
  881. if (this.largestArgLength() > width) {
  882. width = this.largestArgLength();
  883. }
  884. }
  885. if (this.commands && this.commands.length) {
  886. if (this.largestCommandLength() > width) {
  887. width = this.largestCommandLength();
  888. }
  889. }
  890. return width;
  891. };
  892. /**
  893. * Return help for options.
  894. *
  895. * @return {String}
  896. * @api private
  897. */
  898. Command.prototype.optionHelp = function() {
  899. var width = this.padWidth();
  900. // Append the help information
  901. return this.options.map(function(option) {
  902. return pad(option.flags, width) + ' ' + option.description +
  903. ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : '');
  904. }).concat([pad('-h, --help', width) + ' ' + 'output usage information'])
  905. .join('\n');
  906. };
  907. /**
  908. * Return command help documentation.
  909. *
  910. * @return {String}
  911. * @api private
  912. */
  913. Command.prototype.commandHelp = function() {
  914. if (!this.commands.length) return '';
  915. var commands = this.prepareCommands();
  916. var width = this.padWidth();
  917. return [
  918. 'Commands:',
  919. commands.map(function(cmd) {
  920. var desc = cmd[1] ? ' ' + cmd[1] : '';
  921. return (desc ? pad(cmd[0], width) : cmd[0]) + desc;
  922. }).join('\n').replace(/^/gm, ' '),
  923. ''
  924. ].join('\n');
  925. };
  926. /**
  927. * Return program help documentation.
  928. *
  929. * @return {String}
  930. * @api private
  931. */
  932. Command.prototype.helpInformation = function() {
  933. var desc = [];
  934. if (this._description) {
  935. desc = [
  936. this._description,
  937. ''
  938. ];
  939. var argsDescription = this._argsDescription;
  940. if (argsDescription && this._args.length) {
  941. var width = this.padWidth();
  942. desc.push('Arguments:');
  943. desc.push('');
  944. this._args.forEach(function(arg) {
  945. desc.push(' ' + pad(arg.name, width) + ' ' + argsDescription[arg.name]);
  946. });
  947. desc.push('');
  948. }
  949. }
  950. var cmdName = this._name;
  951. if (this._alias) {
  952. cmdName = cmdName + '|' + this._alias;
  953. }
  954. var usage = [
  955. 'Usage: ' + cmdName + ' ' + this.usage(),
  956. ''
  957. ];
  958. var cmds = [];
  959. var commandHelp = this.commandHelp();
  960. if (commandHelp) cmds = [commandHelp];
  961. var options = [
  962. 'Options:',
  963. '' + this.optionHelp().replace(/^/gm, ' '),
  964. ''
  965. ];
  966. return usage
  967. .concat(desc)
  968. .concat(options)
  969. .concat(cmds)
  970. .join('\n');
  971. };
  972. /**
  973. * Output help information for this command
  974. *
  975. * @api public
  976. */
  977. Command.prototype.outputHelp = function(cb) {
  978. if (!cb) {
  979. cb = function(passthru) {
  980. return passthru;
  981. };
  982. }
  983. process.stdout.write(cb(this.helpInformation()));
  984. this.emit('--help');
  985. };
  986. /**
  987. * Output help information and exit.
  988. *
  989. * @api public
  990. */
  991. Command.prototype.help = function(cb) {
  992. this.outputHelp(cb);
  993. process.exit();
  994. };
  995. /**
  996. * Camel-case the given `flag`
  997. *
  998. * @param {String} flag
  999. * @return {String}
  1000. * @api private
  1001. */
  1002. function camelcase(flag) {
  1003. return flag.split('-').reduce(function(str, word) {
  1004. return str + word[0].toUpperCase() + word.slice(1);
  1005. });
  1006. }
  1007. /**
  1008. * Pad `str` to `width`.
  1009. *
  1010. * @param {String} str
  1011. * @param {Number} width
  1012. * @return {String}
  1013. * @api private
  1014. */
  1015. function pad(str, width) {
  1016. var len = Math.max(0, width - str.length);
  1017. return str + Array(len + 1).join(' ');
  1018. }
  1019. /**
  1020. * Output help information if necessary
  1021. *
  1022. * @param {Command} command to output help for
  1023. * @param {Array} array of options to search for -h or --help
  1024. * @api private
  1025. */
  1026. function outputHelpIfNecessary(cmd, options) {
  1027. options = options || [];
  1028. for (var i = 0; i < options.length; i++) {
  1029. if (options[i] === '--help' || options[i] === '-h') {
  1030. cmd.outputHelp();
  1031. process.exit(0);
  1032. }
  1033. }
  1034. }
  1035. /**
  1036. * Takes an argument an returns its human readable equivalent for help usage.
  1037. *
  1038. * @param {Object} arg
  1039. * @return {String}
  1040. * @api private
  1041. */
  1042. function humanReadableArgName(arg) {
  1043. var nameOutput = arg.name + (arg.variadic === true ? '...' : '');
  1044. return arg.required
  1045. ? '<' + nameOutput + '>'
  1046. : '[' + nameOutput + ']';
  1047. }
  1048. // for versions before node v0.8 when there weren't `fs.existsSync`
  1049. function exists(file) {
  1050. try {
  1051. if (fs.statSync(file).isFile()) {
  1052. return true;
  1053. }
  1054. } catch (e) {
  1055. return false;
  1056. }
  1057. }