option.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. const { InvalidArgumentError } = require('./error.js');
  2. class Option {
  3. /**
  4. * Initialize a new `Option` with the given `flags` and `description`.
  5. *
  6. * @param {string} flags
  7. * @param {string} [description]
  8. */
  9. constructor(flags, description) {
  10. this.flags = flags;
  11. this.description = description || '';
  12. this.required = flags.includes('<'); // A value must be supplied when the option is specified.
  13. this.optional = flags.includes('['); // A value is optional when the option is specified.
  14. // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument
  15. this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.
  16. this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.
  17. const optionFlags = splitOptionFlags(flags);
  18. this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).
  19. this.long = optionFlags.longFlag;
  20. this.negate = false;
  21. if (this.long) {
  22. this.negate = this.long.startsWith('--no-');
  23. }
  24. this.defaultValue = undefined;
  25. this.defaultValueDescription = undefined;
  26. this.presetArg = undefined;
  27. this.envVar = undefined;
  28. this.parseArg = undefined;
  29. this.hidden = false;
  30. this.argChoices = undefined;
  31. this.conflictsWith = [];
  32. this.implied = undefined;
  33. this.helpGroupHeading = undefined; // soft initialised when option added to command
  34. }
  35. /**
  36. * Set the default value, and optionally supply the description to be displayed in the help.
  37. *
  38. * @param {*} 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 {*} 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. * @package
  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(
  162. `Allowed choices are ${this.argChoices.join(', ')}.`,
  163. );
  164. }
  165. if (this.variadic) {
  166. return this._concatValue(arg, previous);
  167. }
  168. return arg;
  169. };
  170. return this;
  171. }
  172. /**
  173. * Return option name.
  174. *
  175. * @return {string}
  176. */
  177. name() {
  178. if (this.long) {
  179. return this.long.replace(/^--/, '');
  180. }
  181. return this.short.replace(/^-/, '');
  182. }
  183. /**
  184. * Return option name, in a camelcase format that can be used
  185. * as an object attribute key.
  186. *
  187. * @return {string}
  188. */
  189. attributeName() {
  190. if (this.negate) {
  191. return camelcase(this.name().replace(/^no-/, ''));
  192. }
  193. return camelcase(this.name());
  194. }
  195. /**
  196. * Set the help group heading.
  197. *
  198. * @param {string} heading
  199. * @return {Option}
  200. */
  201. helpGroup(heading) {
  202. this.helpGroupHeading = heading;
  203. return this;
  204. }
  205. /**
  206. * Check if `arg` matches the short or long flag.
  207. *
  208. * @param {string} arg
  209. * @return {boolean}
  210. * @package
  211. */
  212. is(arg) {
  213. return this.short === arg || this.long === arg;
  214. }
  215. /**
  216. * Return whether a boolean option.
  217. *
  218. * Options are one of boolean, negated, required argument, or optional argument.
  219. *
  220. * @return {boolean}
  221. * @package
  222. */
  223. isBoolean() {
  224. return !this.required && !this.optional && !this.negate;
  225. }
  226. }
  227. /**
  228. * This class is to make it easier to work with dual options, without changing the existing
  229. * implementation. We support separate dual options for separate positive and negative options,
  230. * like `--build` and `--no-build`, which share a single option value. This works nicely for some
  231. * use cases, but is tricky for others where we want separate behaviours despite
  232. * the single shared option value.
  233. */
  234. class DualOptions {
  235. /**
  236. * @param {Option[]} options
  237. */
  238. constructor(options) {
  239. this.positiveOptions = new Map();
  240. this.negativeOptions = new Map();
  241. this.dualOptions = new Set();
  242. options.forEach((option) => {
  243. if (option.negate) {
  244. this.negativeOptions.set(option.attributeName(), option);
  245. } else {
  246. this.positiveOptions.set(option.attributeName(), option);
  247. }
  248. });
  249. this.negativeOptions.forEach((value, key) => {
  250. if (this.positiveOptions.has(key)) {
  251. this.dualOptions.add(key);
  252. }
  253. });
  254. }
  255. /**
  256. * Did the value come from the option, and not from possible matching dual option?
  257. *
  258. * @param {*} value
  259. * @param {Option} option
  260. * @returns {boolean}
  261. */
  262. valueFromOption(value, option) {
  263. const optionKey = option.attributeName();
  264. if (!this.dualOptions.has(optionKey)) return true;
  265. // Use the value to deduce if (probably) came from the option.
  266. const preset = this.negativeOptions.get(optionKey).presetArg;
  267. const negativeValue = preset !== undefined ? preset : false;
  268. return option.negate === (negativeValue === value);
  269. }
  270. }
  271. /**
  272. * Convert string from kebab-case to camelCase.
  273. *
  274. * @param {string} str
  275. * @return {string}
  276. * @private
  277. */
  278. function camelcase(str) {
  279. return str.split('-').reduce((str, word) => {
  280. return str + word[0].toUpperCase() + word.slice(1);
  281. });
  282. }
  283. /**
  284. * Split the short and long flag out of something like '-m,--mixed <value>'
  285. *
  286. * @private
  287. */
  288. function splitOptionFlags(flags) {
  289. let shortFlag;
  290. let longFlag;
  291. // short flag, single dash and single character
  292. const shortFlagExp = /^-[^-]$/;
  293. // long flag, double dash and at least one character
  294. const longFlagExp = /^--[^-]/;
  295. const flagParts = flags.split(/[ |,]+/).concat('guard');
  296. // Normal is short and/or long.
  297. if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
  298. if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
  299. // Long then short. Rarely used but fine.
  300. if (!shortFlag && shortFlagExp.test(flagParts[0]))
  301. shortFlag = flagParts.shift();
  302. // Allow two long flags, like '--ws, --workspace'
  303. // This is the supported way to have a shortish option flag.
  304. if (!shortFlag && longFlagExp.test(flagParts[0])) {
  305. shortFlag = longFlag;
  306. longFlag = flagParts.shift();
  307. }
  308. // Check for unprocessed flag. Fail noisily rather than silently ignore.
  309. if (flagParts[0].startsWith('-')) {
  310. const unsupportedFlag = flagParts[0];
  311. const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
  312. if (/^-[^-][^-]/.test(unsupportedFlag))
  313. throw new Error(
  314. `${baseError}
  315. - a short flag is a single dash and a single character
  316. - either use a single dash and a single character (for a short flag)
  317. - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,
  318. );
  319. if (shortFlagExp.test(unsupportedFlag))
  320. throw new Error(`${baseError}
  321. - too many short flags`);
  322. if (longFlagExp.test(unsupportedFlag))
  323. throw new Error(`${baseError}
  324. - too many long flags`);
  325. throw new Error(`${baseError}
  326. - unrecognised flag format`);
  327. }
  328. if (shortFlag === undefined && longFlag === undefined)
  329. throw new Error(
  330. `option creation failed due to no flags found in '${flags}'.`,
  331. );
  332. return { shortFlag, longFlag };
  333. }
  334. exports.Option = Option;
  335. exports.DualOptions = DualOptions;