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

1055 lines
34 KiB

  1. /**
  2. * dashdash - A light, featureful and explicit option parsing library for
  3. * node.js.
  4. */
  5. // vim: set ts=4 sts=4 sw=4 et:
  6. var assert = require('assert-plus');
  7. var format = require('util').format;
  8. var fs = require('fs');
  9. var path = require('path');
  10. var DEBUG = true;
  11. if (DEBUG) {
  12. var debug = console.warn;
  13. } else {
  14. var debug = function () {};
  15. }
  16. // ---- internal support stuff
  17. // Replace {{variable}} in `s` with the template data in `d`.
  18. function renderTemplate(s, d) {
  19. return s.replace(/{{([a-zA-Z]+)}}/g, function (match, key) {
  20. return d.hasOwnProperty(key) ? d[key] : match;
  21. });
  22. }
  23. /**
  24. * Return a shallow copy of the given object;
  25. */
  26. function shallowCopy(obj) {
  27. if (!obj) {
  28. return (obj);
  29. }
  30. var copy = {};
  31. Object.keys(obj).forEach(function (k) {
  32. copy[k] = obj[k];
  33. });
  34. return (copy);
  35. }
  36. function space(n) {
  37. var s = '';
  38. for (var i = 0; i < n; i++) {
  39. s += ' ';
  40. }
  41. return s;
  42. }
  43. function makeIndent(arg, deflen, name) {
  44. if (arg === null || arg === undefined)
  45. return space(deflen);
  46. else if (typeof (arg) === 'number')
  47. return space(arg);
  48. else if (typeof (arg) === 'string')
  49. return arg;
  50. else
  51. assert.fail('invalid "' + name + '": not a string or number: ' + arg);
  52. }
  53. /**
  54. * Return an array of lines wrapping the given text to the given width.
  55. * This splits on whitespace. Single tokens longer than `width` are not
  56. * broken up.
  57. */
  58. function textwrap(s, width) {
  59. var words = s.trim().split(/\s+/);
  60. var lines = [];
  61. var line = '';
  62. words.forEach(function (w) {
  63. var newLength = line.length + w.length;
  64. if (line.length > 0)
  65. newLength += 1;
  66. if (newLength > width) {
  67. lines.push(line);
  68. line = '';
  69. }
  70. if (line.length > 0)
  71. line += ' ';
  72. line += w;
  73. });
  74. lines.push(line);
  75. return lines;
  76. }
  77. /**
  78. * Transform an option name to a "key" that is used as the field
  79. * on the `opts` object returned from `<parser>.parse()`.
  80. *
  81. * Transformations:
  82. * - '-' -> '_': This allow one to use hyphen in option names (common)
  83. * but not have to do silly things like `opt["dry-run"]` to access the
  84. * parsed results.
  85. */
  86. function optionKeyFromName(name) {
  87. return name.replace(/-/g, '_');
  88. }
  89. // ---- Option types
  90. function parseBool(option, optstr, arg) {
  91. return Boolean(arg);
  92. }
  93. function parseString(option, optstr, arg) {
  94. assert.string(arg, 'arg');
  95. return arg;
  96. }
  97. function parseNumber(option, optstr, arg) {
  98. assert.string(arg, 'arg');
  99. var num = Number(arg);
  100. if (isNaN(num)) {
  101. throw new Error(format('arg for "%s" is not a number: "%s"',
  102. optstr, arg));
  103. }
  104. return num;
  105. }
  106. function parseInteger(option, optstr, arg) {
  107. assert.string(arg, 'arg');
  108. var num = Number(arg);
  109. if (!/^[0-9-]+$/.test(arg) || isNaN(num)) {
  110. throw new Error(format('arg for "%s" is not an integer: "%s"',
  111. optstr, arg));
  112. }
  113. return num;
  114. }
  115. function parsePositiveInteger(option, optstr, arg) {
  116. assert.string(arg, 'arg');
  117. var num = Number(arg);
  118. if (!/^[0-9]+$/.test(arg) || isNaN(num) || num === 0) {
  119. throw new Error(format('arg for "%s" is not a positive integer: "%s"',
  120. optstr, arg));
  121. }
  122. return num;
  123. }
  124. /**
  125. * Supported date args:
  126. * - epoch second times (e.g. 1396031701)
  127. * - ISO 8601 format: YYYY-MM-DD[THH:MM:SS[.sss][Z]]
  128. * 2014-03-28T18:35:01.489Z
  129. * 2014-03-28T18:35:01.489
  130. * 2014-03-28T18:35:01Z
  131. * 2014-03-28T18:35:01
  132. * 2014-03-28
  133. */
  134. function parseDate(option, optstr, arg) {
  135. assert.string(arg, 'arg');
  136. var date;
  137. if (/^\d+$/.test(arg)) {
  138. // epoch seconds
  139. date = new Date(Number(arg) * 1000);
  140. /* JSSTYLED */
  141. } else if (/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?Z?)?$/i.test(arg)) {
  142. // ISO 8601 format
  143. date = new Date(arg);
  144. } else {
  145. throw new Error(format('arg for "%s" is not a valid date format: "%s"',
  146. optstr, arg));
  147. }
  148. if (date.toString() === 'Invalid Date') {
  149. throw new Error(format('arg for "%s" is an invalid date: "%s"',
  150. optstr, arg));
  151. }
  152. return date;
  153. }
  154. var optionTypes = {
  155. bool: {
  156. takesArg: false,
  157. parseArg: parseBool
  158. },
  159. string: {
  160. takesArg: true,
  161. helpArg: 'ARG',
  162. parseArg: parseString
  163. },
  164. number: {
  165. takesArg: true,
  166. helpArg: 'NUM',
  167. parseArg: parseNumber
  168. },
  169. integer: {
  170. takesArg: true,
  171. helpArg: 'INT',
  172. parseArg: parseInteger
  173. },
  174. positiveInteger: {
  175. takesArg: true,
  176. helpArg: 'INT',
  177. parseArg: parsePositiveInteger
  178. },
  179. date: {
  180. takesArg: true,
  181. helpArg: 'DATE',
  182. parseArg: parseDate
  183. },
  184. arrayOfBool: {
  185. takesArg: false,
  186. array: true,
  187. parseArg: parseBool
  188. },
  189. arrayOfString: {
  190. takesArg: true,
  191. helpArg: 'ARG',
  192. array: true,
  193. parseArg: parseString
  194. },
  195. arrayOfNumber: {
  196. takesArg: true,
  197. helpArg: 'NUM',
  198. array: true,
  199. parseArg: parseNumber
  200. },
  201. arrayOfInteger: {
  202. takesArg: true,
  203. helpArg: 'INT',
  204. array: true,
  205. parseArg: parseInteger
  206. },
  207. arrayOfPositiveInteger: {
  208. takesArg: true,
  209. helpArg: 'INT',
  210. array: true,
  211. parseArg: parsePositiveInteger
  212. },
  213. arrayOfDate: {
  214. takesArg: true,
  215. helpArg: 'INT',
  216. array: true,
  217. parseArg: parseDate
  218. },
  219. };
  220. // ---- Parser
  221. /**
  222. * Parser constructor.
  223. *
  224. * @param config {Object} The parser configuration
  225. * - options {Array} Array of option specs. See the README for how to
  226. * specify each option spec.
  227. * - allowUnknown {Boolean} Default false. Whether to throw on unknown
  228. * options. If false, then unknown args are included in the _args array.
  229. * - interspersed {Boolean} Default true. Whether to allow interspersed
  230. * arguments (non-options) and options. E.g.:
  231. * node tool.js arg1 arg2 -v
  232. * '-v' is after some args here. If `interspersed: false` then '-v'
  233. * would not be parsed out. Note that regardless of `interspersed`
  234. * the presence of '--' will stop option parsing, as all good
  235. * option parsers should.
  236. */
  237. function Parser(config) {
  238. assert.object(config, 'config');
  239. assert.arrayOfObject(config.options, 'config.options');
  240. assert.optionalBool(config.interspersed, 'config.interspersed');
  241. var self = this;
  242. // Allow interspersed arguments (true by default).
  243. this.interspersed = (config.interspersed !== undefined
  244. ? config.interspersed : true);
  245. // Don't allow unknown flags (true by default).
  246. this.allowUnknown = (config.allowUnknown !== undefined
  247. ? config.allowUnknown : false);
  248. this.options = config.options.map(function (o) { return shallowCopy(o); });
  249. this.optionFromName = {};
  250. this.optionFromEnv = {};
  251. for (var i = 0; i < this.options.length; i++) {
  252. var o = this.options[i];
  253. if (o.group !== undefined && o.group !== null) {
  254. assert.optionalString(o.group,
  255. format('config.options.%d.group', i));
  256. continue;
  257. }
  258. assert.ok(optionTypes[o.type],
  259. format('invalid config.options.%d.type: "%s" in %j',
  260. i, o.type, o));
  261. assert.optionalString(o.name, format('config.options.%d.name', i));
  262. assert.optionalArrayOfString(o.names,
  263. format('config.options.%d.names', i));
  264. assert.ok((o.name || o.names) && !(o.name && o.names),
  265. format('exactly one of "name" or "names" required: %j', o));
  266. assert.optionalString(o.help, format('config.options.%d.help', i));
  267. var env = o.env || [];
  268. if (typeof (env) === 'string') {
  269. env = [env];
  270. }
  271. assert.optionalArrayOfString(env, format('config.options.%d.env', i));
  272. assert.optionalString(o.helpGroup,
  273. format('config.options.%d.helpGroup', i));
  274. assert.optionalBool(o.helpWrap,
  275. format('config.options.%d.helpWrap', i));
  276. assert.optionalBool(o.hidden, format('config.options.%d.hidden', i));
  277. if (o.name) {
  278. o.names = [o.name];
  279. } else {
  280. assert.string(o.names[0],
  281. format('config.options.%d.names is empty', i));
  282. }
  283. o.key = optionKeyFromName(o.names[0]);
  284. o.names.forEach(function (n) {
  285. if (self.optionFromName[n]) {
  286. throw new Error(format(
  287. 'option name collision: "%s" used in %j and %j',
  288. n, self.optionFromName[n], o));
  289. }
  290. self.optionFromName[n] = o;
  291. });
  292. env.forEach(function (n) {
  293. if (self.optionFromEnv[n]) {
  294. throw new Error(format(
  295. 'option env collision: "%s" used in %j and %j',
  296. n, self.optionFromEnv[n], o));
  297. }
  298. self.optionFromEnv[n] = o;
  299. });
  300. }
  301. }
  302. Parser.prototype.optionTakesArg = function optionTakesArg(option) {
  303. return optionTypes[option.type].takesArg;
  304. };
  305. /**
  306. * Parse options from the given argv.
  307. *
  308. * @param inputs {Object} Optional.
  309. * - argv {Array} Optional. The argv to parse. Defaults to
  310. * `process.argv`.
  311. * - slice {Number} The index into argv at which options/args begin.
  312. * Default is 2, as appropriate for `process.argv`.
  313. * - env {Object} Optional. The env to use for 'env' entries in the
  314. * option specs. Defaults to `process.env`.
  315. * @returns {Object} Parsed `opts`. It has special keys `_args` (the
  316. * remaining args from `argv`) and `_order` (gives the order that
  317. * options were specified).
  318. */
  319. Parser.prototype.parse = function parse(inputs) {
  320. var self = this;
  321. // Old API was `parse([argv, [slice]])`
  322. if (Array.isArray(arguments[0])) {
  323. inputs = {argv: arguments[0], slice: arguments[1]};
  324. }
  325. assert.optionalObject(inputs, 'inputs');
  326. if (!inputs) {
  327. inputs = {};
  328. }
  329. assert.optionalArrayOfString(inputs.argv, 'inputs.argv');
  330. //assert.optionalNumber(slice, 'slice');
  331. var argv = inputs.argv || process.argv;
  332. var slice = inputs.slice !== undefined ? inputs.slice : 2;
  333. var args = argv.slice(slice);
  334. var env = inputs.env || process.env;
  335. var opts = {};
  336. var _order = [];
  337. function addOpt(option, optstr, key, val, from) {
  338. var type = optionTypes[option.type];
  339. var parsedVal = type.parseArg(option, optstr, val);
  340. if (type.array) {
  341. if (!opts[key]) {
  342. opts[key] = [];
  343. }
  344. if (type.arrayFlatten && Array.isArray(parsedVal)) {
  345. for (var i = 0; i < parsedVal.length; i++) {
  346. opts[key].push(parsedVal[i]);
  347. }
  348. } else {
  349. opts[key].push(parsedVal);
  350. }
  351. } else {
  352. opts[key] = parsedVal;
  353. }
  354. var item = { key: key, value: parsedVal, from: from };
  355. _order.push(item);
  356. }
  357. // Parse args.
  358. var _args = [];
  359. var i = 0;
  360. outer: while (i < args.length) {
  361. var arg = args[i];
  362. // End of options marker.
  363. if (arg === '--') {
  364. i++;
  365. break;
  366. // Long option
  367. } else if (arg.slice(0, 2) === '--') {
  368. var name = arg.slice(2);
  369. var val = null;
  370. var idx = name.indexOf('=');
  371. if (idx !== -1) {
  372. val = name.slice(idx + 1);
  373. name = name.slice(0, idx);
  374. }
  375. var option = this.optionFromName[name];
  376. if (!option) {
  377. if (!this.allowUnknown)
  378. throw new Error(format('unknown option: "--%s"', name));
  379. else if (this.interspersed)
  380. _args.push(arg);
  381. else
  382. break outer;
  383. } else {
  384. var takesArg = this.optionTakesArg(option);
  385. if (val !== null && !takesArg) {
  386. throw new Error(format('argument given to "--%s" option '
  387. + 'that does not take one: "%s"', name, arg));
  388. }
  389. if (!takesArg) {
  390. addOpt(option, '--'+name, option.key, true, 'argv');
  391. } else if (val !== null) {
  392. addOpt(option, '--'+name, option.key, val, 'argv');
  393. } else if (i + 1 >= args.length) {
  394. throw new Error(format('do not have enough args for "--%s" '
  395. + 'option', name));
  396. } else {
  397. addOpt(option, '--'+name, option.key, args[i + 1], 'argv');
  398. i++;
  399. }
  400. }
  401. // Short option
  402. } else if (arg[0] === '-' && arg.length > 1) {
  403. var j = 1;
  404. var allFound = true;
  405. while (j < arg.length) {
  406. var name = arg[j];
  407. var option = this.optionFromName[name];
  408. if (!option) {
  409. allFound = false;
  410. if (this.allowUnknown) {
  411. if (this.interspersed) {
  412. _args.push(arg);
  413. break;
  414. } else
  415. break outer;
  416. } else if (arg.length > 2) {
  417. throw new Error(format(
  418. 'unknown option: "-%s" in "%s" group',
  419. name, arg));
  420. } else {
  421. throw new Error(format('unknown option: "-%s"', name));
  422. }
  423. } else if (this.optionTakesArg(option)) {
  424. break;
  425. }
  426. j++;
  427. }
  428. j = 1;
  429. while (allFound && j < arg.length) {
  430. var name = arg[j];
  431. var val = arg.slice(j + 1); // option val if it takes an arg
  432. var option = this.optionFromName[name];
  433. var takesArg = this.optionTakesArg(option);
  434. if (!takesArg) {
  435. addOpt(option, '-'+name, option.key, true, 'argv');
  436. } else if (val) {
  437. addOpt(option, '-'+name, option.key, val, 'argv');
  438. break;
  439. } else {
  440. if (i + 1 >= args.length) {
  441. throw new Error(format('do not have enough args '
  442. + 'for "-%s" option', name));
  443. }
  444. addOpt(option, '-'+name, option.key, args[i + 1], 'argv');
  445. i++;
  446. break;
  447. }
  448. j++;
  449. }
  450. // An interspersed arg
  451. } else if (this.interspersed) {
  452. _args.push(arg);
  453. // An arg and interspersed args are not allowed, so done options.
  454. } else {
  455. break outer;
  456. }
  457. i++;
  458. }
  459. _args = _args.concat(args.slice(i));
  460. // Parse environment.
  461. Object.keys(this.optionFromEnv).forEach(function (envname) {
  462. var val = env[envname];
  463. if (val === undefined)
  464. return;
  465. var option = self.optionFromEnv[envname];
  466. if (opts[option.key] !== undefined)
  467. return;
  468. var takesArg = self.optionTakesArg(option);
  469. if (takesArg) {
  470. addOpt(option, envname, option.key, val, 'env');
  471. } else if (val !== '') {
  472. // Boolean envvar handling:
  473. // - VAR=<empty-string> not set (as if the VAR was not set)
  474. // - VAR=0 false
  475. // - anything else true
  476. addOpt(option, envname, option.key, (val !== '0'), 'env');
  477. }
  478. });
  479. // Apply default values.
  480. this.options.forEach(function (o) {
  481. if (opts[o.key] === undefined) {
  482. if (o.default !== undefined) {
  483. opts[o.key] = o.default;
  484. } else if (o.type && optionTypes[o.type].default !== undefined) {
  485. opts[o.key] = optionTypes[o.type].default;
  486. }
  487. }
  488. });
  489. opts._order = _order;
  490. opts._args = _args;
  491. return opts;
  492. };
  493. /**
  494. * Return help output for the current options.
  495. *
  496. * E.g.: if the current options are:
  497. * [{names: ['help', 'h'], type: 'bool', help: 'Show help and exit.'}]
  498. * then this would return:
  499. * ' -h, --help Show help and exit.\n'
  500. *
  501. * @param config {Object} Config for controlling the option help output.
  502. * - indent {Number|String} Default 4. An indent/prefix to use for
  503. * each option line.
  504. * - nameSort {String} Default is 'length'. By default the names are
  505. * sorted to put the short opts first (i.e. '-h, --help' preferred
  506. * to '--help, -h'). Set to 'none' to not do this sorting.
  507. * - maxCol {Number} Default 80. Note that long tokens in a help string
  508. * can go past this.
  509. * - helpCol {Number} Set to specify a specific column at which
  510. * option help will be aligned. By default this is determined
  511. * automatically.
  512. * - minHelpCol {Number} Default 20.
  513. * - maxHelpCol {Number} Default 40.
  514. * - includeEnv {Boolean} Default false. If true, a note stating the `env`
  515. * envvar (if specified for this option) will be appended to the help
  516. * output.
  517. * - includeDefault {Boolean} Default false. If true, a note stating
  518. * the `default` for this option, if any, will be appended to the help
  519. * output.
  520. * - helpWrap {Boolean} Default true. Wrap help text in helpCol..maxCol
  521. * bounds.
  522. * @returns {String}
  523. */
  524. Parser.prototype.help = function help(config) {
  525. config = config || {};
  526. assert.object(config, 'config');
  527. var indent = makeIndent(config.indent, 4, 'config.indent');
  528. var headingIndent = makeIndent(config.headingIndent,
  529. Math.round(indent.length / 2), 'config.headingIndent');
  530. assert.optionalString(config.nameSort, 'config.nameSort');
  531. var nameSort = config.nameSort || 'length';
  532. assert.ok(~['length', 'none'].indexOf(nameSort),
  533. 'invalid "config.nameSort"');
  534. assert.optionalNumber(config.maxCol, 'config.maxCol');
  535. assert.optionalNumber(config.maxHelpCol, 'config.maxHelpCol');
  536. assert.optionalNumber(config.minHelpCol, 'config.minHelpCol');
  537. assert.optionalNumber(config.helpCol, 'config.helpCol');
  538. assert.optionalBool(config.includeEnv, 'config.includeEnv');
  539. assert.optionalBool(config.includeDefault, 'config.includeDefault');
  540. assert.optionalBool(config.helpWrap, 'config.helpWrap');
  541. var maxCol = config.maxCol || 80;
  542. var minHelpCol = config.minHelpCol || 20;
  543. var maxHelpCol = config.maxHelpCol || 40;
  544. var lines = [];
  545. var maxWidth = 0;
  546. this.options.forEach(function (o) {
  547. if (o.hidden) {
  548. return;
  549. }
  550. if (o.group !== undefined && o.group !== null) {
  551. // We deal with groups in the next pass
  552. lines.push(null);
  553. return;
  554. }
  555. var type = optionTypes[o.type];
  556. var arg = o.helpArg || type.helpArg || 'ARG';
  557. var line = '';
  558. var names = o.names.slice();
  559. if (nameSort === 'length') {
  560. names.sort(function (a, b) {
  561. if (a.length < b.length)
  562. return -1;
  563. else if (b.length < a.length)
  564. return 1;
  565. else
  566. return 0;
  567. })
  568. }
  569. names.forEach(function (name, i) {
  570. if (i > 0)
  571. line += ', ';
  572. if (name.length === 1) {
  573. line += '-' + name
  574. if (type.takesArg)
  575. line += ' ' + arg;
  576. } else {
  577. line += '--' + name
  578. if (type.takesArg)
  579. line += '=' + arg;
  580. }
  581. });
  582. maxWidth = Math.max(maxWidth, line.length);
  583. lines.push(line);
  584. });
  585. // Add help strings.
  586. var helpCol = config.helpCol;
  587. if (!helpCol) {
  588. helpCol = maxWidth + indent.length + 2;
  589. helpCol = Math.min(Math.max(helpCol, minHelpCol), maxHelpCol);
  590. }
  591. var i = -1;
  592. this.options.forEach(function (o) {
  593. if (o.hidden) {
  594. return;
  595. }
  596. i++;
  597. if (o.group !== undefined && o.group !== null) {
  598. if (o.group === '') {
  599. // Support a empty string "group" to have a blank line between
  600. // sets of options.
  601. lines[i] = '';
  602. } else {
  603. // Render the group heading with the heading-specific indent.
  604. lines[i] = (i === 0 ? '' : '\n') + headingIndent +
  605. o.group + ':';
  606. }
  607. return;
  608. }
  609. var helpDefault;
  610. if (config.includeDefault) {
  611. if (o.default !== undefined) {
  612. helpDefault = format('Default: %j', o.default);
  613. } else if (o.type && optionTypes[o.type].default !== undefined) {
  614. helpDefault = format('Default: %j',
  615. optionTypes[o.type].default);
  616. }
  617. }
  618. var line = lines[i] = indent + lines[i];
  619. if (!o.help && !(config.includeEnv && o.env) && !helpDefault) {
  620. return;
  621. }
  622. var n = helpCol - line.length;
  623. if (n >= 0) {
  624. line += space(n);
  625. } else {
  626. line += '\n' + space(helpCol);
  627. }
  628. var helpEnv = '';
  629. if (o.env && o.env.length && config.includeEnv) {
  630. helpEnv += 'Environment: ';
  631. var type = optionTypes[o.type];
  632. var arg = o.helpArg || type.helpArg || 'ARG';
  633. var envs = (Array.isArray(o.env) ? o.env : [o.env]).map(
  634. function (e) {
  635. if (type.takesArg) {
  636. return e + '=' + arg;
  637. } else {
  638. return e + '=1';
  639. }
  640. }
  641. );
  642. helpEnv += envs.join(', ');
  643. }
  644. var help = (o.help || '').trim();
  645. if (o.helpWrap !== false && config.helpWrap !== false) {
  646. // Wrap help description normally.
  647. if (help.length && !~'.!?"\''.indexOf(help.slice(-1))) {
  648. help += '.';
  649. }
  650. if (help.length) {
  651. help += ' ';
  652. }
  653. help += helpEnv;
  654. if (helpDefault) {
  655. if (helpEnv) {
  656. help += '. ';
  657. }
  658. help += helpDefault;
  659. }
  660. line += textwrap(help, maxCol - helpCol).join(
  661. '\n' + space(helpCol));
  662. } else {
  663. // Do not wrap help description, but indent newlines appropriately.
  664. var helpLines = help.split('\n').filter(
  665. function (ln) { return ln.length });
  666. if (helpEnv !== '') {
  667. helpLines.push(helpEnv);
  668. }
  669. if (helpDefault) {
  670. helpLines.push(helpDefault);
  671. }
  672. line += helpLines.join('\n' + space(helpCol));
  673. }
  674. lines[i] = line;
  675. });
  676. var rv = '';
  677. if (lines.length > 0) {
  678. rv = lines.join('\n') + '\n';
  679. }
  680. return rv;
  681. };
  682. /**
  683. * Return a string suitable for a Bash completion file for this tool.
  684. *
  685. * @param args.name {String} The tool name.
  686. * @param args.specExtra {String} Optional. Extra Bash code content to add
  687. * to the end of the "spec". Typically this is used to append Bash
  688. * "complete_TYPE" functions for custom option types. See
  689. * "examples/ddcompletion.js" for an example.
  690. * @param args.argtypes {Array} Optional. Array of completion types for
  691. * positional args (i.e. non-options). E.g.
  692. * argtypes = ['fruit', 'veggie', 'file']
  693. * will result in completion of fruits for the first arg, veggies for the
  694. * second, and filenames for the third and subsequent positional args.
  695. * If not given, positional args will use Bash's 'default' completion.
  696. * See `specExtra` for providing Bash `complete_TYPE` functions, e.g.
  697. * `complete_fruit` and `complete_veggie` in this example.
  698. */
  699. Parser.prototype.bashCompletion = function bashCompletion(args) {
  700. assert.object(args, 'args');
  701. assert.string(args.name, 'args.name');
  702. assert.optionalString(args.specExtra, 'args.specExtra');
  703. assert.optionalArrayOfString(args.argtypes, 'args.argtypes');
  704. return bashCompletionFromOptions({
  705. name: args.name,
  706. specExtra: args.specExtra,
  707. argtypes: args.argtypes,
  708. options: this.options
  709. });
  710. };
  711. // ---- Bash completion
  712. const BASH_COMPLETION_TEMPLATE_PATH = path.join(
  713. __dirname, '../etc/dashdash.bash_completion.in');
  714. /**
  715. * Return the Bash completion "spec" (the string value for the "{{spec}}"
  716. * var in the "dashdash.bash_completion.in" template) for this tool.
  717. *
  718. * The "spec" is Bash code that defines the CLI options and subcmds for
  719. * the template's completion code. It looks something like this:
  720. *
  721. * local cmd_shortopts="-J ..."
  722. * local cmd_longopts="--help ..."
  723. * local cmd_optargs="-p=tritonprofile ..."
  724. *
  725. * @param args.options {Array} The array of dashdash option specs.
  726. * @param args.context {String} Optional. A context string for the "local cmd*"
  727. * vars in the spec. By default it is the empty string. When used to
  728. * scope for completion on a *sub-command* (e.g. for "git log" on a "git"
  729. * tool), then it would have a value (e.g. "__log"). See
  730. * <http://github.com/trentm/node-cmdln> Bash completion for details.
  731. * @param opts.includeHidden {Boolean} Optional. Default false. By default
  732. * hidden options and subcmds are "excluded". Here excluded means they
  733. * won't be offered as a completion, but if used, their argument type
  734. * will be completed. "Hidden" options and subcmds are ones with the
  735. * `hidden: true` attribute to exclude them from default help output.
  736. * @param args.argtypes {Array} Optional. Array of completion types for
  737. * positional args (i.e. non-options). E.g.
  738. * argtypes = ['fruit', 'veggie', 'file']
  739. * will result in completion of fruits for the first arg, veggies for the
  740. * second, and filenames for the third and subsequent positional args.
  741. * If not given, positional args will use Bash's 'default' completion.
  742. * See `specExtra` for providing Bash `complete_TYPE` functions, e.g.
  743. * `complete_fruit` and `complete_veggie` in this example.
  744. */
  745. function bashCompletionSpecFromOptions(args) {
  746. assert.object(args, 'args');
  747. assert.object(args.options, 'args.options');
  748. assert.optionalString(args.context, 'args.context');
  749. assert.optionalBool(args.includeHidden, 'args.includeHidden');
  750. assert.optionalArrayOfString(args.argtypes, 'args.argtypes');
  751. var context = args.context || '';
  752. var includeHidden = (args.includeHidden === undefined
  753. ? false : args.includeHidden);
  754. var spec = [];
  755. var shortopts = [];
  756. var longopts = [];
  757. var optargs = [];
  758. (args.options || []).forEach(function (o) {
  759. if (o.group !== undefined && o.group !== null) {
  760. // Skip group headers.
  761. return;
  762. }
  763. var optNames = o.names || [o.name];
  764. var optType = getOptionType(o.type);
  765. if (optType.takesArg) {
  766. var completionType = o.completionType ||
  767. optType.completionType || o.type;
  768. optNames.forEach(function (optName) {
  769. if (optName.length === 1) {
  770. if (includeHidden || !o.hidden) {
  771. shortopts.push('-' + optName);
  772. }
  773. // Include even hidden options in `optargs` so that bash
  774. // completion of its arg still works.
  775. optargs.push('-' + optName + '=' + completionType);
  776. } else {
  777. if (includeHidden || !o.hidden) {
  778. longopts.push('--' + optName);
  779. }
  780. optargs.push('--' + optName + '=' + completionType);
  781. }
  782. });
  783. } else {
  784. optNames.forEach(function (optName) {
  785. if (includeHidden || !o.hidden) {
  786. if (optName.length === 1) {
  787. shortopts.push('-' + optName);
  788. } else {
  789. longopts.push('--' + optName);
  790. }
  791. }
  792. });
  793. }
  794. });
  795. spec.push(format('local cmd%s_shortopts="%s"',
  796. context, shortopts.sort().join(' ')));
  797. spec.push(format('local cmd%s_longopts="%s"',
  798. context, longopts.sort().join(' ')));
  799. spec.push(format('local cmd%s_optargs="%s"',
  800. context, optargs.sort().join(' ')));
  801. if (args.argtypes) {
  802. spec.push(format('local cmd%s_argtypes="%s"',
  803. context, args.argtypes.join(' ')));
  804. }
  805. return spec.join('\n');
  806. }
  807. /**
  808. * Return a string suitable for a Bash completion file for this tool.
  809. *
  810. * @param args.name {String} The tool name.
  811. * @param args.options {Array} The array of dashdash option specs.
  812. * @param args.specExtra {String} Optional. Extra Bash code content to add
  813. * to the end of the "spec". Typically this is used to append Bash
  814. * "complete_TYPE" functions for custom option types. See
  815. * "examples/ddcompletion.js" for an example.
  816. * @param args.argtypes {Array} Optional. Array of completion types for
  817. * positional args (i.e. non-options). E.g.
  818. * argtypes = ['fruit', 'veggie', 'file']
  819. * will result in completion of fruits for the first arg, veggies for the
  820. * second, and filenames for the third and subsequent positional args.
  821. * If not given, positional args will use Bash's 'default' completion.
  822. * See `specExtra` for providing Bash `complete_TYPE` functions, e.g.
  823. * `complete_fruit` and `complete_veggie` in this example.
  824. */
  825. function bashCompletionFromOptions(args) {
  826. assert.object(args, 'args');
  827. assert.object(args.options, 'args.options');
  828. assert.string(args.name, 'args.name');
  829. assert.optionalString(args.specExtra, 'args.specExtra');
  830. assert.optionalArrayOfString(args.argtypes, 'args.argtypes');
  831. // Gather template data.
  832. var data = {
  833. name: args.name,
  834. date: new Date(),
  835. spec: bashCompletionSpecFromOptions({
  836. options: args.options,
  837. argtypes: args.argtypes
  838. }),
  839. };
  840. if (args.specExtra) {
  841. data.spec += '\n\n' + args.specExtra;
  842. }
  843. // Render template.
  844. var template = fs.readFileSync(BASH_COMPLETION_TEMPLATE_PATH, 'utf8');
  845. return renderTemplate(template, data);
  846. }
  847. // ---- exports
  848. function createParser(config) {
  849. return new Parser(config);
  850. }
  851. /**
  852. * Parse argv with the given options.
  853. *
  854. * @param config {Object} A merge of all the available fields from
  855. * `dashdash.Parser` and `dashdash.Parser.parse`: options, interspersed,
  856. * argv, env, slice.
  857. */
  858. function parse(config) {
  859. assert.object(config, 'config');
  860. assert.optionalArrayOfString(config.argv, 'config.argv');
  861. assert.optionalObject(config.env, 'config.env');
  862. var config = shallowCopy(config);
  863. var argv = config.argv;
  864. delete config.argv;
  865. var env = config.env;
  866. delete config.env;
  867. var parser = new Parser(config);
  868. return parser.parse({argv: argv, env: env});
  869. }
  870. /**
  871. * Add a new option type.
  872. *
  873. * @params optionType {Object}:
  874. * - name {String} Required.
  875. * - takesArg {Boolean} Required. Whether this type of option takes an
  876. * argument on process.argv. Typically this is true for all but the
  877. * "bool" type.
  878. * - helpArg {String} Required iff `takesArg === true`. The string to
  879. * show in generated help for options of this type.
  880. * - parseArg {Function} Require. `function (option, optstr, arg)` parser
  881. * that takes a string argument and returns an instance of the
  882. * appropriate type, or throws an error if the arg is invalid.
  883. * - array {Boolean} Optional. Set to true if this is an 'arrayOf' type
  884. * that collects multiple usages of the option in process.argv and
  885. * puts results in an array.
  886. * - arrayFlatten {Boolean} Optional. XXX
  887. * - default Optional. Default value for options of this type, if no
  888. * default is specified in the option type usage.
  889. */
  890. function addOptionType(optionType) {
  891. assert.object(optionType, 'optionType');
  892. assert.string(optionType.name, 'optionType.name');
  893. assert.bool(optionType.takesArg, 'optionType.takesArg');
  894. if (optionType.takesArg) {
  895. assert.string(optionType.helpArg, 'optionType.helpArg');
  896. }
  897. assert.func(optionType.parseArg, 'optionType.parseArg');
  898. assert.optionalBool(optionType.array, 'optionType.array');
  899. assert.optionalBool(optionType.arrayFlatten, 'optionType.arrayFlatten');
  900. optionTypes[optionType.name] = {
  901. takesArg: optionType.takesArg,
  902. helpArg: optionType.helpArg,
  903. parseArg: optionType.parseArg,
  904. array: optionType.array,
  905. arrayFlatten: optionType.arrayFlatten,
  906. default: optionType.default
  907. }
  908. }
  909. function getOptionType(name) {
  910. assert.string(name, 'name');
  911. return optionTypes[name];
  912. }
  913. /**
  914. * Return a synopsis string for the given option spec.
  915. *
  916. * Examples:
  917. * > synopsisFromOpt({names: ['help', 'h'], type: 'bool'});
  918. * '[ --help | -h ]'
  919. * > synopsisFromOpt({name: 'file', type: 'string', helpArg: 'FILE'});
  920. * '[ --file=FILE ]'
  921. */
  922. function synopsisFromOpt(o) {
  923. assert.object(o, 'o');
  924. if (o.hasOwnProperty('group')) {
  925. return null;
  926. }
  927. var names = o.names || [o.name];
  928. // `type` here could be undefined if, for example, the command has a
  929. // dashdash option spec with a bogus 'type'.
  930. var type = getOptionType(o.type);
  931. var helpArg = o.helpArg || (type && type.helpArg) || 'ARG';
  932. var parts = [];
  933. names.forEach(function (name) {
  934. var part = (name.length === 1 ? '-' : '--') + name;
  935. if (type && type.takesArg) {
  936. part += (name.length === 1 ? ' ' + helpArg : '=' + helpArg);
  937. }
  938. parts.push(part);
  939. });
  940. return ('[ ' + parts.join(' | ') + ' ]');
  941. };
  942. module.exports = {
  943. createParser: createParser,
  944. Parser: Parser,
  945. parse: parse,
  946. addOptionType: addOptionType,
  947. getOptionType: getOptionType,
  948. synopsisFromOpt: synopsisFromOpt,
  949. // Bash completion-related exports
  950. BASH_COMPLETION_TEMPLATE_PATH: BASH_COMPLETION_TEMPLATE_PATH,
  951. bashCompletionFromOptions: bashCompletionFromOptions,
  952. bashCompletionSpecFromOptions: bashCompletionSpecFromOptions,
  953. // Export the parseFoo parsers because they might be useful as primitives
  954. // for custom option types.
  955. parseBool: parseBool,
  956. parseString: parseString,
  957. parseNumber: parseNumber,
  958. parseInteger: parseInteger,
  959. parsePositiveInteger: parsePositiveInteger,
  960. parseDate: parseDate
  961. };