Merge branch 'develop' into release/12.x
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by John Gee · committed by John Gee · parents 5aaca0d, 03dea00 · Browse files · 16 files·+301 added−249 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
16 files+301 added−249 removed
- tests:+7 added−7 removed
- other:+294 added−242 removed
Provenance
- Commit
72e6f7a- Tree
7fedabf- Author
John Gee <john@ruru.gen.nz>- Committer
John Gee <john@ruru.gen.nz>- Parent 1
5aaca0d- Parent 2
03dea00
16 files changed+301 added−249 removed
added:docs/options-in-depth.md+204 added
1+<!-- omit from toc -->2+# Options in Depth3+4+The README covers declaring and using options, and mostly parsing will work the way you and your users expect. This page covers some special cases5+and subtle issues in depth.6+7+- [Options taking varying numbers of option-arguments](#options-taking-varying-numbers-of-option-arguments)8+ - [Parsing ambiguity](#parsing-ambiguity)9+ - [Alternative: Make `--` part of your syntax](#alternative-make-----part-of-your-syntax)10+ - [Alternative: Put options last](#alternative-put-options-last)11+ - [Alternative: Use options instead of command-arguments](#alternative-use-options-instead-of-command-arguments)12+- [Combining short options, and options taking arguments](#combining-short-options-and-options-taking-arguments)13+ - [Combining short options as if boolean](#combining-short-options-as-if-boolean)14+15+## Options taking varying numbers of option-arguments16+17+Certain options take a varying number of arguments:18+19+```js20+program21+ .option('-c, --compress [percentage]') // 0 or 122+ .option('--preprocess <file...>') // 1 or more23+ .option('--test [name...]') // 0 or more24+```25+26+This section uses examples with options taking 0 or 1 arguments, but the discussions also apply to variadic options taking more arguments.27+28+For information about terms used in this document see: [terminology](./terminology.md)29+30+### Parsing ambiguity31+32+There is a potential downside to be aware of. If a command has both33+command-arguments and options with varying option-arguments, this introduces a parsing ambiguity which may affect the user of your program.34+Commander looks for option-arguments first, but the user may35+intend the argument following the option as a command or command-argument.36+37+```js38+program39+ .name('cook')40+ .argument('[technique]')41+ .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')42+ .action((technique, options) => {43+ console.log(`technique: ${technique}`);44+ const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;45+ console.log(`ingredient: ${ingredient}`);46+ });47+48+program.parse();49+```50+51+```sh52+$ cook scrambled53+technique: scrambled54+ingredient: undefined55+56+$ cook -i57+technique: undefined58+ingredient: cheese59+60+$ cook -i egg61+technique: undefined62+ingredient: egg63+64+$ cook -i scrambled # oops65+technique: undefined66+ingredient: scrambled67+```68+69+The explicit way to resolve this is use `--` to indicate the end of the options and option-arguments:70+71+```sh72+$ node cook.js -i -- scrambled73+technique: scrambled74+ingredient: cheese75+```76+77+If you want to avoid your users needing to learn when to use `--`, there are a few approaches you could take.78+79+#### Alternative: Make `--` part of your syntax80+81+Rather than trying to teach your users what `--` does, you could just make it part of your syntax.82+83+```js84+program.usage('[options] -- [technique]');85+```86+87+```sh88+$ cook --help89+Usage: cook [options] -- [technique]90+91+Options:92+ -i, --ingredient [ingredient] add cheese or given ingredient93+ -h, --help display help for command94+95+$ cook -- scrambled96+technique: scrambled97+ingredient: undefined98+99+$ cook -i -- scrambled100+technique: scrambled101+ingredient: cheese102+```103+104+#### Alternative: Put options last105+106+Commander follows the GNU convention for parsing and allows options before or after the command-arguments, or intermingled.107+So by putting the options last, the command-arguments do not get confused with the option-arguments.108+109+```js110+program.usage('[technique] [options]');111+```112+113+```sh114+$ cook --help115+Usage: cook [technique] [options]116+117+Options:118+ -i, --ingredient [ingredient] add cheese or given ingredient119+ -h, --help display help for command120+121+$ node cook.js scrambled -i122+technique: scrambled123+ingredient: cheese124+```125+126+#### Alternative: Use options instead of command-arguments127+128+This is a bit more radical, but completely avoids the parsing ambiguity!129+130+```js131+program132+ .name('cook')133+ .option('-t, --technique <technique>', 'cooking technique')134+ .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')135+ .action((options) => {136+ console.log(`technique: ${options.technique}`);137+ const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;138+ console.log(`ingredient: ${ingredient}`);139+ });140+```141+142+```sh143+$ cook -i -t scrambled144+technique: scrambled145+ingredient: cheese146+```147+148+## Combining short options, and options taking arguments149+150+Multiple boolean short options can be combined after a single `-`, like `ls -al`. You can also include just151+a single short option which might take a value, as any following characters will152+be taken as the value.153+154+This means that by default you can not combine short options which may take an argument.155+156+```js157+program158+ .name('collect')159+ .option("-o, --other [count]", "other serving(s)")160+ .option("-v, --vegan [count]", "vegan serving(s)")161+ .option("-l, --halal [count]", "halal serving(s)");162+program.parse(process.argv);163+164+const opts = program.opts();165+if (opts.other) console.log(`other servings: ${opts.other}`);166+if (opts.vegan) console.log(`vegan servings: ${opts.vegan}`);167+if (opts.halal) console.log(`halal servings: ${opts.halal}`);168+```169+170+```sh171+$ collect -o 3172+other servings: 3173+$ collect -o3 174+other servings: 3175+$ collect -l -v176+vegan servings: true177+halal servings: true178+$ collect -lv # oops179+halal servings: v180+```181+182+If you wish to use options taking varying arguments as boolean options, you need to specify them separately.183+184+```console185+$ collect -a -v -l186+any servings: true187+vegan servings: true188+halal servings: true189+```190+191+### Combining short options as if boolean192+193+Before Commander v5, combining a short option and the value was not supported, and combined short flags were always expanded.194+So `-avl` expanded to `-a -v -l`.195+196+If you want backwards compatible behaviour, or prefer combining short options as booleans to combining short option and value,197+you may change the behavior.198+199+To modify the parsing of options taking an optional value:200+201+```js202+.combineFlagAndOptionalValue(true) // `-v45` is treated like `--vegan=45`, this is the default behaviour203+.combineFlagAndOptionalValue(false) // `-vl` is treated like `-v -l`204+```deleted:docs/options-taking-varying-arguments.md-201 removed
1-# Options taking varying numbers of option-arguments2-3-The README covers declaring and using options, and mostly parsing will work the way you and your users expect. This page covers some special cases4-and subtle issues in depth.5-6-- [Options taking varying numbers of option-arguments](#options-taking-varying-numbers-of-option-arguments)7- - [Parsing ambiguity](#parsing-ambiguity)8- - [Alternative: Make `--` part of your syntax](#alternative-make-----part-of-your-syntax)9- - [Alternative: Put options last](#alternative-put-options-last)10- - [Alternative: Use options instead of command-arguments](#alternative-use-options-instead-of-command-arguments)11- - [Combining short options, and options taking arguments](#combining-short-options-and-options-taking-arguments)12- - [Combining short options as if boolean](#combining-short-options-as-if-boolean)13-14-Certain options take a varying number of arguments:15-16-```js17-program18- .option('-c, --compress [percentage]') // 0 or 119- .option('--preprocess <file...>') // 1 or more20- .option('--test [name...]') // 0 or more21-```22-23-This page uses examples with options taking 0 or 1 arguments, but the discussions also apply to variadic options taking more arguments.24-25-For information about terms used in this document see: [terminology](./terminology.md)26-27-## Parsing ambiguity28-29-There is a potential downside to be aware of. If a command has both30-command-arguments and options with varying option-arguments, this introduces a parsing ambiguity which may affect the user of your program.31-Commander looks for option-arguments first, but the user may32-intend the argument following the option as a command or command-argument.33-34-```js35-program36- .name('cook')37- .argument('[technique]')38- .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')39- .action((technique, options) => {40- console.log(`technique: ${technique}`);41- const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;42- console.log(`ingredient: ${ingredient}`);43- });44-45-program.parse();46-```47-48-```sh49-$ cook scrambled50-technique: scrambled51-ingredient: undefined52-53-$ cook -i54-technique: undefined55-ingredient: cheese56-57-$ cook -i egg58-technique: undefined59-ingredient: egg60-61-$ cook -i scrambled # oops62-technique: undefined63-ingredient: scrambled64-```65-66-The explicit way to resolve this is use `--` to indicate the end of the options and option-arguments:67-68-```sh69-$ node cook.js -i -- scrambled70-technique: scrambled71-ingredient: cheese72-```73-74-If you want to avoid your users needing to learn when to use `--`, there are a few approaches you could take.75-76-### Alternative: Make `--` part of your syntax77-78-Rather than trying to teach your users what `--` does, you could just make it part of your syntax.79-80-```js81-program.usage('[options] -- [technique]');82-```83-84-```sh85-$ cook --help86-Usage: cook [options] -- [technique]87-88-Options:89- -i, --ingredient [ingredient] add cheese or given ingredient90- -h, --help display help for command91-92-$ cook -- scrambled93-technique: scrambled94-ingredient: undefined95-96-$ cook -i -- scrambled97-technique: scrambled98-ingredient: cheese99-```100-101-### Alternative: Put options last102-103-Commander follows the GNU convention for parsing and allows options before or after the command-arguments, or intermingled.104-So by putting the options last, the command-arguments do not get confused with the option-arguments.105-106-```js107-program.usage('[technique] [options]');108-```109-110-```sh111-$ cook --help112-Usage: cook [technique] [options]113-114-Options:115- -i, --ingredient [ingredient] add cheese or given ingredient116- -h, --help display help for command117-118-$ node cook.js scrambled -i119-technique: scrambled120-ingredient: cheese121-```122-123-### Alternative: Use options instead of command-arguments124-125-This is a bit more radical, but completely avoids the parsing ambiguity!126-127-```js128-program129- .name('cook')130- .option('-t, --technique <technique>', 'cooking technique')131- .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')132- .action((options) => {133- console.log(`technique: ${options.technique}`);134- const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;135- console.log(`ingredient: ${ingredient}`);136- });137-```138-139-```sh140-$ cook -i -t scrambled141-technique: scrambled142-ingredient: cheese143-```144-145-## Combining short options, and options taking arguments146-147-Multiple boolean short options can be combined after a single `-`, like `ls -al`. You can also include just148-a single short option which might take a value, as any following characters will149-be taken as the value.150-151-This means that by default you can not combine short options which may take an argument.152-153-```js154-program155- .name('collect')156- .option("-o, --other [count]", "other serving(s)")157- .option("-v, --vegan [count]", "vegan serving(s)")158- .option("-l, --halal [count]", "halal serving(s)");159-program.parse(process.argv);160-161-const opts = program.opts();162-if (opts.other) console.log(`other servings: ${opts.other}`);163-if (opts.vegan) console.log(`vegan servings: ${opts.vegan}`);164-if (opts.halal) console.log(`halal servings: ${opts.halal}`);165-```166-167-```sh168-$ collect -o 3169-other servings: 3170-$ collect -o3 171-other servings: 3172-$ collect -l -v173-vegan servings: true174-halal servings: true175-$ collect -lv # oops176-halal servings: v177-```178-179-If you wish to use options taking varying arguments as boolean options, you need to specify them separately.180-181-```182-$ collect -a -v -l183-any servings: true184-vegan servings: true185-halal servings: true186-```187-188-### Combining short options as if boolean189-190-Before Commander v5, combining a short option and the value was not supported, and combined short flags were always expanded.191-So `-avl` expanded to `-a -v -l`.192-193-If you want backwards compatible behaviour, or prefer combining short options as booleans to combining short option and value, 194-you may change the behavior.195-196-To modify the parsing of options taking an optional value:197-198-```js199-.combineFlagAndOptionalValue(true) // `-v45` is treated like `--vegan=45`, this is the default behaviour200-.combineFlagAndOptionalValue(false) // `-vl` is treated like `-v -l`201-```modified:lib/argument.js-2 removed
12343456139 unmodified linesExpand allconst { InvalidArgumentError } = require('./error.js');
// @ts-check
class Argument { /** * Initialize a new command argument with the given name and description. * The default is that the argument is required, and you can explicitly139 unmodified linesExpand allmodified:lib/command.js+3 added-5 removed
8 unmodified lines9 const { Help } = require('./help.js');10 const { Option, splitOptionFlags, DualOptions } = require('./option.js');11 const { suggestSimilar } = require('./suggestSimilar');12 13-// @ts-check14-13 class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *743 unmodified lines760 storeOptionsAsProperties(storeAsProperties = true) {761 if (this.options.length) {762 throw new Error('call .storeOptionsAsProperties() before adding options');763 }766- if (Object.keys(this._optionValues).length) {767- throw new Error('call .storeOptionsAsProperties() before setting option values');768- }764+ // if (Object.keys(this._optionValues).length) {765+ // throw new Error('call .storeOptionsAsProperties() before setting option values');766+ // }767 this._storeOptionsAsProperties = !!storeAsProperties;768 return this;769 }770 1418 unmodified linesmodified:lib/error.js-2 removed
12123439 unmodified lines// @ts-check
/** * CommanderError class * @class */39 unmodified linesmodified:lib/help.js-2 removed
6 unmodified lines7 * @typedef { import("./command.js").Command } Command8 * @typedef { import("./option.js").Option } Option9 */10 11-// @ts-check12-11 // Although this is a class, methods are static in style to allow override using subclass or just functions.12 class Help {13 constructor() {14 this.helpWidth = undefined;448 unmodified linesmodified:lib/option.js-2 removed
1 const { InvalidArgumentError } = require('./error.js');2 3-// @ts-check4-3 class Option {4 /**5 * Initialize a new `Option` with the given `flags` and `description`.6 *322 unmodified linesmodified:tests/commander.configureCommand.test.js+7 added-7 removed
83 unmodified lines84 program.storeOptionsAsProperties();85 }).toThrow();86 });87 88-test('when storeOptionsAsProperties() after setting option value then throw', () => {89- const program = new commander.Command();90- program.setOptionValue('foo', 'bar');91- expect(() => {92- program.storeOptionsAsProperties();93- }).toThrow();94-});88+// test('when storeOptionsAsProperties() after setting option value then throw', () => {89+// const program = new commander.Command();90+// program.setOptionValue('foo', 'bar');91+// expect(() => {92+// program.storeOptionsAsProperties();93+// }).toThrow();94+// });modified:.eslintrc.js+1 added-1 removed
14 unmodified lines15 16 const typescriptSettings = {17 files: ['*.ts', '*.mts'],18 parserOptions: {19- project: './tsconfig.json'19+ project: './tsconfig.ts.json'20 },21 plugins: [22 '@typescript-eslint'23 ],44 unmodified linesmodified:index.js-2 removed
2 unmodified lines3 const { CommanderError, InvalidArgumentError } = require('./lib/error.js');4 const { Help } = require('./lib/help.js');5 const { Option } = require('./lib/option.js');6 7-// @ts-check8-7 exports.program = new Command();8 9 exports.createCommand = (name) => new Command(name);10 exports.createOption = (flags, description) => new Option(flags, description);14 unmodified linesmodified:jest.config.js+1 added-1 removed
1 const config = {2 testEnvironment: 'node',3 collectCoverage: true,4 transform: {5- '^.+\\.tsx?$': 'ts-jest'5+ '^.+\\.tsx?$': ['ts-jest', { tsconfig: 'tsconfig.ts.json' }]6 },7 testPathIgnorePatterns: [8 '/node_modules/'9 ]3 unmodified linesmodified:package.json+4 added-4 removed
20 unmodified lines21 "scripts": {22 "lint": "npm run lint:javascript && npm run lint:typescript",23 "lint:javascript": "eslint index.js esm.mjs \"lib/*.js\" \"tests/**/*.js\"",24 "lint:typescript": "eslint typings/*.ts tests/*.ts",25- "test": "jest && npm run test-typings",25+ "test": "jest && npm run typecheck-ts",26 "test-esm": "node ./tests/esm-imports-test.mjs",27- "test-typings": "tsd",28- "typescript-checkJS": "tsc --allowJS --checkJS index.js lib/*.js --noEmit",29- "test-all": "npm run test && npm run lint && npm run typescript-checkJS && npm run test-esm"27+ "typecheck-ts": "tsd && tsc -p tsconfig.ts.json",28+ "typecheck-js": "tsc -p tsconfig.js.json",29+ "test-all": "npm run test && npm run lint && npm run typecheck-js && npm run test-esm"30 },31 "files": [32 "index.js",33 "lib/*.js",47 unmodified linesmodified:Readme.md+3 added-3 removed
325 unmodified lines326 327 Options with an optional option-argument are not greedy and will ignore arguments starting with a dash.328 So `id` behaves as a boolean option for `--id -5`, but you can use a combined form if needed like `--id=-5`.329 330-For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).330+For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).331 332 ### Required option333 334 You may specify a required (mandatory) option using `.requiredOption()`. The option must have a value after parsing, usually specified on the command line, or perhaps from a default value (say from environment). The method is otherwise the same as `.option()` in format, taking flags and description, and optional default value or custom processing.43 unmodified lines378 Options: { number: [ '1', '2', '3' ], letter: true }379 Remaining arguments: [ 'operand' ]380 ```381 382-For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).382+For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).383 384 ### Version option385 386 The optional `version` method adds handling for displaying the command version. The default option flags are `-V` and `--version`, and when present the command prints the version number and exits.743 unmodified lines1130 1131 There is more information available about:1132 1133 - [deprecated](./docs/deprecated.md) features still supported for backwards compatibility1134-- [options taking varying arguments](./docs/options-taking-varying-arguments.md)1134+- [options taking varying arguments](./docs/options-in-depth.md)1135 - [parsing life cycle and hooks](./docs/parsing-and-hooks.md)1136 1137 ## Support1138 10 unmodified linesadded:tsconfig.js.json+13 added
1+{ /* 2+ Simple override including just JavaScript files.3+ Used by npm run-script typecheck-js4+ */5+ /* Visit https://aka.ms/tsconfig to read more about tsconfig configuration. */6+ "extends": "./tsconfig.json",7+ "include": [8+ /* All JavaScript targets from tsconfig.json include. */9+ "*.js",10+ "*.mjs",11+ "lib/**/*.js"12+ ],13+}modified:tsconfig.json+45 added-17 removed
1 {2- "compilerOptions": {3- "module": "commonjs",4- "lib": [5- "es6"6- ],7- "noImplicitAny": true,8- "noImplicitThis": true,9- "strictNullChecks": true,10- "types": [11- "node",12- "jest"13- ],14- "esModuleInterop": true, // Mainly so can test an import problem which only occurs with this option on!15- "noEmit": true,16- "forceConsistentCasingInFileNames": true17- },18- "include": ["**/*.ts"],2+ /*3+ TypeScript is being used to do type checking across both JavaScript and TypeScript files.4+ In particular, this picks up some problems in the JSDoc in the JavaScript files, and validates the code5+ is consistent with the JSDoc.6+ 7+ The settings here are used by VSCode.8+ 9+ See also tsconfig.js.json and tsconfig.ts.json.10+ */11+ /* Visit https://aka.ms/tsconfig to read more about tsconfig configuration. */12+ "compilerOptions": {13+ "lib": ["es2021"],14+ "module": "node16",15+ "target": "es2021",16+17+ "allowJs": true,18+ "checkJs": true,19+ 20+ /* Strict by default, but dial it down to reduce churn in our JavaScript code. */21+ "strict": true,22+ "noImplicitAny": false, 23+ "strictNullChecks": false,24+ "useUnknownInCatchVariables": false,25+26+ "types": [27+ "node",28+ "jest"29+ ],30+ "noEmit": true, /* just type checking and not emitting transpiled files */31+ "skipLibCheck": false, /* we want to check our hand crafted definitions */32+ "forceConsistentCasingInFileNames": true,33+ "esModuleInterop": true /* common TypeScript config */34+ },35+ "include": [36+ /* JavaScript. Should match includes in tsconfig.js.json. */37+ "*.js",38+ "*.mjs",39+ "lib/**/*.js",40+ /* TypeScript. Should match includes in tsconfig.ts.json. */41+ "**/*.ts",42+ "**/*.mts"43+ ],44+ "exclude": [45+ "node_modules"46+ ]47 }added:tsconfig.ts.json+20 added
1+{ /* 2+ Override to include just TypeScript files and use stricter settings than we do with JavaScript.3+ Used by:4+ - npm run-script typecheck-ts5+ - eslint6+ */7+ /* Visit https://aka.ms/tsconfig to read more about tsconfig configuration. */8+ "extends": "./tsconfig.json",9+ "compilerOptions": {10+ /* Full strict is fine for the TypeScript files, so turn back on the checks we turned off for mixed-use. */11+ "noImplicitAny": true, 12+ "strictNullChecks": true,13+ "useUnknownInCatchVariables": true,14+ },15+ "include": [16+ /* All TypeScript targets from tsconfig.json include. */17+ "**/*.ts",18+ "**/*.mts"19+ ],20+}