UI for Zipcoin Blue

index.js 27KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232
  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. }
  580. return this;
  581. };
  582. /**
  583. * Return an option matching `arg` if any.
  584. *
  585. * @param {String} arg
  586. * @return {Option}
  587. * @api private
  588. */
  589. Command.prototype.optionFor = function(arg) {
  590. for (var i = 0, len = this.options.length; i < len; ++i) {
  591. if (this.options[i].is(arg)) {
  592. return this.options[i];
  593. }
  594. }
  595. };
  596. /**
  597. * Parse options from `argv` returning `argv`
  598. * void of these options.
  599. *
  600. * @param {Array} argv
  601. * @return {Array}
  602. * @api public
  603. */
  604. Command.prototype.parseOptions = function(argv) {
  605. var args = [],
  606. len = argv.length,
  607. literal,
  608. option,
  609. arg;
  610. var unknownOptions = [];
  611. // parse options
  612. for (var i = 0; i < len; ++i) {
  613. arg = argv[i];
  614. // literal args after --
  615. if (literal) {
  616. args.push(arg);
  617. continue;
  618. }
  619. if (arg === '--') {
  620. literal = true;
  621. continue;
  622. }
  623. // find matching Option
  624. option = this.optionFor(arg);
  625. // option is defined
  626. if (option) {
  627. // requires arg
  628. if (option.required) {
  629. arg = argv[++i];
  630. if (arg == null) return this.optionMissingArgument(option);
  631. this.emit('option:' + option.name(), arg);
  632. // optional arg
  633. } else if (option.optional) {
  634. arg = argv[i + 1];
  635. if (arg == null || (arg[0] === '-' && arg !== '-')) {
  636. arg = null;
  637. } else {
  638. ++i;
  639. }
  640. this.emit('option:' + option.name(), arg);
  641. // bool
  642. } else {
  643. this.emit('option:' + option.name());
  644. }
  645. continue;
  646. }
  647. // looks like an option
  648. if (arg.length > 1 && arg[0] === '-') {
  649. unknownOptions.push(arg);
  650. // If the next argument looks like it might be
  651. // an argument for this option, we pass it on.
  652. // If it isn't, then it'll simply be ignored
  653. if ((i + 1) < argv.length && argv[i + 1][0] !== '-') {
  654. unknownOptions.push(argv[++i]);
  655. }
  656. continue;
  657. }
  658. // arg
  659. args.push(arg);
  660. }
  661. return { args: args, unknown: unknownOptions };
  662. };
  663. /**
  664. * Return an object containing options as key-value pairs
  665. *
  666. * @return {Object}
  667. * @api public
  668. */
  669. Command.prototype.opts = function() {
  670. var result = {},
  671. len = this.options.length;
  672. for (var i = 0; i < len; i++) {
  673. var key = this.options[i].attributeName();
  674. result[key] = key === this._versionOptionName ? this._version : this[key];
  675. }
  676. return result;
  677. };
  678. /**
  679. * Argument `name` is missing.
  680. *
  681. * @param {String} name
  682. * @api private
  683. */
  684. Command.prototype.missingArgument = function(name) {
  685. console.error();
  686. console.error(" error: missing required argument `%s'", name);
  687. console.error();
  688. process.exit(1);
  689. };
  690. /**
  691. * `Option` is missing an argument, but received `flag` or nothing.
  692. *
  693. * @param {String} option
  694. * @param {String} flag
  695. * @api private
  696. */
  697. Command.prototype.optionMissingArgument = function(option, flag) {
  698. console.error();
  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. console.error();
  705. process.exit(1);
  706. };
  707. /**
  708. * Unknown option `flag`.
  709. *
  710. * @param {String} flag
  711. * @api private
  712. */
  713. Command.prototype.unknownOption = function(flag) {
  714. if (this._allowUnknownOption) return;
  715. console.error();
  716. console.error(" error: unknown option `%s'", flag);
  717. console.error();
  718. process.exit(1);
  719. };
  720. /**
  721. * Variadic argument with `name` is not the last argument as required.
  722. *
  723. * @param {String} name
  724. * @api private
  725. */
  726. Command.prototype.variadicArgNotLast = function(name) {
  727. console.error();
  728. console.error(" error: variadic arguments must be last `%s'", name);
  729. console.error();
  730. process.exit(1);
  731. };
  732. /**
  733. * Set the program version to `str`.
  734. *
  735. * This method auto-registers the "-V, --version" flag
  736. * which will print the version number when passed.
  737. *
  738. * @param {String} str
  739. * @param {String} [flags]
  740. * @return {Command} for chaining
  741. * @api public
  742. */
  743. Command.prototype.version = function(str, flags) {
  744. if (arguments.length === 0) return this._version;
  745. this._version = str;
  746. flags = flags || '-V, --version';
  747. var versionOption = new Option(flags, 'output the version number');
  748. this._versionOptionName = versionOption.long.substr(2) || 'version';
  749. this.options.push(versionOption);
  750. this.on('option:' + this._versionOptionName, function() {
  751. process.stdout.write(str + '\n');
  752. process.exit(0);
  753. });
  754. return this;
  755. };
  756. /**
  757. * Set the description to `str`.
  758. *
  759. * @param {String} str
  760. * @param {Object} argsDescription
  761. * @return {String|Command}
  762. * @api public
  763. */
  764. Command.prototype.description = function(str, argsDescription) {
  765. if (arguments.length === 0) return this._description;
  766. this._description = str;
  767. this._argsDescription = argsDescription;
  768. return this;
  769. };
  770. /**
  771. * Set an alias for the command
  772. *
  773. * @param {String} alias
  774. * @return {String|Command}
  775. * @api public
  776. */
  777. Command.prototype.alias = function(alias) {
  778. var command = this;
  779. if (this.commands.length !== 0) {
  780. command = this.commands[this.commands.length - 1];
  781. }
  782. if (arguments.length === 0) return command._alias;
  783. if (alias === command._name) throw new Error('Command alias can\'t be the same as its name');
  784. command._alias = alias;
  785. return this;
  786. };
  787. /**
  788. * Set / get the command usage `str`.
  789. *
  790. * @param {String} str
  791. * @return {String|Command}
  792. * @api public
  793. */
  794. Command.prototype.usage = function(str) {
  795. var args = this._args.map(function(arg) {
  796. return humanReadableArgName(arg);
  797. });
  798. var usage = '[options]' +
  799. (this.commands.length ? ' [command]' : '') +
  800. (this._args.length ? ' ' + args.join(' ') : '');
  801. if (arguments.length === 0) return this._usage || usage;
  802. this._usage = str;
  803. return this;
  804. };
  805. /**
  806. * Get or set the name of the command
  807. *
  808. * @param {String} str
  809. * @return {String|Command}
  810. * @api public
  811. */
  812. Command.prototype.name = function(str) {
  813. if (arguments.length === 0) return this._name;
  814. this._name = str;
  815. return this;
  816. };
  817. /**
  818. * Return prepared commands.
  819. *
  820. * @return {Array}
  821. * @api private
  822. */
  823. Command.prototype.prepareCommands = function() {
  824. return this.commands.filter(function(cmd) {
  825. return !cmd._noHelp;
  826. }).map(function(cmd) {
  827. var args = cmd._args.map(function(arg) {
  828. return humanReadableArgName(arg);
  829. }).join(' ');
  830. return [
  831. cmd._name +
  832. (cmd._alias ? '|' + cmd._alias : '') +
  833. (cmd.options.length ? ' [options]' : '') +
  834. (args ? ' ' + args : ''),
  835. cmd._description
  836. ];
  837. });
  838. };
  839. /**
  840. * Return the largest command length.
  841. *
  842. * @return {Number}
  843. * @api private
  844. */
  845. Command.prototype.largestCommandLength = function() {
  846. var commands = this.prepareCommands();
  847. return commands.reduce(function(max, command) {
  848. return Math.max(max, command[0].length);
  849. }, 0);
  850. };
  851. /**
  852. * Return the largest option length.
  853. *
  854. * @return {Number}
  855. * @api private
  856. */
  857. Command.prototype.largestOptionLength = function() {
  858. var options = [].slice.call(this.options);
  859. options.push({
  860. flags: '-h, --help'
  861. });
  862. return options.reduce(function(max, option) {
  863. return Math.max(max, option.flags.length);
  864. }, 0);
  865. };
  866. /**
  867. * Return the largest arg length.
  868. *
  869. * @return {Number}
  870. * @api private
  871. */
  872. Command.prototype.largestArgLength = function() {
  873. return this._args.reduce(function(max, arg) {
  874. return Math.max(max, arg.name.length);
  875. }, 0);
  876. };
  877. /**
  878. * Return the pad width.
  879. *
  880. * @return {Number}
  881. * @api private
  882. */
  883. Command.prototype.padWidth = function() {
  884. var width = this.largestOptionLength();
  885. if (this._argsDescription && this._args.length) {
  886. if (this.largestArgLength() > width) {
  887. width = this.largestArgLength();
  888. }
  889. }
  890. if (this.commands && this.commands.length) {
  891. if (this.largestCommandLength() > width) {
  892. width = this.largestCommandLength();
  893. }
  894. }
  895. return width;
  896. };
  897. /**
  898. * Return help for options.
  899. *
  900. * @return {String}
  901. * @api private
  902. */
  903. Command.prototype.optionHelp = function() {
  904. var width = this.padWidth();
  905. // Append the help information
  906. return this.options.map(function(option) {
  907. return pad(option.flags, width) + ' ' + option.description +
  908. ((option.bool && option.defaultValue !== undefined) ? ' (default: ' + option.defaultValue + ')' : '');
  909. }).concat([pad('-h, --help', width) + ' ' + 'output usage information'])
  910. .join('\n');
  911. };
  912. /**
  913. * Return command help documentation.
  914. *
  915. * @return {String}
  916. * @api private
  917. */
  918. Command.prototype.commandHelp = function() {
  919. if (!this.commands.length) return '';
  920. var commands = this.prepareCommands();
  921. var width = this.padWidth();
  922. return [
  923. ' Commands:',
  924. '',
  925. commands.map(function(cmd) {
  926. var desc = cmd[1] ? ' ' + cmd[1] : '';
  927. return (desc ? pad(cmd[0], width) : cmd[0]) + desc;
  928. }).join('\n').replace(/^/gm, ' '),
  929. ''
  930. ].join('\n');
  931. };
  932. /**
  933. * Return program help documentation.
  934. *
  935. * @return {String}
  936. * @api private
  937. */
  938. Command.prototype.helpInformation = function() {
  939. var desc = [];
  940. if (this._description) {
  941. desc = [
  942. ' ' + this._description,
  943. ''
  944. ];
  945. var argsDescription = this._argsDescription;
  946. if (argsDescription && this._args.length) {
  947. var width = this.padWidth();
  948. desc.push(' Arguments:');
  949. desc.push('');
  950. this._args.forEach(function(arg) {
  951. desc.push(' ' + pad(arg.name, width) + ' ' + argsDescription[arg.name]);
  952. });
  953. desc.push('');
  954. }
  955. }
  956. var cmdName = this._name;
  957. if (this._alias) {
  958. cmdName = cmdName + '|' + this._alias;
  959. }
  960. var usage = [
  961. '',
  962. ' Usage: ' + cmdName + ' ' + this.usage(),
  963. ''
  964. ];
  965. var cmds = [];
  966. var commandHelp = this.commandHelp();
  967. if (commandHelp) cmds = [commandHelp];
  968. var options = [
  969. ' Options:',
  970. '',
  971. '' + this.optionHelp().replace(/^/gm, ' '),
  972. ''
  973. ];
  974. return usage
  975. .concat(desc)
  976. .concat(options)
  977. .concat(cmds)
  978. .join('\n');
  979. };
  980. /**
  981. * Output help information for this command
  982. *
  983. * @api public
  984. */
  985. Command.prototype.outputHelp = function(cb) {
  986. if (!cb) {
  987. cb = function(passthru) {
  988. return passthru;
  989. };
  990. }
  991. process.stdout.write(cb(this.helpInformation()));
  992. this.emit('--help');
  993. };
  994. /**
  995. * Output help information and exit.
  996. *
  997. * @api public
  998. */
  999. Command.prototype.help = function(cb) {
  1000. this.outputHelp(cb);
  1001. process.exit();
  1002. };
  1003. /**
  1004. * Camel-case the given `flag`
  1005. *
  1006. * @param {String} flag
  1007. * @return {String}
  1008. * @api private
  1009. */
  1010. function camelcase(flag) {
  1011. return flag.split('-').reduce(function(str, word) {
  1012. return str + word[0].toUpperCase() + word.slice(1);
  1013. });
  1014. }
  1015. /**
  1016. * Pad `str` to `width`.
  1017. *
  1018. * @param {String} str
  1019. * @param {Number} width
  1020. * @return {String}
  1021. * @api private
  1022. */
  1023. function pad(str, width) {
  1024. var len = Math.max(0, width - str.length);
  1025. return str + Array(len + 1).join(' ');
  1026. }
  1027. /**
  1028. * Output help information if necessary
  1029. *
  1030. * @param {Command} command to output help for
  1031. * @param {Array} array of options to search for -h or --help
  1032. * @api private
  1033. */
  1034. function outputHelpIfNecessary(cmd, options) {
  1035. options = options || [];
  1036. for (var i = 0; i < options.length; i++) {
  1037. if (options[i] === '--help' || options[i] === '-h') {
  1038. cmd.outputHelp();
  1039. process.exit(0);
  1040. }
  1041. }
  1042. }
  1043. /**
  1044. * Takes an argument an returns its human readable equivalent for help usage.
  1045. *
  1046. * @param {Object} arg
  1047. * @return {String}
  1048. * @api private
  1049. */
  1050. function humanReadableArgName(arg) {
  1051. var nameOutput = arg.name + (arg.variadic === true ? '...' : '');
  1052. return arg.required
  1053. ? '<' + nameOutput + '>'
  1054. : '[' + nameOutput + ']';
  1055. }
  1056. // for versions before node v0.8 when there weren't `fs.existsSync`
  1057. function exists(file) {
  1058. try {
  1059. if (fs.statSync(file).isFile()) {
  1060. return true;
  1061. }
  1062. } catch (e) {
  1063. return false;
  1064. }
  1065. }