Add support for dual long options when no short option (#2312)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by John Gee · committed by GitHub · parent bb733f4 · Browse files · 7 files·+61 added−28 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
7 files+61 added−28 removed
- tests:+5 added−3 removed
- other:+56 added−25 removed
Provenance
- Commit
8263b7f- Tree
f7dcb68- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
bb733f4
7 files changed+61 added−28 removed
modified:docs/deprecated.md+10 added-7 removed
10 unmodified lines11 - [.on('command:\*')](#oncommand)12 - [.command('\*')](#command)13 - [cmd.description(cmdDescription, argDescriptions)](#cmddescriptioncmddescription-argdescriptions)14 - [InvalidOptionArgumentError](#invalidoptionargumenterror)15- - [Short option flag longer than a single character](#short-option-flag-longer-than-a-single-character)15 - [Import from `commander/esm.mjs`](#import-from-commanderesmmjs)16 - [cmd.\_args](#cmd_args)17 - [.addHelpCommand(string|boolean|undefined)](#addhelpcommandstringbooleanundefined)18 - [Removed](#removed)19+ - [Short option flag longer than a single character](#short-option-flag-longer-than-a-single-character)20 - [Default import of global Command object](#default-import-of-global-command-object)21 22 ### RegExp .option() parameter23 143 unmodified lines167 ```168 169 Deprecated from Commander v8.170 171-### Short option flag longer than a single character172-173-Short option flags like `-ws` were never supported, but the old README did not make this clear. The README now states that short options are a single character.174-175-README updated in Commander v3. Deprecated from Commander v9.176-171 ### Import from `commander/esm.mjs`172 173 The first support for named imports required an explicit entry file.174 50 unmodified lines225 - Deprecated from Commander v12.226 227 ## Removed228 229+### Short option flag longer than a single character230+231+Short option flags like `-ws` were never supported, but the old README did not make this clear. The README now states that short options are a single character.232+233+- README updated in Commander v3.234+- Deprecated from Commander v9.235+- Throws an exception in Commander v13. Deprecated and gone!236+- Replacement added in Commander v13.1 with support for dual long options, like `--ws, --workspace`.237+238 ### Default import of global Command object239 240 The default import was a global Command object.241 17 unmodified linesmodified:lib/command.js+1 added-1 removed
754 unmodified lines755 *756 * @example757 * program758 * .option('-p, --pepper', 'add pepper')759- * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument759+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument760 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default761 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function762 *763 * @param {string} flags1899 unmodified linesmodified:lib/option.js+34 added-15 removed
16 unmodified lines17 // 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);21- this.short = optionFlags.shortFlag;21+ this.short = optionFlags.shortFlag; // May be a short flag, undefined, or even a long flag (if option has two long flags).22 this.long = optionFlags.longFlag;23 this.negate = false;24 if (this.long) {25 this.negate = this.long.startsWith('--no-');294 unmodified lines320 // long flag, double dash and at least one character321 const longFlagExp = /^--[^-]/;322 323 const flagParts = flags.split(/[ |,]+/).concat('guard');324+ // Normal is short and/or long.325 if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();326 if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();327+ // Long then short. Rarely used but fine.328+ if (!shortFlag && shortFlagExp.test(flagParts[0]))329+ shortFlag = flagParts.shift();330+ // Allow two long flags, like '--ws, --workspace'331+ // This is the supported way to have a shortish option flag.332+ if (!shortFlag && longFlagExp.test(flagParts[0])) {333+ shortFlag = longFlag;334+ longFlag = flagParts.shift();335+ }336 327- // Check for some unsupported flags that people try.328- if (/^-[^-][^-]/.test(flagParts[0]))337+ // Check for unprocessed flag. Fail noisily rather than silently ignore.338+ if (flagParts[0].startsWith('-')) {339+ const unsupportedFlag = flagParts[0];340+ const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;341+ if (/^-[^-][^-]/.test(unsupportedFlag))342+ throw new Error(343+ `${baseError}344+- a short flag is a single dash and a single character345+ - either use a single dash and a single character (for a short flag)346+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`,347+ );348+ if (shortFlagExp.test(unsupportedFlag))349+ throw new Error(`${baseError}350+- too many short flags`);351+ if (longFlagExp.test(unsupportedFlag))352+ throw new Error(`${baseError}353+- too many long flags`);354+355+ throw new Error(`${baseError}356+- unrecognised flag format`);357+ }358+ if (shortFlag === undefined && longFlag === undefined)359 throw new Error(330- `invalid Option flags, short option is dash and single character: '${flags}'`,360+ `option creation failed due to no flags found in '${flags}'.`,361 );332- if (shortFlag && shortFlagExp.test(flagParts[0]))333- throw new Error(334- `invalid Option flags, more than one short flag: '${flags}'`,335- );336- if (longFlag && longFlagExp.test(flagParts[0]))337- throw new Error(338- `invalid Option flags, more than one long flag: '${flags}'`,339- );340- // Generic error if failed to find a flag or an unexpected flag left over.341- if (!(shortFlag || longFlag) || flagParts[0].startsWith('-'))342- throw new Error(`invalid Option flags: '${flags}'`);362 363 return { shortFlag, longFlag };364 }365 2 unmodified linesmodified:tests/option.bad-flags.test.js+5 added-3 removed
3 unmodified lines4567898910111213141516171818192021222324252627282930315 unmodified lines3 unmodified linestest.each([ { flags: '-a, -b' }, // too many short flags { flags: '-a, -b <value>' }, { flags: '-a, -b, --long' }, { flags: '--one, --two' }, // too many long flags { flags: '--one, --two [value]' }, { flags: '--one, --two, --three' }, // too many long flags { flags: '-ws' }, // short flag with more than one character { flags: '---triple' }, // double dash not followed by a non-dash { flags: 'sdkjhskjh' }, // oops, no flags { flags: '-a,-b' }, // try all the separators { flags: '-a|-b' }, { flags: '-a -b' },])('when construct Option with flags %p then throw', ({ flags }) => { expect(() => { new Option(flags); }).toThrow(/^invalid Option flags/); }).toThrow(/^option creation failed/);});
// Check that supported flags do not throw.test.each([ { flags: '-s' }, // single short { flags: '--long' }, // single long { flags: '-b, --both' }, // short and long { flags: '--both, -b' }, // long and short { flags: '--ws, --workspace' }, // two long (morally shortish and long) { flags: '-b,--both <comma>' }, { flags: '-b|--both <bar>' }, { flags: '-b --both [space]' }, { flags: '-v, --variadic <files...>' },5 unmodified linesmodified:typings/index.d.ts+1 added-1 removed
615 unmodified lines616 *617 * ```js618 * program619 * .option('-p, --pepper', 'add pepper')620- * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument620+ * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument621 * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default622 * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function623 * ```624 *421 unmodified linesmodified:CHANGELOG.md+1 added
21 unmodified lines22 ### Changed23 24 - *Breaking*: excess command-arguments cause an error by default, see migration tips ([#2223])25 - *Breaking*: throw during Option construction for unsupported option flags, like multiple characters after single `-` ([#2270])26+ - note: support for dual long option flags added in Commander 13.127 - *Breaking*: throw on multiple calls to `.parse()` if `storeOptionsAsProperties: true` ([#2299])28 - TypeScript: include implicit `this` in parameters for action handler callback ([#2197])29 30 ### Deleted1466 unmodified linesmodified:Readme.md+9 added-1 removed
173 unmodified lines174 ```175 176 ## Options177 178-Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|').178+Options are defined with the `.option()` method, also serving as documentation for the options. Each option can have a short flag (single character) and a long name, separated by a comma or space or vertical bar ('|'). To allow a wider range of short-ish flags than just179+single characters, you may also have two long options. Examples:180 181+```js182+program183+ .option('-p, --port <number>', 'server port number')184+ .option('--trace', 'add extra debugging output')185+ .option('--ws, --workspace <name>', 'use a custom workspace')186+```187+188 The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.189 190 Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.191 958 unmodified lines