Skip to content
Myr

option.js

This file

Path

lib/option.js

331 lines · 8.4 KiB · JavaScript

Last changed by

Assume a string parameter to implies is name of boolean option. (#1854)John Geebefore adoptionf4c7349

History of this file

Take it

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 1–30why, one step back
1const { InvalidArgumentError } = require('./error.js');
23// @ts-check45class Option {6 /**7 * Initialize a new `Option` with the given `flags` and `description`.8 *9 * @param {string} flags10 * @param {string} [description]11 */1213 constructor(flags, description) {14 this.flags = flags;15 this.description = description || '';1617 this.required = flags.includes('<'); // A value must be supplied when the option is specified.18 this.optional = flags.includes('['); // A value is optional when the option is specified.19 // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument20 this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.21 this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.22 const optionFlags = splitOptionFlags(flags);23 this.short = optionFlags.shortFlag;24 this.long = optionFlags.longFlag;25 this.negate = false;26 if (this.long) {27 this.negate = this.long.startsWith('--no-');28 }29 this.defaultValue = undefined;30 this.defaultValueDescription = undefined;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 31why, one step back
31 this.presetArg = undefined;

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

line 32why, one step back
32 this.envVar = undefined;

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 33–35why, one step back
33 this.parseArg = undefined;
34 this.hidden = false;35 this.argChoices = undefined;

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

line 36why, one step back
36 this.conflictsWith = [];

Add Option.implies() (#1724)John Geebefore adoptiond660967

line 37why, one step back
37 this.implied = undefined;

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 38–50why, one step back
38 }
3940 /**41 * Set the default value, and optionally supply the description to be displayed in the help.42 *43 * @param {any} value44 * @param {string} [description]45 * @return {Option}46 */4748 default(value, description) {49 this.defaultValue = value;50 this.defaultValueDescription = description;

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

line 51why, one step back
51 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 52why, one step back
52 }

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 53–54why, one step back
53
54 /**

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 55–67why, one step back
55 * Preset to use when option used without option-argument, especially optional but also boolean and negated.
56 * The custom processing (parseArg) is called.57 *58 * @example59 * new Option('--color').default('GREYSCALE').preset('RGB');60 * new Option('--donate [amount]').preset('20').argParser(parseFloat);61 *62 * @param {any} arg63 * @return {Option}64 */6566 preset(arg) {67 this.presetArg = arg;

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 68–71why, one step back
68 return this;
69 }7071 /**

Add extended conflicts example (#1700)John Geebefore adoption1d27078

lines 72–77why, one step back
72 * Add option name(s) that conflict with this option.
73 * An error will be displayed if conflicting options are found during parsing.74 *75 * @example76 * new Option('--rgb').conflicts('cmyk');77 * new Option('--js').conflicts(['ts', 'jsx']);

feat(option): allow to set options as conflicting (#1678)Erez Rokahbefore adoptionfc4fd41

lines 78–84why, one step back
78 *
79 * @param {string | string[]} names80 * @return {Option}81 */8283 conflicts(names) {84 this.conflictsWith = this.conflictsWith.concat(names);

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 85–88why, one step back
85 return this;
86 }8788 /**

Add Option.implies() (#1724)John Geebefore adoptiond660967

lines 89–101why, one step back
89 * Specify implied option values for when this option is set and the implied options are not.
90 *91 * The custom processing (parseArg) is not called on the implied values.92 *93 * @example94 * program95 * .addOption(new Option('--log', 'write logging information to file'))96 * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));97 *98 * @param {Object} impliedOptionValues99 * @return {Option}100 */101 implies(impliedOptionValues) {

Assume a string parameter to implies is name of boolean option. (#1854)John Geebefore adoptionf4c7349

lines 102–107why, one step back
102 let newImplied = impliedOptionValues;
103 if (typeof impliedOptionValues === 'string') {104 // string is not documented, but easy mistake and we can do what user probably intended.105 newImplied = { [impliedOptionValues]: true };106 }107 this.implied = Object.assign(this.implied || {}, newImplied);

Add Option.implies() (#1724)John Geebefore adoptiond660967

lines 108–111why, one step back
108 return this;
109 }110111 /**

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

line 112why, one step back
112 * Set environment variable to check for option value.

Add implied to option value sources (#1794)John Geebefore adoption72be61c

lines 113–115why, one step back
113 *
114 * An environment variable is only used if when processed the current option value is115 * undefined, or the source of the current value is 'default' or 'config' or 'env'.

Add .env method to Option for consulting environment variable for option value (#1587)John Geebefore adoption8571a75

lines 116–122why, one step back
116 *
117 * @param {string} name118 * @return {Option}119 */120121 env(name) {122 this.envVar = name;

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 123why, one step back
123 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 124why, one step back
124 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 125–135why, one step back
125
126 /**127 * Set the custom handler for processing CLI option arguments into option values.128 *129 * @param {Function} [fn]130 * @return {Option}131 */132133 argParser(fn) {134 this.parseArg = fn;135 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 136why, one step back
136 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 137–147why, one step back
137
138 /**139 * Whether the option is mandatory and must have a value after parsing.140 *141 * @param {boolean} [mandatory=true]142 * @return {Option}143 */144145 makeOptionMandatory(mandatory = true) {146 this.mandatory = !!mandatory;147 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 148why, one step back
148 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 149–159why, one step back
149
150 /**151 * Hide option in help.152 *153 * @param {boolean} [hide=true]154 * @return {Option}155 */156157 hideHelp(hide = true) {158 this.hidden = !!hide;159 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 160why, one step back
160 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 161–181why, one step back
161
162 /**163 * @api private164 */165166 _concatValue(value, previous) {167 if (previous === this.defaultValue || !Array.isArray(previous)) {168 return [value];169 }170171 return previous.concat(value);172 }173174 /**175 * Only allow option value to be one of choices.176 *177 * @param {string[]} values178 * @return {Option}179 */180181 choices(values) {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 182why, one step back
182 this.argChoices = values.slice();

Refactor classes into files (#1522)John Geebefore adoption08245cc

line 183why, one step back
183 this.parseArg = (arg, previous) => {

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 184–185why, one step back
184 if (!this.argChoices.includes(arg)) {
185 throw new InvalidArgumentError(`Allowed choices are ${this.argChoices.join(', ')}.`);

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 186–192why, one step back
186 }
187 if (this.variadic) {188 return this._concatValue(arg, previous);189 }190 return arg;191 };192 return this;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 193why, one step back
193 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 194–205why, one step back
194
195 /**196 * Return option name.197 *198 * @return {string}199 */200201 name() {202 if (this.long) {203 return this.long.replace(/^--/, '');204 }205 return this.short.replace(/^-/, '');

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 206why, one step back
206 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 207–217why, one step back
207
208 /**209 * Return option name, in a camelcase format that can be used210 * as a object attribute key.211 *212 * @return {string}213 * @api private214 */215216 attributeName() {217 return camelcase(this.name().replace(/^no-/, ''));

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

line 218why, one step back
218 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 219–229why, one step back
219
220 /**221 * Check if `arg` matches the short or long flag.222 *223 * @param {string} arg224 * @return {boolean}225 * @api private226 */227228 is(arg) {229 return this.short === arg || this.long === arg;

Merge pull request #1683 from tj/release/9.xJohn Geebefore adoption02a124c

lines 230–243why, one step back
230 }
231232 /**233 * Return whether a boolean option.234 *235 * Options are one of boolean, negated, required argument, or optional argument.236 *237 * @return {boolean}238 * @api private239 */240241 isBoolean() {242 return !this.required && !this.optional && !this.negate;243 }

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 244–246why, one step back
244}
245246/**

Add Option.implies() (#1724)John Geebefore adoptiond660967

lines 247–293why, one step back
247 * This class is to make it easier to work with dual options, without changing the existing
248 * implementation. We support separate dual options for separate positive and negative options,249 * like `--build` and `--no-build`, which share a single option value. This works nicely for some250 * use cases, but is tricky for others where we want separate behaviours despite251 * the single shared option value.252 */253class DualOptions {254 /**255 * @param {Option[]} options256 */257 constructor(options) {258 this.positiveOptions = new Map();259 this.negativeOptions = new Map();260 this.dualOptions = new Set();261 options.forEach(option => {262 if (option.negate) {263 this.negativeOptions.set(option.attributeName(), option);264 } else {265 this.positiveOptions.set(option.attributeName(), option);266 }267 });268 this.negativeOptions.forEach((value, key) => {269 if (this.positiveOptions.has(key)) {270 this.dualOptions.add(key);271 }272 });273 }274275 /**276 * Did the value come from the option, and not from possible matching dual option?277 *278 * @param {any} value279 * @param {Option} option280 * @returns {boolean}281 */282 valueFromOption(value, option) {283 const optionKey = option.attributeName();284 if (!this.dualOptions.has(optionKey)) return true;285286 // Use the value to deduce if (probably) came from the option.287 const preset = this.negativeOptions.get(optionKey).presetArg;288 const negativeValue = (preset !== undefined) ? preset : false;289 return option.negate === (negativeValue === value);290 }291}292293/**

Refactor classes into files (#1522)John Geebefore adoption08245cc

lines 294–330why, one step back
294 * Convert string from kebab-case to camelCase.
295 *296 * @param {string} str297 * @return {string}298 * @api private299 */300301function camelcase(str) {302 return str.split('-').reduce((str, word) => {303 return str + word[0].toUpperCase() + word.slice(1);304 });305}306307/**308 * Split the short and long flag out of something like '-m,--mixed <value>'309 *310 * @api private311 */312313function splitOptionFlags(flags) {314 let shortFlag;315 let longFlag;316 // Use original very loose parsing to maintain backwards compatibility for now,317 // which allowed for example unintended `-sw, --short-word` [sic].318 const flagParts = flags.split(/[ |,]+/);319 if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift();320 longFlag = flagParts.shift();321 // Add support for lone short flag without significantly changing parsing!322 if (!shortFlag && /^-[^-]$/.test(longFlag)) {323 shortFlag = longFlag;324 longFlag = undefined;325 }326 return { shortFlag, longFlag };327}328329exports.Option = Option;330exports.splitOptionFlags = splitOptionFlags;

Add Option.implies() (#1724)John Geebefore adoptiond660967

line 331why, one step back
331exports.DualOptions = DualOptions;