Skip to content
Myr

option.js

This file

Path

lib/option.js

377 lines · 10.0 KiB · JavaScript

Last changed by

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

History of this file

Take it

The walk stopped after 200 commits: lines older than 471ec40 point at it.

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 1why, one step back
1import { InvalidArgumentError } from './error.js';

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

line 2why, one step back
2

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 3why, one step back
3export class Option {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 4–20why, one step back
4 /**
5 * Initialize a new `Option` with the given `flags` and `description`.6 *7 * @param {string} flags8 * @param {string} [description]9 */1011 constructor(flags, description) {12 this.flags = flags;13 this.description = description || '';1415 this.required = flags.includes('<'); // A value must be supplied when the option is specified.16 this.optional = flags.includes('['); // A value is optional when the option is specified.17 // variadic test ignores <value,...> et al which might be used to describe custom splitting of single argument18 this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values.19 this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line.20 const optionFlags = splitOptionFlags(flags);

Add support for dual long options when no short option (#2312)John Geebefore adoption8263b7f

line 21why, one step back
21 this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 22–35why, one step back
22 this.long = optionFlags.longFlag;
23 this.negate = false;24 if (this.long) {25 this.negate = this.long.startsWith('--no-');26 }27 this.defaultValue = undefined;28 this.defaultValueDescription = undefined;29 this.presetArg = undefined;30 this.envVar = undefined;31 this.parseArg = undefined;32 this.hidden = false;33 this.argChoices = undefined;34 this.conflictsWith = [];35 this.implied = undefined;

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

line 36why, one step back
36 this.helpGroupHeading = undefined; // soft initialised when option added to command

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 37–41why, one step back
37 }
3839 /**40 * Set the default value, and optionally supply the description to be displayed in the help.41 *

Replace {any} with {*} as native JSDoc (#2015)John Geebefore adoption26a34e6

line 42why, one step back
42 * @param {*} value

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 43–60why, one step back
43 * @param {string} [description]
44 * @return {Option}45 */4647 default(value, description) {48 this.defaultValue = value;49 this.defaultValueDescription = description;50 return this;51 }5253 /**54 * Preset to use when option used without option-argument, especially optional but also boolean and negated.55 * The custom processing (parseArg) is called.56 *57 * @example58 * new Option('--color').default('GREYSCALE').preset('RGB');59 * new Option('--donate [amount]').preset('20').argParser(parseFloat);60 *

Replace {any} with {*} as native JSDoc (#2015)John Geebefore adoption26a34e6

line 61why, one step back
61 * @param {*} arg

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 62–77why, one step back
62 * @return {Option}
63 */6465 preset(arg) {66 this.presetArg = arg;67 return this;68 }6970 /**71 * Add option name(s) that conflict with this option.72 * An error will be displayed if conflicting options are found during parsing.73 *74 * @example75 * new Option('--rgb').conflicts('cmyk');76 * new Option('--js').conflicts(['ts', 'jsx']);77 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 78why, one step back
78 * @param {(string | string[])} names

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 79–96why, one step back
79 * @return {Option}
80 */8182 conflicts(names) {83 this.conflictsWith = this.conflictsWith.concat(names);84 return this;85 }8687 /**88 * Specify implied option values for when this option is set and the implied options are not.89 *90 * The custom processing (parseArg) is not called on the implied values.91 *92 * @example93 * program94 * .addOption(new Option('--log', 'write logging information to file'))95 * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));96 *

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 97why, one step back
97 * @param {object} impliedOptionValues

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 98–100why, one step back
98 * @return {Option}
99 */100 implies(impliedOptionValues) {

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

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

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 107–161why, one step back
107 return this;
108 }109110 /**111 * Set environment variable to check for option value.112 *113 * An environment variable is only used if when processed the current option value is114 * undefined, or the source of the current value is 'default' or 'config' or 'env'.115 *116 * @param {string} name117 * @return {Option}118 */119120 env(name) {121 this.envVar = name;122 return this;123 }124125 /**126 * Set the custom handler for processing CLI option arguments into option values.127 *128 * @param {Function} [fn]129 * @return {Option}130 */131132 argParser(fn) {133 this.parseArg = fn;134 return this;135 }136137 /**138 * Whether the option is mandatory and must have a value after parsing.139 *140 * @param {boolean} [mandatory=true]141 * @return {Option}142 */143144 makeOptionMandatory(mandatory = true) {145 this.mandatory = !!mandatory;146 return this;147 }148149 /**150 * Hide option in help.151 *152 * @param {boolean} [hide=true]153 * @return {Option}154 */155156 hideHelp(hide = true) {157 this.hidden = !!hide;158 return this;159 }160161 /**

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 162why, one step back
162 * @package

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 163–164why, one step back
163 */
164

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 165why, one step back
165 _collectValue(value, previous) {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 166–169why, one step back
166 if (previous === this.defaultValue || !Array.isArray(previous)) {
167 return [value];168 }169

Merge from develop (#2482)John Geebefore adoptionb51c0ea

lines 170–171why, one step back
170 previous.push(value);
171 return previous;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 172–184why, one step back
172 }
173174 /**175 * Only allow option value to be one of choices.176 *177 * @param {string[]} values178 * @return {Option}179 */180181 choices(values) {182 this.argChoices = values.slice();183 this.parseArg = (arg, previous) => {184 if (!this.argChoices.includes(arg)) {

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

lines 185–187why, one step back
185 throw new InvalidArgumentError(
186 `Allowed choices are ${this.argChoices.join(', ')}.`,187 );

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 188–189why, one step back
188 }
189 if (this.variadic) {

Merge from develop (#2482)John Geebefore adoptionb51c0ea

line 190why, one step back
190 return this._collectValue(arg, previous);

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 191–211why, one step back
191 }
192 return arg;193 };194 return this;195 }196197 /**198 * Return option name.199 *200 * @return {string}201 */202203 name() {204 if (this.long) {205 return this.long.replace(/^--/, '');206 }207 return this.short.replace(/^-/, '');208 }209210 /**211 * Return option name, in a camelcase format that can be used

Merge branch 'develop' into release/13.xJohn Geebefore adoption5a79585

line 212why, one step back
212 * as an object attribute key.

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 213–217why, one step back
213 *
214 * @return {string}215 */216217 attributeName() {

Merge branch 'develop' into release/13.xJohn Geebefore adoption5a79585

lines 218–221why, one step back
218 if (this.negate) {
219 return camelcase(this.name().replace(/^no-/, ''));220 }221 return camelcase(this.name());

Add support for groups of options and commands in the help (#2328)John Geebefore adoptionc324ea3

lines 222–232why, one step back
222 }
223224 /**225 * Set the help group heading.226 *227 * @param {string} heading228 * @return {Option}229 */230 helpGroup(heading) {231 this.helpGroupHeading = heading;232 return this;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 233–239why, one step back
233 }
234235 /**236 * Check if `arg` matches the short or long flag.237 *238 * @param {string} arg239 * @return {boolean}

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 240why, one step back
240 * @package

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 241–252why, one step back
241 */
242243 is(arg) {244 return this.short === arg || this.long === arg;245 }246247 /**248 * Return whether a boolean option.249 *250 * Options are one of boolean, negated, required argument, or optional argument.251 *252 * @return {boolean}

Fix some JSDoc lint issues (#2181)John Geebefore adoptionb95ea44

line 253why, one step back
253 * @package

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 254–267why, one step back
254 */
255256 isBoolean() {257 return !this.required && !this.optional && !this.negate;258 }259}260261/**262 * This class is to make it easier to work with dual options, without changing the existing263 * implementation. We support separate dual options for separate positive and negative options,264 * like `--build` and `--no-build`, which share a single option value. This works nicely for some265 * use cases, but is tricky for others where we want separate behaviours despite266 * the single shared option value.267 */

Switching to esm-only (#2464)John Geebefore adoptionf4bd470

line 268why, one step back
268export class DualOptions {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 269–275why, one step back
269 /**
270 * @param {Option[]} options271 */272 constructor(options) {273 this.positiveOptions = new Map();274 this.negativeOptions = new Map();275 this.dualOptions = new Set();

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 276why, one step back
276 options.forEach((option) => {

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 277–292why, one step back
277 if (option.negate) {
278 this.negativeOptions.set(option.attributeName(), option);279 } else {280 this.positiveOptions.set(option.attributeName(), option);281 }282 });283 this.negativeOptions.forEach((value, key) => {284 if (this.positiveOptions.has(key)) {285 this.dualOptions.add(key);286 }287 });288 }289290 /**291 * Did the value come from the option, and not from possible matching dual option?292 *

Replace {any} with {*} as native JSDoc (#2015)John Geebefore adoption26a34e6

line 293why, one step back
293 * @param {*} value

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 294–302why, one step back
294 * @param {Option} option
295 * @returns {boolean}296 */297 valueFromOption(value, option) {298 const optionKey = option.attributeName();299 if (!this.dualOptions.has(optionKey)) return true;300301 // Use the value to deduce if (probably) came from the option.302 const preset = this.negativeOptions.get(optionKey).presetArg;

Reformat code with Prettier (#2180)John Geebefore adoption1bdc749

line 303why, one step back
303 const negativeValue = preset !== undefined ? preset : false;

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 304–312why, one step back
304 return option.negate === (negativeValue === value);
305 }306}307308/**309 * Convert string from kebab-case to camelCase.310 *311 * @param {string} str312 * @return {string}

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 313why, one step back
313 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 314–324why, one step back
314 */
315316function camelcase(str) {317 return str.split('-').reduce((str, word) => {318 return str + word[0].toUpperCase() + word.slice(1);319 });320}321322/**323 * Split the short and long flag out of something like '-m,--mixed <value>'324 *

Merge pull request #2140 from tj/release/12.xJohn Geebefore adoptione3192a1

line 325why, one step back
325 * @private

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 326–330why, one step back
326 */
327328function splitOptionFlags(flags) {329 let shortFlag;330 let longFlag;

Throw for unsupported option flag setup (#2270)John Geebefore adoption966720a

lines 331–336why, one step back
331 // short flag, single dash and single character
332 const shortFlagExp = /^-[^-]$/;333 // long flag, double dash and at least one character334 const longFlagExp = /^--[^-]/;335336 const flagParts = flags.split(/[ |,]+/).concat('guard');

Add support for dual long options when no short option (#2312)John Geebefore adoption8263b7f

line 337why, one step back
337 // Normal is short and/or long.

Throw for unsupported option flag setup (#2270)John Geebefore adoption966720a

lines 338–339why, one step back
338 if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
339 if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();

Add support for dual long options when no short option (#2312)John Geebefore adoption8263b7f

lines 340–348why, one step back
340 // Long then short. Rarely used but fine.
341 if (!shortFlag && shortFlagExp.test(flagParts[0]))342 shortFlag = flagParts.shift();343 // Allow two long flags, like '--ws, --workspace'344 // This is the supported way to have a shortish option flag.345 if (!shortFlag && longFlagExp.test(flagParts[0])) {346 shortFlag = longFlag;347 longFlag = flagParts.shift();348 }

Throw for unsupported option flag setup (#2270)John Geebefore adoption966720a

line 349why, one step back
349

Add support for dual long options when no short option (#2312)John Geebefore adoption8263b7f

lines 350–371why, one step back
350 // Check for unprocessed flag. Fail noisily rather than silently ignore.
351 if (flagParts[0].startsWith('-')) {352 const unsupportedFlag = flagParts[0];353 const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;354 if (/^-[^-][^-]/.test(unsupportedFlag))355 throw new Error(356 `${baseError}357- a short flag is a single dash and a single character358 - either use a single dash and a single character (for a short flag)359 - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,360 );361 if (shortFlagExp.test(unsupportedFlag))362 throw new Error(`${baseError}363- too many short flags`);364 if (longFlagExp.test(unsupportedFlag))365 throw new Error(`${baseError}366- too many long flags`);367368 throw new Error(`${baseError}369- unrecognised flag format`);370 }371 if (shortFlag === undefined && longFlag === undefined)

Throw for unsupported option flag setup (#2270)John Geebefore adoption966720a

line 372why, one step back
372 throw new Error(

Add support for dual long options when no short option (#2312)John Geebefore adoption8263b7f

line 373why, one step back
373 `option creation failed due to no flags found in '${flags}'.`,

Throw for unsupported option flag setup (#2270)John Geebefore adoption966720a

lines 374–375why, one step back
374 );
375

Add copyInheritedSettings to README (#1798)John Geebefore adoption471ec40

lines 376–377why, one step back
376 return { shortFlag, longFlag };
377}