index.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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. * Expose the root command.
  12. */
  13. exports = module.exports = new Command();
  14. /**
  15. * Expose `Command`.
  16. */
  17. exports.Command = Command;
  18. /**
  19. * Expose `Option`.
  20. */
  21. exports.Option = Option;
  22. /**
  23. * Initialize a new `Option` with the given `flags` and `description`.
  24. *
  25. * @param {String} flags
  26. * @param {String} description
  27. * @api public
  28. */
  29. function Option(flags, description) {
  30. this.flags = flags;
  31. this.required = ~flags.indexOf('<');
  32. this.optional = ~flags.indexOf('[');
  33. this.bool = !~flags.indexOf('-no-');
  34. flags = flags.split(/[ ,|]+/);
  35. if (flags.length > 1 && !/^[[<]/.test(flags[1])) this.short = flags.shift();
  36. this.long = flags.shift();
  37. this.description = description || '';
  38. }
  39. /**
  40. * Return option name.
  41. *
  42. * @return {String}
  43. * @api private
  44. */
  45. Option.prototype.name = function() {
  46. return this.long
  47. .replace('--', '')
  48. .replace('no-', '');
  49. };
  50. /**
  51. * Return option name, in a camelcase format that can be used
  52. * as a object attribute key.
  53. *
  54. * @return {String}
  55. * @api private
  56. */
  57. Option.prototype.attributeName = function() {
  58. return camelcase( this.name() );
  59. };
  60. /**
  61. * Check if `arg` matches the short or long flag.
  62. *
  63. * @param {String} arg
  64. * @return {Boolean}
  65. * @api private
  66. */
  67. Option.prototype.is = function(arg) {
  68. return arg == this.short || arg == this.long;
  69. };
  70. /**
  71. * Initialize a new `Command`.
  72. *
  73. * @param {String} name
  74. * @api public
  75. */
  76. function Command(name) {
  77. this.commands = [];
  78. this.options = [];
  79. this._execs = {};
  80. this._allowUnknownOption = false;
  81. this._args = [];
  82. this._name = name || '';
  83. }
  84. /**
  85. * Inherit from `EventEmitter.prototype`.
  86. */
  87. Command.prototype.__proto__ = EventEmitter.prototype;
  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 && null == args[i]) {
  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. }
  344. else {
  345. defaultValue = fn;
  346. fn = null;
  347. }
  348. }
  349. // preassign default value only for --no-*, [optional], or <required>
  350. if (false == option.bool || option.optional || option.required) {
  351. // when --no-* we make sure default is true
  352. if (false == option.bool) defaultValue = true;
  353. // preassign only if we have a default
  354. if (undefined !== defaultValue) {
  355. self[name] = defaultValue;
  356. option.defaultValue = defaultValue;
  357. }
  358. }
  359. // register the option
  360. this.options.push(option);
  361. // when it's passed assign the value
  362. // and conditionally invoke the callback
  363. this.on('option:' + oname, function(val) {
  364. // coercion
  365. if (null !== val && fn) val = fn(val, undefined === self[name]
  366. ? defaultValue
  367. : self[name]);
  368. // unassigned or bool
  369. if ('boolean' == typeof self[name] || 'undefined' == typeof self[name]) {
  370. // if no value, bool true, and we have a default, then use it!
  371. if (null == val) {
  372. self[name] = option.bool
  373. ? defaultValue || true
  374. : false;
  375. } else {
  376. self[name] = val;
  377. }
  378. } else if (null !== val) {
  379. // reassign
  380. self[name] = val;
  381. }
  382. });
  383. return this;
  384. };
  385. /**
  386. * Allow unknown options on the command line.
  387. *
  388. * @param {Boolean} arg if `true` or omitted, no error will be thrown
  389. * for unknown options.
  390. * @api public
  391. */
  392. Command.prototype.allowUnknownOption = function(arg) {
  393. this._allowUnknownOption = arguments.length === 0 || arg;
  394. return this;
  395. };
  396. /**
  397. * Parse `argv`, settings options and invoking commands when defined.
  398. *
  399. * @param {Array} argv
  400. * @return {Command} for chaining
  401. * @api public
  402. */
  403. Command.prototype.parse = function(argv) {
  404. // implicit help
  405. if (this.executables) this.addImplicitHelpCommand();
  406. // store raw args
  407. this.rawArgs = argv;
  408. // guess name
  409. this._name = this._name || basename(argv[1], '.js');
  410. // github-style sub-commands with no sub-command
  411. if (this.executables && argv.length < 3 && !this.defaultExecutable) {
  412. // this user needs help
  413. argv.push('--help');
  414. }
  415. // process argv
  416. var parsed = this.parseOptions(this.normalize(argv.slice(2)));
  417. var args = this.args = parsed.args;
  418. var result = this.parseArgs(this.args, parsed.unknown);
  419. // executable sub-commands
  420. var name = result.args[0];
  421. var aliasCommand = null;
  422. // check alias of sub commands
  423. if (name) {
  424. aliasCommand = this.commands.filter(function(command) {
  425. return command.alias() === name;
  426. })[0];
  427. }
  428. if (this._execs[name] && typeof this._execs[name] != "function") {
  429. return this.executeSubCommand(argv, args, parsed.unknown);
  430. } else if (aliasCommand) {
  431. // is alias of a subCommand
  432. args[0] = aliasCommand._name;
  433. return this.executeSubCommand(argv, args, parsed.unknown);
  434. } else if (this.defaultExecutable) {
  435. // use the default subcommand
  436. args.unshift(this.defaultExecutable);
  437. return this.executeSubCommand(argv, args, parsed.unknown);
  438. }
  439. return result;
  440. };
  441. /**
  442. * Execute a sub-command executable.
  443. *
  444. * @param {Array} argv
  445. * @param {Array} args
  446. * @param {Array} unknown
  447. * @api private
  448. */
  449. Command.prototype.executeSubCommand = function(argv, args, unknown) {
  450. args = args.concat(unknown);
  451. if (!args.length) this.help();
  452. if ('help' == args[0] && 1 == args.length) this.help();
  453. // <cmd> --help
  454. if ('help' == args[0]) {
  455. args[0] = args[1];
  456. args[1] = '--help';
  457. }
  458. // executable
  459. var f = argv[1];
  460. // name of the subcommand, link `pm-install`
  461. var bin = basename(f, '.js') + '-' + args[0];
  462. // In case of globally installed, get the base dir where executable
  463. // subcommand file should be located at
  464. var baseDir
  465. , link = fs.lstatSync(f).isSymbolicLink() ? fs.readlinkSync(f) : f;
  466. // when symbolink is relative path
  467. if (link !== f && link.charAt(0) !== '/') {
  468. link = path.join(dirname(f), link)
  469. }
  470. baseDir = dirname(link);
  471. // prefer local `./<bin>` to bin in the $PATH
  472. var localBin = path.join(baseDir, bin);
  473. // whether bin file is a js script with explicit `.js` extension
  474. var isExplicitJS = false;
  475. if (exists(localBin + '.js')) {
  476. bin = localBin + '.js';
  477. isExplicitJS = true;
  478. } else if (exists(localBin)) {
  479. bin = localBin;
  480. }
  481. args = args.slice(1);
  482. var proc;
  483. if (process.platform !== 'win32') {
  484. if (isExplicitJS) {
  485. args.unshift(bin);
  486. // add executable arguments to spawn
  487. args = (process.execArgv || []).concat(args);
  488. proc = spawn(process.argv[0], args, { stdio: 'inherit', customFds: [0, 1, 2] });
  489. } else {
  490. proc = spawn(bin, args, { stdio: 'inherit', customFds: [0, 1, 2] });
  491. }
  492. } else {
  493. args.unshift(bin);
  494. proc = spawn(process.execPath, args, { stdio: 'inherit'});
  495. }
  496. var signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP'];
  497. signals.forEach(function(signal) {
  498. process.on(signal, function(){
  499. if ((proc.killed === false) && (proc.exitCode === null)){
  500. proc.kill(signal);
  501. }
  502. });
  503. });
  504. proc.on('close', process.exit.bind(process));
  505. proc.on('error', function(err) {
  506. if (err.code == "ENOENT") {
  507. console.error('\n %s(1) does not exist, try --help\n', bin);
  508. } else if (err.code == "EACCES") {
  509. console.error('\n %s(1) not executable. try chmod or run with root\n', bin);
  510. }
  511. process.exit(1);
  512. });
  513. // Store the reference to the child process
  514. this.runningCommand = proc;
  515. };
  516. /**
  517. * Normalize `args`, splitting joined short flags. For example
  518. * the arg "-abc" is equivalent to "-a -b -c".
  519. * This also normalizes equal sign and splits "--abc=def" into "--abc def".
  520. *
  521. * @param {Array} args
  522. * @return {Array}
  523. * @api private
  524. */
  525. Command.prototype.normalize = function(args) {
  526. var ret = []
  527. , arg
  528. , lastOpt
  529. , index;
  530. for (var i = 0, len = args.length; i < len; ++i) {
  531. arg = args[i];
  532. if (i > 0) {
  533. lastOpt = this.optionFor(args[i-1]);
  534. }
  535. if (arg === '--') {
  536. // Honor option terminator
  537. ret = ret.concat(args.slice(i));
  538. break;
  539. } else if (lastOpt && lastOpt.required) {
  540. ret.push(arg);
  541. } else if (arg.length > 1 && '-' == arg[0] && '-' != arg[1]) {
  542. arg.slice(1).split('').forEach(function(c) {
  543. ret.push('-' + c);
  544. });
  545. } else if (/^--/.test(arg) && ~(index = arg.indexOf('='))) {
  546. ret.push(arg.slice(0, index), arg.slice(index + 1));
  547. } else {
  548. ret.push(arg);
  549. }
  550. }
  551. return ret;
  552. };
  553. /**
  554. * Parse command `args`.
  555. *
  556. * When listener(s) are available those
  557. * callbacks are invoked, otherwise the "*"
  558. * event is emitted and those actions are invoked.
  559. *
  560. * @param {Array} args
  561. * @return {Command} for chaining
  562. * @api private
  563. */
  564. Command.prototype.parseArgs = function(args, unknown) {
  565. var name;
  566. if (args.length) {
  567. name = args[0];
  568. if (this.listeners('command:' + name).length) {
  569. this.emit('command:' + args.shift(), args, unknown);
  570. } else {
  571. this.emit('command:*', args);
  572. }
  573. } else {
  574. outputHelpIfNecessary(this, unknown);
  575. // If there were no args and we have unknown options,
  576. // then they are extraneous and we need to error.
  577. if (unknown.length > 0) {
  578. this.unknownOption(unknown[0]);
  579. }
  580. }
  581. return this;
  582. };
  583. /**
  584. * Return an option matching `arg` if any.
  585. *
  586. * @param {String} arg
  587. * @return {Option}
  588. * @api private
  589. */
  590. Command.prototype.optionFor = function(arg) {
  591. for (var i = 0, len = this.options.length; i < len; ++i) {
  592. if (this.options[i].is(arg)) {
  593. return this.options[i];
  594. }
  595. }
  596. };
  597. /**
  598. * Parse options from `argv` returning `argv`
  599. * void of these options.
  600. *
  601. * @param {Array} argv
  602. * @return {Array}
  603. * @api public
  604. */
  605. Command.prototype.parseOptions = function(argv) {
  606. var args = []
  607. , len = argv.length
  608. , literal
  609. , option
  610. , arg;
  611. var unknownOptions = [];
  612. // parse options
  613. for (var i = 0; i < len; ++i) {
  614. arg = argv[i];
  615. // literal args after --
  616. if (literal) {
  617. args.push(arg);
  618. continue;
  619. }
  620. if ('--' == arg) {
  621. literal = true;
  622. continue;
  623. }
  624. // find matching Option
  625. option = this.optionFor(arg);
  626. // option is defined
  627. if (option) {
  628. // requires arg
  629. if (option.required) {
  630. arg = argv[++i];
  631. if (null == arg) return this.optionMissingArgument(option);
  632. this.emit('option:' + option.name(), arg);
  633. // optional arg
  634. } else if (option.optional) {
  635. arg = argv[i+1];
  636. if (null == arg || ('-' == arg[0] && '-' != arg)) {
  637. arg = null;
  638. } else {
  639. ++i;
  640. }
  641. this.emit('option:' + option.name(), arg);
  642. // bool
  643. } else {
  644. this.emit('option:' + option.name());
  645. }
  646. continue;
  647. }
  648. // looks like an option
  649. if (arg.length > 1 && '-' == arg[0]) {
  650. unknownOptions.push(arg);
  651. // If the next argument looks like it might be
  652. // an argument for this option, we pass it on.
  653. // If it isn't, then it'll simply be ignored
  654. if (argv[i+1] && '-' != argv[i+1][0]) {
  655. unknownOptions.push(argv[++i]);
  656. }
  657. continue;
  658. }
  659. // arg
  660. args.push(arg);
  661. }
  662. return { args: args, unknown: unknownOptions };
  663. };
  664. /**
  665. * Return an object containing options as key-value pairs
  666. *
  667. * @return {Object}
  668. * @api public
  669. */
  670. Command.prototype.opts = function() {
  671. var result = {}
  672. , len = this.options.length;
  673. for (var i = 0 ; i < len; i++) {
  674. var key = this.options[i].attributeName();
  675. result[key] = key === 'version' ? this._version : this[key];
  676. }
  677. return result;
  678. };
  679. /**
  680. * Argument `name` is missing.
  681. *
  682. * @param {String} name
  683. * @api private
  684. */
  685. Command.prototype.missingArgument = function(name) {
  686. console.error();
  687. console.error(" error: missing required argument `%s'", name);
  688. console.error();
  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. console.error();
  700. if (flag) {
  701. console.error(" error: option `%s' argument missing, got `%s'", option.flags, flag);
  702. } else {
  703. console.error(" error: option `%s' argument missing", option.flags);
  704. }
  705. console.error();
  706. process.exit(1);
  707. };
  708. /**
  709. * Unknown option `flag`.
  710. *
  711. * @param {String} flag
  712. * @api private
  713. */
  714. Command.prototype.unknownOption = function(flag) {
  715. if (this._allowUnknownOption) return;
  716. console.error();
  717. console.error(" error: unknown option `%s'", flag);
  718. console.error();
  719. process.exit(1);
  720. };
  721. /**
  722. * Variadic argument with `name` is not the last argument as required.
  723. *
  724. * @param {String} name
  725. * @api private
  726. */
  727. Command.prototype.variadicArgNotLast = function(name) {
  728. console.error();
  729. console.error(" error: variadic arguments must be last `%s'", name);
  730. console.error();
  731. process.exit(1);
  732. };
  733. /**
  734. * Set the program version to `str`.
  735. *
  736. * This method auto-registers the "-V, --version" flag
  737. * which will print the version number when passed.
  738. *
  739. * @param {String} str
  740. * @param {String} [flags]
  741. * @return {Command} for chaining
  742. * @api public
  743. */
  744. Command.prototype.version = function(str, flags) {
  745. if (0 == arguments.length) return this._version;
  746. this._version = str;
  747. flags = flags || '-V, --version';
  748. this.option(flags, 'output the version number');
  749. this.on('option:version', function() {
  750. process.stdout.write(str + '\n');
  751. process.exit(0);
  752. });
  753. return this;
  754. };
  755. /**
  756. * Set the description to `str`.
  757. *
  758. * @param {String} str
  759. * @return {String|Command}
  760. * @api public
  761. */
  762. Command.prototype.description = function(str) {
  763. if (0 === arguments.length) return this._description;
  764. this._description = str;
  765. return this;
  766. };
  767. /**
  768. * Set an alias for the command
  769. *
  770. * @param {String} alias
  771. * @return {String|Command}
  772. * @api public
  773. */
  774. Command.prototype.alias = function(alias) {
  775. var command = this;
  776. if(this.commands.length !== 0) {
  777. command = this.commands[this.commands.length - 1]
  778. }
  779. if (arguments.length === 0) return command._alias;
  780. if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
  781. command._alias = alias;
  782. return this;
  783. };
  784. /**
  785. * Set / get the command usage `str`.
  786. *
  787. * @param {String} str
  788. * @return {String|Command}
  789. * @api public
  790. */
  791. Command.prototype.usage = function(str) {
  792. var args = this._args.map(function(arg) {
  793. return humanReadableArgName(arg);
  794. });
  795. var usage = '[options]'
  796. + (this.commands.length ? ' [command]' : '')
  797. + (this._args.length ? ' ' + args.join(' ') : '');
  798. if (0 == arguments.length) return this._usage || usage;
  799. this._usage = str;
  800. return this;
  801. };
  802. /**
  803. * Get or set the name of the command
  804. *
  805. * @param {String} str
  806. * @return {String|Command}
  807. * @api public
  808. */
  809. Command.prototype.name = function(str) {
  810. if (0 === arguments.length) return this._name;
  811. this._name = str;
  812. return this;
  813. };
  814. /**
  815. * Return the largest option length.
  816. *
  817. * @return {Number}
  818. * @api private
  819. */
  820. Command.prototype.largestOptionLength = function() {
  821. return this.options.reduce(function(max, option) {
  822. return Math.max(max, option.flags.length);
  823. }, 0);
  824. };
  825. /**
  826. * Return help for options.
  827. *
  828. * @return {String}
  829. * @api private
  830. */
  831. Command.prototype.optionHelp = function() {
  832. var width = this.largestOptionLength();
  833. // Append the help information
  834. return this.options.map(function(option) {
  835. return pad(option.flags, width) + ' ' + option.description
  836. + (option.defaultValue !== undefined ? ' (default: ' + option.defaultValue + ')' : '');
  837. }).concat([pad('-h, --help', width) + ' ' + 'output usage information'])
  838. .join('\n');
  839. };
  840. /**
  841. * Return command help documentation.
  842. *
  843. * @return {String}
  844. * @api private
  845. */
  846. Command.prototype.commandHelp = function() {
  847. if (!this.commands.length) return '';
  848. var commands = this.commands.filter(function(cmd) {
  849. return !cmd._noHelp;
  850. }).map(function(cmd) {
  851. var args = cmd._args.map(function(arg) {
  852. return humanReadableArgName(arg);
  853. }).join(' ');
  854. return [
  855. cmd._name
  856. + (cmd._alias ? '|' + cmd._alias : '')
  857. + (cmd.options.length ? ' [options]' : '')
  858. + ' ' + args
  859. , cmd._description
  860. ];
  861. });
  862. var width = commands.reduce(function(max, command) {
  863. return Math.max(max, command[0].length);
  864. }, 0);
  865. return [
  866. ''
  867. , ' Commands:'
  868. , ''
  869. , commands.map(function(cmd) {
  870. var desc = cmd[1] ? ' ' + cmd[1] : '';
  871. return pad(cmd[0], width) + desc;
  872. }).join('\n').replace(/^/gm, ' ')
  873. , ''
  874. ].join('\n');
  875. };
  876. /**
  877. * Return program help documentation.
  878. *
  879. * @return {String}
  880. * @api private
  881. */
  882. Command.prototype.helpInformation = function() {
  883. var desc = [];
  884. if (this._description) {
  885. desc = [
  886. ' ' + this._description
  887. , ''
  888. ];
  889. }
  890. var cmdName = this._name;
  891. if (this._alias) {
  892. cmdName = cmdName + '|' + this._alias;
  893. }
  894. var usage = [
  895. ''
  896. ,' Usage: ' + cmdName + ' ' + this.usage()
  897. , ''
  898. ];
  899. var cmds = [];
  900. var commandHelp = this.commandHelp();
  901. if (commandHelp) cmds = [commandHelp];
  902. var options = [
  903. ''
  904. , ' Options:'
  905. , ''
  906. , '' + this.optionHelp().replace(/^/gm, ' ')
  907. , ''
  908. ];
  909. return usage
  910. .concat(desc)
  911. .concat(options)
  912. .concat(cmds)
  913. .join('\n');
  914. };
  915. /**
  916. * Output help information for this command
  917. *
  918. * @api public
  919. */
  920. Command.prototype.outputHelp = function(cb) {
  921. if (!cb) {
  922. cb = function(passthru) {
  923. return passthru;
  924. }
  925. }
  926. process.stdout.write(cb(this.helpInformation()));
  927. this.emit('--help');
  928. };
  929. /**
  930. * Output help information and exit.
  931. *
  932. * @api public
  933. */
  934. Command.prototype.help = function(cb) {
  935. this.outputHelp(cb);
  936. process.exit();
  937. };
  938. /**
  939. * Camel-case the given `flag`
  940. *
  941. * @param {String} flag
  942. * @return {String}
  943. * @api private
  944. */
  945. function camelcase(flag) {
  946. return flag.split('-').reduce(function(str, word) {
  947. return str + word[0].toUpperCase() + word.slice(1);
  948. });
  949. }
  950. /**
  951. * Pad `str` to `width`.
  952. *
  953. * @param {String} str
  954. * @param {Number} width
  955. * @return {String}
  956. * @api private
  957. */
  958. function pad(str, width) {
  959. var len = Math.max(0, width - str.length);
  960. return str + Array(len + 1).join(' ');
  961. }
  962. /**
  963. * Output help information if necessary
  964. *
  965. * @param {Command} command to output help for
  966. * @param {Array} array of options to search for -h or --help
  967. * @api private
  968. */
  969. function outputHelpIfNecessary(cmd, options) {
  970. options = options || [];
  971. for (var i = 0; i < options.length; i++) {
  972. if (options[i] == '--help' || options[i] == '-h') {
  973. cmd.outputHelp();
  974. process.exit(0);
  975. }
  976. }
  977. }
  978. /**
  979. * Takes an argument an returns its human readable equivalent for help usage.
  980. *
  981. * @param {Object} arg
  982. * @return {String}
  983. * @api private
  984. */
  985. function humanReadableArgName(arg) {
  986. var nameOutput = arg.name + (arg.variadic === true ? '...' : '');
  987. return arg.required
  988. ? '<' + nameOutput + '>'
  989. : '[' + nameOutput + ']'
  990. }
  991. // for versions before node v0.8 when there weren't `fs.existsSync`
  992. function exists(file) {
  993. try {
  994. if (fs.statSync(file).isFile()) {
  995. return true;
  996. }
  997. } catch (e) {
  998. return false;
  999. }
  1000. }