No Description

cli.js 36KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  1. /**
  2. * Copyright (c) 2010 Chris O'Hara <cohara87@gmail.com>
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining
  5. * a copy of this software and associated documentation files (the
  6. * "Software"), to deal in the Software without restriction, including
  7. * without limitation the rights to use, copy, modify, merge, publish,
  8. * distribute, sublicense, and/or sell copies of the Software, and to
  9. * permit persons to whom the Software is furnished to do so, subject to
  10. * the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be
  13. * included in all copies or substantial portions of the Software.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  16. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  18. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  19. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  20. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  21. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. */
  23. //Note: cli includes kof/node-natives and creationix/stack. I couldn't find
  24. //license information for either - contact me if you want your license added
  25. var cli = exports,
  26. argv, curr_opt, curr_val, full_opt, is_long,
  27. short_tags = [], opt_list, parsed = {},
  28. usage, argv_parsed, command_list, commands,
  29. daemon, daemon_arg, no_color, show_debug;
  30. cli.app = null;
  31. cli.version = null;
  32. cli.argv = [];
  33. cli.argc = 0;
  34. cli.options = {};
  35. cli.args = [];
  36. cli.command = null;
  37. cli.width = 70;
  38. cli.option_width = 25;
  39. /**
  40. * Bind kof's node-natives (https://github.com/kof/node-natives) to `cli.native`
  41. *
  42. * Rather than requiring node natives (e.g. var fs = require('fs')), all
  43. * native modules can be accessed like `cli.native.fs`
  44. */
  45. cli.native = {};
  46. var define_native = function (module) {
  47. Object.defineProperty(cli.native, module, {
  48. enumerable: true,
  49. configurable: true,
  50. get: function() {
  51. delete cli.native[module];
  52. return (cli.native[module] = require(module));
  53. }
  54. });
  55. };
  56. var natives = process.binding('natives');
  57. for (var module in natives) {
  58. define_native(module);
  59. }
  60. cli.output = console.log;
  61. cli.exit = require('exit');
  62. /**
  63. * Define plugins. Plugins can be enabled and disabled by calling:
  64. *
  65. * `cli.enable(plugin1, [plugin2, ...])`
  66. * `cli.disable(plugin1, [plugin2, ...])`
  67. *
  68. * Methods are chainable - `cli.enable(plugin).disable(plugin2)`.
  69. *
  70. * The 'help' plugin is enabled by default.
  71. */
  72. var enable = {
  73. help: true, //Adds -h, --help
  74. version: false, //Adds -v,--version => gets version by parsing a nearby package.json
  75. daemon: false, //Adds -d,--daemon [ARG] => (see cli.daemon() below)
  76. status: false, //Adds -k,--no-color & --debug => display plain status messages /display debug messages
  77. timeout: false, //Adds -t,--timeout N => timeout the process after N seconds
  78. catchall: false, //Adds -c,--catch => catch and output uncaughtExceptions
  79. glob: false //Adds glob matching => use cli.glob(arg)
  80. }
  81. cli.enable = function (/*plugins*/) {
  82. Array.prototype.slice.call(arguments).forEach(function (plugin) {
  83. switch (plugin) {
  84. case 'daemon':
  85. try {
  86. daemon = require('daemon');
  87. if (typeof daemon.daemonize !== 'function') {
  88. throw 'Invalid module';
  89. }
  90. } catch (e) {
  91. cli.fatal('daemon.node not installed. Please run `npm install daemon`');
  92. }
  93. break;
  94. case 'catchall':
  95. process.on('uncaughtException', function (err) {
  96. cli.error('Uncaught exception: ' + (err.msg || err));
  97. });
  98. break;
  99. case 'help': case 'version': case 'status':
  100. case 'autocomplete': case 'timeout':
  101. //Just add switches.
  102. break;
  103. case 'glob':
  104. cli.glob = require('glob');
  105. break;
  106. default:
  107. cli.fatal('Unknown plugin "' + plugin + '"');
  108. break;
  109. }
  110. enable[plugin] = true;
  111. });
  112. return cli;
  113. }
  114. cli.disable = function (/*plugins*/) {
  115. Array.prototype.slice.call(arguments).forEach(function (plugin) {
  116. if (enable[plugin]) {
  117. enable[plugin] = false;
  118. }
  119. });
  120. return cli;
  121. }
  122. /**
  123. * Sets argv (default is process.argv).
  124. *
  125. * @param {Array|String} argv
  126. * @param {Boolean} keep_arg0 (optional - default is false)
  127. * @api public
  128. */
  129. cli.setArgv = function (arr, keep_arg0) {
  130. if (typeof arr == 'string') {
  131. arr = arr.split(' ');
  132. } else {
  133. arr = arr.slice();
  134. }
  135. cli.app = arr.shift();
  136. // Strip off argv[0] if it's a node binary
  137. // So this is still broken and will break if you are calling node through a
  138. // symlink, unless you are lucky enough to have it as 'node' literal. Latter
  139. // is a hack, but resolving abspaths/symlinks is an unportable can of worms.
  140. if (!keep_arg0 && (['node', 'node.exe'].indexOf(cli.native.path.basename(cli.app)) !== -1
  141. || cli.native.path.basename(process.execPath) === cli.app
  142. || process.execPath === cli.app)) {
  143. cli.app = arr.shift();
  144. }
  145. cli.app = cli.native.path.basename(cli.app);
  146. argv_parsed = false;
  147. cli.args = cli.argv = argv = arr;
  148. cli.argc = argv.length;
  149. cli.options = {};
  150. cli.command = null;
  151. };
  152. cli.setArgv(process.argv);
  153. /**
  154. * Returns the next opt, or false if no opts are found.
  155. *
  156. * @return {String} opt
  157. * @api public
  158. */
  159. cli.next = function () {
  160. if (!argv_parsed) {
  161. cli.args = [];
  162. argv_parsed = true;
  163. }
  164. curr_val = null;
  165. //If we're currently in a group of short opts (e.g. -abc), return the next opt
  166. if (short_tags.length) {
  167. curr_opt = short_tags.shift();
  168. full_opt = '-' + curr_opt;
  169. return curr_opt;
  170. }
  171. if (!argv.length) {
  172. return false;
  173. }
  174. curr_opt = argv.shift();
  175. //If an escape sequence is found (- or --), subsequent opts are ignored
  176. if (curr_opt === '-' || curr_opt === '--') {
  177. while (argv.length) {
  178. cli.args.push(argv.shift());
  179. }
  180. return false;
  181. }
  182. //If the next element in argv isn't an opt, add it to the list of args
  183. if (curr_opt[0] !== '-') {
  184. cli.args.push(curr_opt);
  185. return cli.next();
  186. } else {
  187. //Check if the opt is short/long
  188. is_long = curr_opt[1] === '-';
  189. curr_opt = curr_opt.substr(is_long ? 2 : 1);
  190. }
  191. //Accept grouped short opts, e.g. -abc => -a -b -c
  192. if (!is_long && curr_opt.length > 1) {
  193. short_tags = curr_opt.split('');
  194. return cli.next();
  195. }
  196. var eq, len;
  197. //Check if the long opt is in the form --option=VALUE
  198. if (is_long && (eq = curr_opt.indexOf('=')) >= 0) {
  199. curr_val = curr_opt.substr(eq + 1);
  200. curr_opt = curr_opt.substr(0, eq);
  201. len = curr_val.length;
  202. //Allow values to be quoted
  203. if ((curr_val[0] === '"' && curr_val[len - 1] === '"') ||
  204. (curr_val[0] === "'" && curr_val[len - 1] === "'"))
  205. {
  206. curr_val = curr_val.substr(1, len-2);
  207. }
  208. if (curr_val.match(/^[0-9]+$/)) {
  209. curr_val = parseInt(curr_val, 10);
  210. }
  211. }
  212. //Save the opt representation for later
  213. full_opt = (is_long ? '--' : '-') + curr_opt;
  214. return curr_opt;
  215. };
  216. /**
  217. * Parses command line opts.
  218. *
  219. * `opts` must be an object with opts defined like:
  220. * long_tag: [short_tag, description, value_type, default_value];
  221. *
  222. * `commands` is an optional array or object for apps that are of the form
  223. * my_app [OPTIONS] <command> [ARGS]
  224. * The command list is output with usage information + there is bundled
  225. * support for auto-completion, etc.
  226. *
  227. * See README.md for more information.
  228. *
  229. * @param {Object} opts
  230. * @param {Object} commands (optional)
  231. * @return {Object} opts (parsed)
  232. * @api public
  233. */
  234. cli.parse = function (opts, command_def) {
  235. var default_val, i, parsed = cli.options, seen,
  236. catch_all = !opts;
  237. opt_list = opts || {};
  238. commands = command_def;
  239. command_list = commands || [];
  240. if (commands && !Array.isArray(commands)) {
  241. command_list = Object.keys(commands);
  242. }
  243. while ((o = cli.next())) {
  244. seen = false;
  245. for (var opt in opt_list) {
  246. if (!(opt_list[opt] instanceof Array)) {
  247. continue;
  248. }
  249. if (!opt_list[opt][0]) {
  250. opt_list[opt][0] = opt;
  251. }
  252. if (o === opt || o === opt_list[opt][0]) {
  253. seen = true;
  254. if (opt_list[opt].length === 2) {
  255. parsed[opt] = true;
  256. break;
  257. }
  258. default_val = null;
  259. if (opt_list[opt].length === 4) {
  260. default_val = opt_list[opt][3];
  261. }
  262. if (opt_list[opt][2] instanceof Array) {
  263. for (i = 0, l = opt_list[opt][2].length; i < l; i++) {
  264. if (typeof opt_list[opt][2][i] === 'number') {
  265. opt_list[opt][2][i] += '';
  266. }
  267. }
  268. parsed[opt] = cli.getArrayValue(opt_list[opt][2], is_long ? null : default_val);
  269. break;
  270. }
  271. if (opt_list[opt][2].toLowerCase) {
  272. opt_list[opt][2] = opt_list[opt][2].toLowerCase();
  273. }
  274. switch (opt_list[opt][2]) {
  275. case 'string': case 1: case true:
  276. parsed[opt] = cli.getValue(default_val);
  277. break;
  278. case 'int': case 'number': case 'num':
  279. case 'time': case 'seconds': case 'secs': case 'minutes': case 'mins':
  280. case 'x': case 'n':
  281. parsed[opt] = cli.getInt(default_val);
  282. break;
  283. case 'float': case 'decimal':
  284. parsed[opt] = cli.getFloat(default_val);
  285. break;
  286. case 'path': case 'file': case 'directory': case 'dir':
  287. parsed[opt] = cli.getPath(default_val, opt_list[opt][2]);
  288. break;
  289. case 'email':
  290. parsed[opt] = cli.getEmail(default_val);
  291. break;
  292. case 'url': case 'uri': case 'domain': case 'host':
  293. parsed[opt] = cli.getUrl(default_val, opt_list[opt][2]);
  294. break;
  295. case 'ip':
  296. parsed[opt] = cli.getIp(default_val);
  297. break;
  298. case 'bool': case 'boolean': case 'on':
  299. parsed[opt] = true;
  300. break;
  301. case 'false': case 'off': case false: case 0:
  302. parsed[opt] = false;
  303. break;
  304. default:
  305. cli.fatal('Unknown opt type "' + opt_list[opt][2] + '"');
  306. }
  307. break;
  308. }
  309. }
  310. if (process.env.NODE_DISABLE_COLORS) {
  311. no_color = true;
  312. }
  313. if (!seen) {
  314. if (enable.help && (o === 'h' || o === 'help')) {
  315. cli.getUsage();
  316. } else if (enable.version && (o === 'v' || o === 'version')) {
  317. if (cli.version == null) {
  318. cli.parsePackageJson();
  319. }
  320. console.error(cli.app + ' v' + cli.version);
  321. cli.exit();
  322. break;
  323. } else if (enable.daemon && (o === 'd' || o === 'daemon')) {
  324. daemon_arg = cli.getArrayValue(['start','stop','restart','pid','log'], is_long ? null : 'start');
  325. continue;
  326. } else if (enable.catchall && (o === 'c' || o === 'catch')) {
  327. continue;
  328. } else if (enable.status && (o === 'k' || o === 'no-color' || o === 'debug')) {
  329. no_color = (o === 'k' || o === 'no-color');
  330. show_debug = o === 'debug';
  331. continue;
  332. } else if (enable.timeout && (o === 't' || o === 'timeout')) {
  333. var secs = cli.getInt();
  334. setTimeout(function () {
  335. cli.fatal('Process timed out after ' + secs + 's');
  336. }, secs * 1000);
  337. continue;
  338. } else if (catch_all) {
  339. parsed[o] = curr_val || true;
  340. continue;
  341. }
  342. cli.fatal('Unknown option ' + full_opt);
  343. }
  344. }
  345. //Fill the remaining options with their default value or null
  346. for (var opt in opt_list) {
  347. default_val = opt_list[opt].length === 4 ? opt_list[opt][3] : null;
  348. if (!(opt_list[opt] instanceof Array)) {
  349. parsed[opt] = opt_list[opt];
  350. continue;
  351. } else if (typeof parsed[opt] === 'undefined') {
  352. parsed[opt] = default_val;
  353. }
  354. }
  355. if (command_list.length) {
  356. if (cli.args.length === 0) {
  357. if (enable.help) {
  358. cli.getUsage();
  359. } else {
  360. cli.fatal('A command is required (' + command_list.join(', ') + ').');
  361. }
  362. return cli.exit(1);
  363. } else {
  364. cli.command = cli.autocompleteCommand(cli.args.shift());
  365. }
  366. }
  367. cli.argc = cli.args.length;
  368. return parsed;
  369. };
  370. /**
  371. * Helper method for matching a command from the command list.
  372. *
  373. * @param {String} command
  374. * @return {String} full_command
  375. * @api public
  376. */
  377. cli.autocompleteCommand = function (command) {
  378. var list;
  379. if (!(command_list instanceof Array)) {
  380. list = Object.keys(command_list);
  381. } else {
  382. list = command_list;
  383. }
  384. var i, j = 0, c = command.length, tmp_list;
  385. if (list.length === 0 || list.indexOf(command) !== -1) {
  386. return command;
  387. }
  388. for (i = 0; i < c; i++) {
  389. tmp_list = [];
  390. l = list.length;
  391. if (l <= 1) break;
  392. for (j = 0; j < l; j++)
  393. if (list[j].length >= i && list[j][i] === command[i])
  394. tmp_list.push(list[j]);
  395. list = tmp_list;
  396. }
  397. l = list.length;
  398. if (l === 1) {
  399. return list[0];
  400. } else if (l === 0) {
  401. cli.fatal('Unknown command "' + command + '"' + (enable.help ? '. Please see --help for more information' : ''));
  402. } else {
  403. list.sort();
  404. cli.fatal('The command "' + command + '" is ambiguous and could mean "' + list.join('", "') + '"');
  405. }
  406. };
  407. /**
  408. * Adds methods to output styled status messages to stderr.
  409. *
  410. * Added methods are cli.info(msg), cli.error(msg), cli.ok(msg), and
  411. * cli.debug(msg).
  412. *
  413. * To control status messages, use the 'status' plugin
  414. * 1) debug() messages are hidden by default. Display them with
  415. * the --debug opt.
  416. * 2) to hide all status messages, use the -s or --silent opt.
  417. *
  418. * @api private
  419. */
  420. cli.status = function (msg, type) {
  421. var pre;
  422. switch (type) {
  423. case 'info':
  424. pre = no_color ? 'INFO:' : '\x1B[33mINFO\x1B[0m:';
  425. break;
  426. case 'debug':
  427. pre = no_color ? 'DEBUG:' : '\x1B[36mDEBUG\x1B[0m:';
  428. break;
  429. case 'error':
  430. case 'fatal':
  431. pre = no_color ? 'ERROR:' : '\x1B[31mERROR\x1B[0m:';
  432. break;
  433. case 'ok':
  434. pre = no_color ? 'OK:' : '\x1B[32mOK\x1B[0m:';
  435. break;
  436. }
  437. msg = pre + ' ' + msg;
  438. if (type === 'fatal') {
  439. console.error(msg);
  440. return cli.exit(1);
  441. }
  442. if (enable.status && !show_debug && type === 'debug') {
  443. return;
  444. }
  445. console.error(msg);
  446. };
  447. ['info','error','ok','debug','fatal'].forEach(function (type) {
  448. cli[type] = function (msg) {
  449. cli.status(msg, type);
  450. };
  451. });
  452. /**
  453. * Sets the app name and version.
  454. *
  455. * Usage:
  456. * setApp('myapp', '0.1.0');
  457. * setApp('./package.json'); //Pull name/version from package.json
  458. *
  459. * @param {String} name
  460. * @return cli (for chaining)
  461. * @api public
  462. */
  463. cli.setApp = function (name, version) {
  464. if (name.indexOf('package.json') !== -1) {
  465. cli.parsePackageJson(name);
  466. } else {
  467. cli.app = name;
  468. cli.version = version;
  469. }
  470. return cli;
  471. };
  472. /**
  473. * Parses the version number from package.json. If no path is specified, cli
  474. * will attempt to locate a package.json in ./, ../ or ../../
  475. *
  476. * @param {String} path (optional)
  477. * @api public
  478. */
  479. cli.parsePackageJson = function (path) {
  480. var parse_packagejson = function (path) {
  481. var packagejson = JSON.parse(cli.native.fs.readFileSync(path, 'utf8'));
  482. cli.version = packagejson.version;
  483. cli.app = packagejson.name;
  484. };
  485. var try_all = function (arr, func, err) {
  486. for (var i = 0, l = arr.length; i < l; i++) {
  487. try {
  488. func(arr[i]);
  489. return;
  490. } catch (e) {
  491. if (i === l-1) {
  492. cli.fatal(err);
  493. }
  494. }
  495. }
  496. };
  497. try {
  498. if (path) {
  499. return parse_packagejson(path);
  500. }
  501. try_all([
  502. __dirname + '/package.json',
  503. __dirname + '/../package.json',
  504. __dirname + '/../../package.json'
  505. ], parse_packagejson);
  506. } catch (e) {
  507. cli.fatal('Could not detect ' + cli.app + ' version');
  508. }
  509. };
  510. /**
  511. * Sets the usage string - default is `app [OPTIONS] [ARGS]`.
  512. *
  513. * @param {String} u
  514. * @return cli (for chaining)
  515. * @api public
  516. */
  517. cli.setUsage = function (u) {
  518. usage = u;
  519. return cli;
  520. };
  521. var pad = function (str, len) {
  522. if (typeof len === 'undefined') {
  523. len = str;
  524. str = '';
  525. }
  526. if (str.length < len) {
  527. len -= str.length;
  528. while (len--) str += ' ';
  529. }
  530. return str;
  531. };
  532. /**
  533. * Automatically build usage information from the opts list. If the help
  534. * plugin is enabled (default), this info is displayed with -h, --help.
  535. *
  536. * @api public
  537. */
  538. cli.getUsage = function (code) {
  539. var short, desc, optional, line, seen_opts = [],
  540. switch_pad = cli.option_width;
  541. var trunc_desc = function (pref, desc, len) {
  542. var pref_len = pref.length,
  543. desc_len = cli.width - pref_len,
  544. truncated = '';
  545. if (desc.length <= desc_len) {
  546. return desc;
  547. }
  548. var desc_words = (desc+'').split(' '), chars = 0, word;
  549. while (desc_words.length) {
  550. truncated += (word = desc_words.shift()) + ' ';
  551. chars += word.length;
  552. if (desc_words.length && chars + desc_words[0].length > desc_len) {
  553. truncated += '\n' + pad(pref_len);
  554. chars = 0;
  555. }
  556. }
  557. return truncated;
  558. };
  559. usage = usage || cli.app + ' [OPTIONS]' + (command_list.length ? ' <command>' : '') + ' [ARGS]';
  560. if (no_color) {
  561. console.error('Usage:\n ' + usage);
  562. console.error('Options: ');
  563. } else {
  564. console.error('\x1b[1mUsage\x1b[0m:\n ' + usage);
  565. console.error('\n\x1b[1mOptions\x1b[0m: ');
  566. }
  567. for (var opt in opt_list) {
  568. if (opt.length === 1) {
  569. long = opt_list[opt][0];
  570. short = opt;
  571. } else {
  572. long = opt;
  573. short = opt_list[opt][0];
  574. }
  575. //Parse opt_list
  576. desc = opt_list[opt][1].trim();
  577. type = opt_list[opt].length >= 3 ? opt_list[opt][2] : null;
  578. optional = opt_list[opt].length === 4 ? opt_list[opt][3] : null;
  579. //Build usage line
  580. if (short === long) {
  581. if (short.length === 1) {
  582. line = ' -' + short;
  583. } else {
  584. line = ' --' + long;
  585. }
  586. } else if (short) {
  587. line = ' -' + short + ', --' + long;
  588. } else {
  589. line = ' --' + long;
  590. }
  591. line += ' ';
  592. if (type) {
  593. if (type instanceof Array) {
  594. desc += '. VALUE must be either [' + type.join('|') + ']';
  595. type = 'VALUE';
  596. }
  597. if (type === true || type === 1) {
  598. type = long.toUpperCase();
  599. }
  600. type = type.toUpperCase();
  601. if (type === 'FLOAT' || type === 'INT') {
  602. type = 'NUMBER';
  603. }
  604. line += optional ? '[' + type + ']' : type;
  605. }
  606. line = pad(line, switch_pad);
  607. line += trunc_desc(line, desc);
  608. line += optional ? ' (Default is ' + optional + ')' : '';
  609. console.error(line.replace('%s', '%\0s'));
  610. seen_opts.push(short);
  611. seen_opts.push(long);
  612. }
  613. if (enable.timeout && seen_opts.indexOf('t') === -1 && seen_opts.indexOf('timeout') === -1) {
  614. console.error(pad(' -t, --timeout N', switch_pad) + 'Exit if the process takes longer than N seconds');
  615. }
  616. if (enable.status) {
  617. if (seen_opts.indexOf('k') === -1 && seen_opts.indexOf('no-color') === -1) {
  618. console.error(pad(' -k, --no-color', switch_pad) + 'Omit color from output');
  619. }
  620. if (seen_opts.indexOf('debug') === -1) {
  621. console.error(pad(' --debug', switch_pad) + 'Show debug information');
  622. }
  623. }
  624. if (enable.catchall && seen_opts.indexOf('c') === -1 && seen_opts.indexOf('catch') === -1) {
  625. console.error(pad(' -c, --catch', switch_pad) + 'Catch unanticipated errors');
  626. }
  627. if (enable.daemon && seen_opts.indexOf('d') === -1 && seen_opts.indexOf('daemon') === -1) {
  628. console.error(pad(' -d, --daemon [ARG]', switch_pad) + 'Daemonize the process. Control the daemon using [start, stop, restart, log, pid]');
  629. }
  630. if (enable.version && seen_opts.indexOf('v') === -1 && seen_opts.indexOf('version') === -1) {
  631. console.error(pad(' -v, --version', switch_pad) + 'Display the current version');
  632. }
  633. if (enable.help && seen_opts.indexOf('h') === -1 && seen_opts.indexOf('help') === -1) {
  634. console.error(pad(' -h, --help', switch_pad) + 'Display help and usage details');
  635. }
  636. if (command_list.length) {
  637. console.error('\n\x1b[1mCommands\x1b[0m: ');
  638. if (!Array.isArray(commands)) {
  639. for (var c in commands) {
  640. line = ' ' + pad(c, switch_pad - 2);
  641. line += trunc_desc(line, commands[c]);
  642. console.error(line);
  643. }
  644. } else {
  645. command_list.sort();
  646. console.error(' ' + trunc_desc(' ', command_list.join(', ')));
  647. }
  648. }
  649. return cli.exit(code);
  650. };
  651. /**
  652. * Generates an error message when an opt is incorrectly used.
  653. *
  654. * @param {String} expects (e.g. 'a value')
  655. * @param {String} type (e.g. 'VALUE')
  656. * @api public
  657. */
  658. cli.getOptError = function (expects, type) {
  659. var err = full_opt + ' expects ' + expects
  660. + '. Use `' + cli.app + ' ' + full_opt + (is_long ? '=' : ' ') + type + '`';
  661. return err;
  662. };
  663. /**
  664. * Gets the next opt value and validates it with an optional validation
  665. * function. If validation fails or no value can be obtained, this method
  666. * will return the default value (if specified) or exit with err_msg.
  667. *
  668. * @param {String} default_val
  669. * @param {Function} validate_func
  670. * @param {String} err_msg
  671. * @api public
  672. */
  673. cli.getValue = function (default_val, validate_func, err_msg) {
  674. err_msg = err_msg || cli.getOptError('a value', 'VALUE');
  675. var value;
  676. try {
  677. if (curr_val) {
  678. if (validate_func) {
  679. curr_val = validate_func(curr_val);
  680. }
  681. return curr_val;
  682. }
  683. //Grouped short opts aren't allowed to have values
  684. if (short_tags.length) {
  685. throw 'Short tags';
  686. }
  687. //If there's no args left or the next arg is an opt, return the
  688. //default value (if specified) - otherwise fail
  689. if (!argv.length || (argv[0].length === 1 && argv[0][0] === '-')) {
  690. throw 'No value';
  691. }
  692. value = argv.shift();
  693. if (value.match(/^[0-9]+$/)) {
  694. value = parseInt(value, 10);
  695. }
  696. //Run the value through a validation/transformation function if specified
  697. if (validate_func) {
  698. value = validate_func(value);
  699. }
  700. } catch (e) {
  701. //The value didn't pass the validation/transformation. Unshift the value and
  702. //return the default value (if specified)
  703. if (value) {
  704. argv.unshift(value);
  705. }
  706. return default_val != null ? default_val : cli.fatal(err_msg);
  707. }
  708. return value;
  709. };
  710. cli.getInt = function (default_val) {
  711. return cli.getValue(default_val, function (value) {
  712. if (typeof value === 'number') return value;
  713. if (!value.match(/^(?:-?(?:0|[1-9][0-9]*))$/)) {
  714. throw 'Invalid int';
  715. }
  716. return parseInt(value);
  717. }, cli.getOptError('a number', 'NUMBER'));
  718. }
  719. cli.getFloat = function (default_val) {
  720. return cli.getValue(default_val, function (value) {
  721. if (!value.match(/^(?:-?(?:0|[1-9][0-9]*))?(?:\.[0-9]*)?$/)) {
  722. throw 'Invalid float';
  723. }
  724. return parseFloat(value, 10);
  725. }, cli.getOptError('a number', 'NUMBER'));
  726. }
  727. cli.getUrl = function (default_val, identifier) {
  728. identifier = identifier || 'url';
  729. return cli.getValue(default_val, function (value) {
  730. if (!value.match(/^(?:(?:ht|f)tp(?:s?)\:\/\/|~\/|\/)?(?:\w+:\w+@)?((?:(?:[-\w\d{1-3}]+\.)+(?:com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|edu|co\.uk|ac\.uk|it|fr|tv|museum|asia|local|travel|[a-z]{2})?)|((\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)(\.(\b25[0-5]\b|\b[2][0-4][0-9]\b|\b[0-1]?[0-9]?[0-9]\b)){3}))(?::[\d]{1,5})?(?:(?:(?:\/(?:[-\w~!$+|.,=]|%[a-f\d]{2})+)+|\/)+|\?|#)?(?:(?:\?(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)(?:&(?:[-\w~!$+|.,*:]|%[a-f\d{2}])+=?(?:[-\w~!$+|.,*:=]|%[a-f\d]{2})*)*)*(?:#(?:[-\w~!$ |\/.,*:;=]|%[a-f\d]{2})*)?$/i)) {
  731. throw 'Invalid URL';
  732. }
  733. return value;
  734. }, cli.getOptError('a ' + identifier, identifier.toUpperCase()));
  735. }
  736. cli.getEmail = function (default_val) {
  737. return cli.getValue(default_val, function (value) {
  738. if (!value.match(/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/)) {
  739. throw 'Invalid email';
  740. }
  741. return value;
  742. }, cli.getOptError('an email', 'EMAIL'));
  743. }
  744. cli.getIp = function (default_val) {
  745. return cli.getValue(default_val, function (value) {
  746. if (!value.match(/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/)) {
  747. throw 'Invalid IP';
  748. }
  749. return value;
  750. }, cli.getOptError('an IP', 'IP'));
  751. }
  752. cli.getPath = function (default_val, identifier) {
  753. identifier = identifier || 'path';
  754. return cli.getValue(default_val, function (value) {
  755. if (value.match(/[?*;{}]/)) {
  756. throw 'Invalid path';
  757. }
  758. return value;
  759. }, cli.getOptError('a ' + identifier, identifier.toUpperCase()));
  760. }
  761. cli.getArrayValue = function (arr, default_val) {
  762. return cli.getValue(default_val, function (value) {
  763. if (arr.indexOf(value) === -1) {
  764. throw 'Unexpected value';
  765. }
  766. return value;
  767. }, cli.getOptError('either [' + arr.join('|') + ']', 'VALUE'));
  768. }
  769. /**
  770. * Gets all data from STDIN (with optional encoding) and sends it to callback.
  771. *
  772. * @param {String} encoding (optional - default is 'utf8')
  773. * @param {Function} callback
  774. * @api public
  775. */
  776. cli.withStdin = function (encoding, callback) {
  777. if (typeof encoding === 'function') {
  778. callback = encoding;
  779. encoding = 'utf8';
  780. }
  781. var stream = process.openStdin(), data = '';
  782. stream.setEncoding(encoding);
  783. stream.on('data', function (chunk) {
  784. data += chunk;
  785. });
  786. stream.on('end', function () {
  787. callback.apply(cli, [data]);
  788. });
  789. };
  790. /**
  791. * Gets all data from STDIN, splits the data into lines and sends it
  792. * to callback (callback isn't called until all of STDIN is read. To
  793. * process each line as it's received, see the method below
  794. *
  795. * @param {Function} callback
  796. * @api public
  797. */
  798. cli.withStdinLines = function (callback) {
  799. cli.withStdin(function (data) {
  800. var sep = data.indexOf('\r\n') !== -1 ? '\r\n' : '\n';
  801. callback.apply(cli, [data.split(sep), sep]);
  802. });
  803. };
  804. /**
  805. * Asynchronously reads a file line by line. When a line is received,
  806. * callback is called with (line, sep) - when EOF is reached, callback
  807. * receives (null, null, true)
  808. *
  809. * @param {String} file (optional - default is 'stdin')
  810. * @param {String} encoding (optional - default is 'utf8')
  811. * @param {Function} callback (line, sep, eof)
  812. * @api public
  813. */
  814. cli.withInput = function (file, encoding, callback) {
  815. if (typeof encoding === 'function') {
  816. callback = encoding;
  817. encoding = 'utf8';
  818. } else if (typeof file === 'function') {
  819. callback = file;
  820. encoding = 'utf8';
  821. file = 'stdin';
  822. }
  823. if (file === 'stdin') {
  824. file = process.openStdin();
  825. } else {
  826. try {
  827. file = cli.native.fs.createReadStream(file);
  828. file.on('error', cli.fatal);
  829. } catch (e) {
  830. return cli.fatal(e);
  831. }
  832. }
  833. file.setEncoding(encoding);
  834. var lines = [], data = '', eof, sep;
  835. file.on('data', function (chunk) {
  836. if (eof) return;
  837. data += chunk;
  838. if (!sep) {
  839. if (data.indexOf('\r\n') !== -1) {
  840. sep = '\r\n';
  841. } else if (data.indexOf('\n') !== -1) {
  842. sep = '\n';
  843. } else {
  844. last_line = data;
  845. return;
  846. }
  847. }
  848. lines = data.split(sep);
  849. data = eof ? null : lines.pop();
  850. while (lines.length) {
  851. callback.apply(cli, [lines.shift(), sep, false]);
  852. }
  853. });
  854. file.on('end', function () {
  855. eof = true;
  856. if (data.length) {
  857. callback.apply(cli, [data, sep || '', false]);
  858. }
  859. callback.apply(cli, [null, null, true]);
  860. });
  861. };
  862. /**
  863. * A method for creating and controlling a daemon.
  864. *
  865. * `arg` can be:
  866. * start = daemonizes the process
  867. * stop = stops the daemon if it is running
  868. * restart = alias for stop -> start
  869. * pid = outputs the daemon's PID if it is running
  870. * log = outputs the daemon's log file (stdout + stderr)
  871. *
  872. * @param {String} arg (Optional - default is 'start')
  873. * @param {Function} callback
  874. * @api public
  875. */
  876. cli.daemon = function (arg, callback) {
  877. if (typeof daemon === 'undefined') {
  878. cli.fatal('Daemon is not initialized');
  879. }
  880. if (typeof arg === 'function') {
  881. callback = arg;
  882. arg = 'start';
  883. }
  884. var lock_file = '/tmp/' + cli.app + '.pid',
  885. log_file = '/tmp/' + cli.app + '.log';
  886. var start = function () {
  887. daemon.daemonize(log_file, lock_file, function (err) {
  888. if (err) return cli.error('Error starting daemon: ' + err);
  889. callback();
  890. });
  891. };
  892. var stop = function () {
  893. try {
  894. cli.native.fs.readFileSync(lock_file);
  895. } catch (e) {
  896. return cli.error('Daemon is not running');
  897. }
  898. daemon.kill(lock_file, function (err, pid) {
  899. if (err && err.errno === 3) {
  900. return cli.error('Daemon is not running');
  901. } else if (err) {
  902. return cli.error('Error stopping daemon: ' + err.errno);
  903. }
  904. cli.ok('Successfully stopped daemon with pid: ' + pid);
  905. });
  906. };
  907. switch(arg) {
  908. case 'stop':
  909. stop();
  910. break;
  911. case 'restart':
  912. daemon.stop(lock_file, function () {
  913. start();
  914. });
  915. break;
  916. case 'log':
  917. try {
  918. cli.native.fs.createReadStream(log_file, {encoding: 'utf8'}).pipe(process.stdout);
  919. } catch (e) {
  920. return cli.error('No daemon log file');
  921. }
  922. break;
  923. case 'pid':
  924. try {
  925. var pid = cli.native.fs.readFileSync(lock_file, 'utf8');
  926. cli.native.fs.statSync('/proc/' + pid);
  927. cli.info(pid);
  928. } catch (e) {
  929. return cli.error('Daemon is not running');
  930. }
  931. break;
  932. default:
  933. start();
  934. break;
  935. }
  936. }
  937. /**
  938. * The main entry method. Calling cli.main() is only necessary in
  939. * scripts that have daemon support enabled. `callback` receives (args, options)
  940. *
  941. * @param {Function} callback
  942. * @api public
  943. */
  944. cli.main = function (callback) {
  945. var after = function () {
  946. callback.apply(cli, [cli.args, cli.options]);
  947. };
  948. if (enable.daemon && daemon_arg) {
  949. cli.daemon(daemon_arg, after);
  950. } else {
  951. after();
  952. }
  953. }
  954. /**
  955. * Bind creationix's stack (https://github.com/creationix/stack).
  956. *
  957. * Create a simple middleware stack by calling:
  958. *
  959. * cli.createServer(middleware).listen(port);
  960. *
  961. * @return {Server} server
  962. * @api public
  963. */
  964. cli.createServer = function(/*layers*/) {
  965. var defaultStackErrorHandler = function (req, res, err) {
  966. if (err) {
  967. console.error(err.stack);
  968. res.writeHead(500, {"Content-Type": "text/plain"});
  969. return res.end(err.stack + "\n");
  970. }
  971. res.writeHead(404, {"Content-Type": "text/plain"});
  972. res.end("Not Found\n");
  973. };
  974. var handle, error;
  975. handle = error = defaultStackErrorHandler;
  976. var layers = Array.prototype.slice.call(arguments);
  977. //Allow createServer(a,b,c) and createServer([a,b,c])
  978. if (layers.length && layers[0] instanceof Array) {
  979. layers = layers[0];
  980. }
  981. layers.reverse().forEach(function (layer) {
  982. var child = handle;
  983. handle = function (req, res) {
  984. try {
  985. layer(req, res, function (err) {
  986. if (err) return error(req, res, err);
  987. child(req, res);
  988. });
  989. } catch (err) {
  990. error(req, res, err);
  991. }
  992. };
  993. });
  994. return cli.native.http.createServer(handle);
  995. };
  996. /**
  997. * A wrapper for child_process.exec().
  998. *
  999. * If the child_process exits successfully, `callback` receives an array of
  1000. * stdout lines. The current process exits if the child process has an error
  1001. * and `errback` isn't defined.
  1002. *
  1003. * @param {String} cmd
  1004. * @param {Function} callback (optional)
  1005. * @param {Function} errback (optional)
  1006. * @api public
  1007. */
  1008. cli.exec = function (cmd, callback, errback) {
  1009. cli.native.child_process.exec(cmd, function (err, stdout, stderr) {
  1010. err = err || stderr;
  1011. if (err) {
  1012. if (errback) {
  1013. return errback(err, stdout);
  1014. }
  1015. return cli.fatal('exec() failed\n' + err);
  1016. }
  1017. if (callback) {
  1018. callback(stdout.split('\n'));
  1019. }
  1020. });
  1021. };
  1022. /**
  1023. * Helper method for outputting a progress bar to the console.
  1024. *
  1025. * @param {Number} progress (0 <= progress <= 1)
  1026. * @api public
  1027. */
  1028. var last_progress_call, progress_len = 74;
  1029. cli.progress = function (progress, decimals, stream) {
  1030. stream = stream || process.stdout;
  1031. if (progress < 0 || progress > 1 || isNaN(progress)) return;
  1032. if (!decimals) decimals = 0;
  1033. var now = (new Date()).getTime();
  1034. if (last_progress_call && (now - last_progress_call) < 100 && progress !== 1) {
  1035. return; //Throttle progress calls
  1036. }
  1037. last_progress_call = now;
  1038. var barLength = Math.floor(progress_len * progress),
  1039. str = '';
  1040. if (barLength == 0 && progress > 0) {
  1041. barLength = 1;
  1042. }
  1043. for (var i = 1; i <= progress_len; i++) {
  1044. str += i <= barLength ? '#' : ' ';
  1045. }
  1046. var pwr = Math.pow(10, decimals);
  1047. var percentage = Math.floor(progress * 100 * pwr) / pwr + '%';
  1048. for (i = 0; i < decimals; i++) {
  1049. percentage += ' ';
  1050. }
  1051. stream.clearLine();
  1052. stream.write('[' + str + '] ' + percentage);
  1053. if (progress === 1) {
  1054. stream.write('\n');
  1055. } else {
  1056. stream.cursorTo(0);
  1057. }
  1058. };
  1059. /**
  1060. * Helper method for outputting a spinner to the console.
  1061. *
  1062. * @param {String|Boolean} prefix (optional)
  1063. * @api public
  1064. */
  1065. var spinnerInterval;
  1066. cli.spinner = function (prefix, end, stream) {
  1067. stream = stream || process.stdout;
  1068. if (end) {
  1069. stream.clearLine();
  1070. stream.cursorTo(0);
  1071. stream.write(prefix + '\n');
  1072. return clearInterval(spinnerInterval);
  1073. }
  1074. prefix = prefix + ' ' || '';
  1075. var spinner = ['-','\\','|','/'], i = 0, l = spinner.length;
  1076. spinnerInterval = setInterval(function () {
  1077. stream.clearLine();
  1078. stream.cursorTo(0);
  1079. stream.write(prefix + spinner[i++]);
  1080. if (i == l) i = 0;
  1081. }, 200);
  1082. };