option.js 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. this.implied = Object.assign(this.implied || {}, impliedOptionValues);
  92. return this;
  93. }
  94. /**
  95. * Set environment variable to check for option value.
  96. * Priority order of option values is default < env < cli
  97. *
  98. * @param {string} name
  99. * @return {Option}
  100. */
  101. env(name) {
  102. this.envVar = name;
  103. return this;
  104. }
  105. /**
  106. * Set the custom handler for processing CLI option arguments into option values.
  107. *
  108. * @param {Function} [fn]
  109. * @return {Option}
  110. */
  111. argParser(fn) {
  112. this.parseArg = fn;
  113. return this;
  114. }
  115. /**
  116. * Whether the option is mandatory and must have a value after parsing.
  117. *
  118. * @param {boolean} [mandatory=true]
  119. * @return {Option}
  120. */
  121. makeOptionMandatory(mandatory = true) {
  122. this.mandatory = !!mandatory;
  123. return this;
  124. }
  125. /**
  126. * Hide option in help.
  127. *
  128. * @param {boolean} [hide=true]
  129. * @return {Option}
  130. */
  131. hideHelp(hide = true) {
  132. this.hidden = !!hide;
  133. return this;
  134. }
  135. /**
  136. * @api private
  137. */
  138. _concatValue(value, previous) {
  139. if (previous === this.defaultValue || !Array.isArray(previous)) {
  140. return [value];
  141. }
  142. return previous.concat(value);
  143. }
  144. /**
  145. * Only allow option value to be one of choices.
  146. *
  147. * @param {string[]} values
  148. * @return {Option}
  149. */
  150. choices(values) {
  151. this.argChoices = values.slice();
  152. this.parseArg = (arg, previous) => {
  153. if (!this.argChoices.includes(arg)) {
  154. throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`);
  155. }
  156. if (this.variadic) {
  157. return this._concatValue(arg, previous);
  158. }
  159. return arg;
  160. };
  161. return this;
  162. }
  163. /**
  164. * Return option name.
  165. *
  166. * @return {string}
  167. */
  168. name() {
  169. if (this.long) {
  170. return this.long.replace(/^--/, '');
  171. }
  172. return this.short.replace(/^-/, '');
  173. }
  174. /**
  175. * Return option name, in a camelcase format that can be used
  176. * as a object attribute key.
  177. *
  178. * @return {string}
  179. * @api private
  180. */
  181. attributeName() {
  182. return camelcase(this.name().replace(/^no-/, ''));
  183. }
  184. /**
  185. * Check if `arg` matches the short or long flag.
  186. *
  187. * @param {string} arg
  188. * @return {boolean}
  189. * @api private
  190. */
  191. is(arg) {
  192. return this.short === arg || this.long === arg;
  193. }
  194. /**
  195. * Return whether a boolean option.
  196. *
  197. * Options are one of boolean, negated, required argument, or optional argument.
  198. *
  199. * @return {boolean}
  200. * @api private
  201. */
  202. isBoolean() {
  203. return !this.required && !this.optional && !this.negate;
  204. }
  205. }
  206. /**
  207. * This class is to make it easier to work with dual options, without changing the existing
  208. * implementation. We support separate dual options for separate positive and negative options,
  209. * like `--build` and `--no-build`, which share a single option value. This works nicely for some
  210. * use cases, but is tricky for others where we want separate behaviours despite
  211. * the single shared option value.
  212. */
  213. class DualOptions {
  214. /**
  215. * @param {Option[]} options
  216. */
  217. constructor(options) {
  218. this.positiveOptions = new Map();
  219. this.negativeOptions = new Map();
  220. this.dualOptions = new Set();
  221. options.forEach(option => {
  222. if (option.negate) {
  223. this.negativeOptions.set(option.attributeName(), option);
  224. } else {
  225. this.positiveOptions.set(option.attributeName(), option);
  226. }
  227. });
  228. this.negativeOptions.forEach((value, key) => {
  229. if (this.positiveOptions.has(key)) {
  230. this.dualOptions.add(key);
  231. }
  232. });
  233. }
  234. /**
  235. * Did the value come from the option, and not from possible matching dual option?
  236. *
  237. * @param {any} value
  238. * @param {Option} option
  239. * @returns {boolean}
  240. */
  241. valueFromOption(value, option) {
  242. const optionKey = option.attributeName();
  243. if (!this.dualOptions.has(optionKey)) return true;
  244. // Use the value to deduce if (probably) came from the option.
  245. const preset = this.negativeOptions.get(optionKey).presetArg;
  246. const negativeValue = (preset !== undefined) ? preset : false;
  247. return option.negate === (negativeValue === value);
  248. }
  249. }
  250. /**
  251. * Convert string from kebab-case to camelCase.
  252. *
  253. * @param {string} str
  254. * @return {string}
  255. * @api private
  256. */
  257. function camelcase(str) {
  258. return str.split('-').reduce((str, word) => {
  259. return str + word[0].toUpperCase() + word.slice(1);
  260. });
  261. }
  262. /**
  263. * Split the short and long flag out of something like '-m,--mixed <value>'
  264. *
  265. * @api private
  266. */
  267. function splitOptionFlags(flags) {
  268. let shortFlag;
  269. let longFlag;
  270. // Use original very loose parsing to maintain backwards compatibility for now,
  271. // which allowed for example unintended `-sw, --short-word` [sic].
  272. const flagParts = flags.split(/[ |,]+/);
  273. if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();
  274. longFlag = flagParts.shift();
  275. // Add support for lone short flag without significantly changing parsing!
  276. if (!shortFlag && /^-[^-]$/.test(longFlag)) {
  277. shortFlag = longFlag;
  278. longFlag = undefined;
  279. }
  280. return { shortFlag, longFlag };
  281. }
  282. exports.Option = Option;
  283. exports.splitOptionFlags = splitOptionFlags;
  284. exports.DualOptions = DualOptions;