option.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. const { InvalidArgumentError } = require('./error.js');
  2. // @ts-check
  3. class Option {
  4. /**
  5. * Initialize a new `Option` with the given `flags` and `description`.
  6. *
  7. * @param {string} flags
  8. * @param {string} [description]
  9. */
  10. constructor(flags, description) {
  11. this.flags = flags;
  12. this.description = description || '';
  13. this.required = flags.includes('<'); // A value must be supplied when the option is specified.
  14. this.optional = flags.includes('['); // A value is optional when the option is specified.
  15. // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
  16. this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
  17. this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
  18. const optionFlags = splitOptionFlags(flags);
  19. this.short = optionFlags.shortFlag;
  20. this.long = optionFlags.longFlag;
  21. this.negate = false;
  22. if (this.long) {
  23. this.negate = this.long.startsWith('--no-');
  24. }
  25. this.defaultValue = undefined;
  26. this.defaultValueDescription = undefined;
  27. this.presetArg = undefined;
  28. this.envVar = undefined;
  29. this.parseArg = undefined;
  30. this.hidden = false;
  31. this.argChoices = undefined;
  32. this.conflictsWith = [];
  33. this.implied = undefined;
  34. }
  35. /**
  36. * Set the default value, and optionally supply the description to be displayed in the help.
  37. *
  38. * @param {any} value
  39. * @param {string} [description]
  40. * @return {Option}
  41. */
  42. default(value, description) {
  43. this.defaultValue = value;
  44. this.defaultValueDescription = description;
  45. return this;
  46. }
  47. /**
  48. * Preset to use when option used without option-argument, especially optional but also boolean and negated.
  49. * The custom processing (parseArg) is called.
  50. *
  51. * @example
  52. * new Option('--color').default('GREYSCALE').preset('RGB');
  53. * new Option('--donate [amount]').preset('20').argParser(parseFloat);
  54. *
  55. * @param {any} arg
  56. * @return {Option}
  57. */
  58. preset(arg) {
  59. this.presetArg = arg;
  60. return this;
  61. }
  62. /**
  63. * Add option name(s) that conflict with this option.
  64. * An error will be displayed if conflicting options are found during parsing.
  65. *
  66. * @example
  67. * new Option('--rgb').conflicts('cmyk');
  68. * new Option('--js').conflicts(['ts', 'jsx']);
  69. *
  70. * @param {string | string[]} names
  71. * @return {Option}
  72. */
  73. conflicts(names) {
  74. this.conflictsWith = this.conflictsWith.concat(names);
  75. return this;
  76. }
  77. /**
  78. * Specify implied option values for when this option is set and the implied options are not.
  79. *
  80. * The custom processing (parseArg) is not called on the implied values.
  81. *
  82. * @example
  83. * program
  84. * .addOption(new Option('--log', 'write logging information to file'))
  85. * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
  86. *
  87. * @param {Object} impliedOptionValues
  88. * @return {Option}
  89. */
  90. implies(impliedOptionValues) {
  91. let newImplied = impliedOptionValues;
  92. if (typeof impliedOptionValues === 'string') {
  93. // string is not documented, but easy mistake and we can do what user probably intended.
  94. newImplied = { [impliedOptionValues]: true };
  95. }
  96. this.implied = Object.assign(this.implied || {}, newImplied);
  97. return this;
  98. }
  99. /**
  100. * Set environment variable to check for option value.
  101. *
  102. * An environment variable is only used if when processed the current option value is
  103. * undefined, or the source of the current value is 'default' or 'config' or 'env'.
  104. *
  105. * @param {string} name
  106. * @return {Option}
  107. */
  108. env(name) {
  109. this.envVar = name;
  110. return this;
  111. }
  112. /**
  113. * Set the custom handler for processing CLI option arguments into option values.
  114. *
  115. * @param {Function} [fn]
  116. * @return {Option}
  117. */
  118. argParser(fn) {
  119. this.parseArg = fn;
  120. return this;
  121. }
  122. /**
  123. * Whether the option is mandatory and must have a value after parsing.
  124. *
  125. * @param {boolean} [mandatory=true]
  126. * @return {Option}
  127. */
  128. makeOptionMandatory(mandatory = true) {
  129. this.mandatory = !!mandatory;
  130. return this;
  131. }
  132. /**
  133. * Hide option in help.
  134. *
  135. * @param {boolean} [hide=true]
  136. * @return {Option}
  137. */
  138. hideHelp(hide = true) {
  139. this.hidden = !!hide;
  140. return this;
  141. }
  142. /**
  143. * @api private
  144. */
  145. _concatValue(value, previous) {
  146. if (previous === this.defaultValue || !Array.isArray(previous)) {
  147. return [value];
  148. }
  149. return previous.concat(value);
  150. }
  151. /**
  152. * Only allow option value to be one of choices.
  153. *
  154. * @param {string[]} values
  155. * @return {Option}
  156. */
  157. choices(values) {
  158. this.argChoices = values.slice();
  159. this.parseArg = (arg, previous) => {
  160. if (!this.argChoices.includes(arg)) {
  161. throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`);
  162. }
  163. if (this.variadic) {
  164. return this._concatValue(arg, previous);
  165. }
  166. return arg;
  167. };
  168. return this;
  169. }
  170. /**
  171. * Return option name.
  172. *
  173. * @return {string}
  174. */
  175. name() {
  176. if (this.long) {
  177. return this.long.replace(/^--/, '');
  178. }
  179. return this.short.replace(/^-/, '');
  180. }
  181. /**
  182. * Return option name, in a camelcase format that can be used
  183. * as a object attribute key.
  184. *
  185. * @return {string}
  186. * @api private
  187. */
  188. attributeName() {
  189. return camelcase(this.name().replace(/^no-/, ''));
  190. }
  191. /**
  192. * Check if `arg` matches the short or long flag.
  193. *
  194. * @param {string} arg
  195. * @return {boolean}
  196. * @api private
  197. */
  198. is(arg) {
  199. return this.short === arg || this.long === arg;
  200. }
  201. /**
  202. * Return whether a boolean option.
  203. *
  204. * Options are one of boolean, negated, required argument, or optional argument.
  205. *
  206. * @return {boolean}
  207. * @api private
  208. */
  209. isBoolean() {
  210. return !this.required && !this.optional && !this.negate;
  211. }
  212. }
  213. /**
  214. * This class is to make it easier to work with dual options, without changing the existing
  215. * implementation. We support separate dual options for separate positive and negative options,
  216. * like `--build` and `--no-build`, which share a single option value. This works nicely for some
  217. * use cases, but is tricky for others where we want separate behaviours despite
  218. * the single shared option value.
  219. */
  220. class DualOptions {
  221. /**
  222. * @param {Option[]} options
  223. */
  224. constructor(options) {
  225. this.positiveOptions = new Map();
  226. this.negativeOptions = new Map();
  227. this.dualOptions = new Set();
  228. options.forEach(option => {
  229. if (option.negate) {
  230. this.negativeOptions.set(option.attributeName(), option);
  231. } else {
  232. this.positiveOptions.set(option.attributeName(), option);
  233. }
  234. });
  235. this.negativeOptions.forEach((value, key) => {
  236. if (this.positiveOptions.has(key)) {
  237. this.dualOptions.add(key);
  238. }
  239. });
  240. }
  241. /**
  242. * Did the value come from the option, and not from possible matching dual option?
  243. *
  244. * @param {any} value
  245. * @param {Option} option
  246. * @returns {boolean}
  247. */
  248. valueFromOption(value, option) {
  249. const optionKey = option.attributeName();
  250. if (!this.dualOptions.has(optionKey)) return true;
  251. // Use the value to deduce if (probably) came from the option.
  252. const preset = this.negativeOptions.get(optionKey).presetArg;
  253. const negativeValue = (preset !== undefined) ? preset : false;
  254. return option.negate === (negativeValue === value);
  255. }
  256. }
  257. /**
  258. * Convert string from kebab-case to camelCase.
  259. *
  260. * @param {string} str
  261. * @return {string}
  262. * @api private
  263. */
  264. function camelcase(str) {
  265. return str.split('-').reduce((str, word) => {
  266. return str + word[0].toUpperCase() + word.slice(1);
  267. });
  268. }
  269. /**
  270. * Split the short and long flag out of something like '-m,--mixed <value>'
  271. *
  272. * @api private
  273. */
  274. function splitOptionFlags(flags) {
  275. let shortFlag;
  276. let longFlag;
  277. // Use original very loose parsing to maintain backwards compatibility for now,
  278. // which allowed for example unintended `-sw, --short-word` [sic].
  279. const flagParts = flags.split(/[ |,]+/);
  280. if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
  281. longFlag = flagParts.shift();
  282. // Add support for lone short flag without significantly changing parsing!
  283. if (!shortFlag && /^-[^-]$/.test(longFlag)) {
  284. shortFlag = longFlag;
  285. longFlag = undefined;
  286. }
  287. return { shortFlag, longFlag };
  288. }
  289. exports.Option = Option;
  290. exports.splitOptionFlags = splitOptionFlags;
  291. exports.DualOptions = DualOptions;