Skip to content
Myr

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

16 files+301 added−249 removed

added:docs/options-in-depth.md+204 added
1<!-- omit from toc -->2# Options in Depth34The README covers declaring and using options, and mostly parsing will work the way you and your users expect. This page covers some special cases5and subtle issues in depth.67- [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)1415## Options taking varying numbers of option-arguments1617Certain options take a varying number of arguments:1819```js20program21 .option('-c, --compress [percentage]') // 0 or 122 .option('--preprocess <file...>') // 1 or more23 .option('--test [name...]') // 0 or more24```2526This section uses examples with options taking 0 or 1 arguments, but the discussions also apply to variadic options taking more arguments.2728For information about terms used in this document see: [terminology](./terminology.md)2930### Parsing ambiguity3132There is a potential downside to be aware of. If a command has both33command-arguments and options with varying option-arguments, this introduces a parsing ambiguity which may affect the user of your program.34Commander looks for option-arguments first, but the user may35intend the argument following the option as a command or command-argument.3637```js38program39 .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 });4748program.parse();49```5051```sh52$ cook scrambled53technique: scrambled54ingredient: undefined5556$ cook -i57technique: undefined58ingredient: cheese5960$ cook -i egg61technique: undefined62ingredient: egg6364$ cook -i scrambled # oops65technique: undefined66ingredient: scrambled67```6869The explicit way to resolve this is use `--` to indicate the end of the options and option-arguments:7071```sh72$ node cook.js -i -- scrambled73technique: scrambled74ingredient: cheese75```7677If you want to avoid your users needing to learn when to use `--`, there are a few approaches you could take.7879#### Alternative: Make `--` part of your syntax8081Rather than trying to teach your users what `--` does, you could just make it part of your syntax.8283```js84program.usage('[options] -- [technique]');85```8687```sh88$ cook --help89Usage: cook [options] -- [technique]9091Options:92 -i, --ingredient [ingredient] add cheese or given ingredient93 -h, --help display help for command9495$ cook -- scrambled96technique: scrambled97ingredient: undefined9899$ cook -i -- scrambled100technique: scrambled101ingredient: cheese102```103104#### Alternative: Put options last105106Commander follows the GNU convention for parsing and allows options before or after the command-arguments, or intermingled.107So by putting the options last, the command-arguments do not get confused with the option-arguments.108109```js110program.usage('[technique] [options]');111```112113```sh114$ cook --help115Usage: cook [technique] [options]116117Options:118 -i, --ingredient [ingredient] add cheese or given ingredient119 -h, --help display help for command120121$ node cook.js scrambled -i122technique: scrambled123ingredient: cheese124```125126#### Alternative: Use options instead of command-arguments127128This is a bit more radical, but completely avoids the parsing ambiguity!129130```js131program132 .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```141142```sh143$ cook -i -t scrambled144technique: scrambled145ingredient: cheese146```147148## Combining short options, and options taking arguments149150Multiple boolean short options can be combined after a single `-`, like `ls -al`. You can also include just151a single short option which might take a value, as any following characters will152be taken as the value.153154This means that by default you can not combine short options which may take an argument.155156```js157program158 .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)");162program.parse(process.argv);163164const opts = program.opts();165if (opts.other) console.log(`other servings: ${opts.other}`);166if (opts.vegan) console.log(`vegan servings: ${opts.vegan}`);167if (opts.halal) console.log(`halal servings: ${opts.halal}`);168```169170```sh171$ collect -o 3172other servings: 3173$ collect -o3 174other servings: 3175$ collect -l -v176vegan servings: true177halal servings: true178$ collect -lv # oops179halal servings: v180```181182If you wish to use options taking varying arguments as boolean options, you need to specify them separately.183184```console185$ collect -a -v -l186any servings: true187vegan servings: true188halal servings: true189```190191### Combining short options as if boolean192193Before Commander v5, combining a short option and the value was not supported, and combined short flags were always expanded.194So `-avl` expanded to `-a -v -l`.195196If you want backwards compatible behaviour, or prefer combining short options as booleans to combining short option and value,197you may change the behavior.198199To modify the parsing of options taking an optional value:200201```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-arguments23The README covers declaring and using options, and mostly parsing will work the way you and your users expect. This page covers some special cases4and subtle issues in depth.56- [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)1314Certain options take a varying number of arguments:1516```js17program18 .option('-c, --compress [percentage]') // 0 or 119 .option('--preprocess <file...>') // 1 or more20 .option('--test [name...]') // 0 or more21```2223This page uses examples with options taking 0 or 1 arguments, but the discussions also apply to variadic options taking more arguments.2425For information about terms used in this document see: [terminology](./terminology.md)2627## Parsing ambiguity2829There is a potential downside to be aware of. If a command has both30command-arguments and options with varying option-arguments, this introduces a parsing ambiguity which may affect the user of your program.31Commander looks for option-arguments first, but the user may32intend the argument following the option as a command or command-argument.3334```js35program36 .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 });4445program.parse();46```4748```sh49$ cook scrambled50technique: scrambled51ingredient: undefined5253$ cook -i54technique: undefined55ingredient: cheese5657$ cook -i egg58technique: undefined59ingredient: egg6061$ cook -i scrambled # oops62technique: undefined63ingredient: scrambled64```6566The explicit way to resolve this is use `--` to indicate the end of the options and option-arguments:6768```sh69$ node cook.js -i -- scrambled70technique: scrambled71ingredient: cheese72```7374If you want to avoid your users needing to learn when to use `--`, there are a few approaches you could take.7576### Alternative: Make `--` part of your syntax7778Rather than trying to teach your users what `--` does, you could just make it part of your syntax.7980```js81program.usage('[options] -- [technique]');82```8384```sh85$ cook --help86Usage: cook [options] -- [technique]8788Options:89 -i, --ingredient [ingredient] add cheese or given ingredient90 -h, --help display help for command9192$ cook -- scrambled93technique: scrambled94ingredient: undefined9596$ cook -i -- scrambled97technique: scrambled98ingredient: cheese99```100101### Alternative: Put options last102103Commander follows the GNU convention for parsing and allows options before or after the command-arguments, or intermingled.104So by putting the options last, the command-arguments do not get confused with the option-arguments.105106```js107program.usage('[technique] [options]');108```109110```sh111$ cook --help112Usage: cook [technique] [options]113114Options:115 -i, --ingredient [ingredient] add cheese or given ingredient116 -h, --help display help for command117118$ node cook.js scrambled -i119technique: scrambled120ingredient: cheese121```122123### Alternative: Use options instead of command-arguments124125This is a bit more radical, but completely avoids the parsing ambiguity!126127```js128program129 .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```138139```sh140$ cook -i -t scrambled141technique: scrambled142ingredient: cheese143```144145## Combining short options, and options taking arguments146147Multiple boolean short options can be combined after a single `-`, like `ls -al`. You can also include just148a single short option which might take a value, as any following characters will149be taken as the value.150151This means that by default you can not combine short options which may take an argument.152153```js154program155 .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)");159program.parse(process.argv);160161const opts = program.opts();162if (opts.other) console.log(`other servings: ${opts.other}`);163if (opts.vegan) console.log(`vegan servings: ${opts.vegan}`);164if (opts.halal) console.log(`halal servings: ${opts.halal}`);165```166167```sh168$ collect -o 3169other servings: 3170$ collect -o3 171other servings: 3172$ collect -l -v173vegan servings: true174halal servings: true175$ collect -lv # oops176halal servings: v177```178179If you wish to use options taking varying arguments as boolean options, you need to specify them separately.180181```182$ collect -a -v -l183any servings: true184vegan servings: true185halal servings: true186```187188### Combining short options as if boolean189190Before Commander v5, combining a short option and the value was not supported, and combined short flags were always expanded.191So `-avl` expanded to `-a -v -l`.192193If you want backwards compatible behaviour, or prefer combining short options as booleans to combining short option and value, 194you may change the behavior.195196To modify the parsing of options taking an optional value:197198```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
modified:lib/command.js+3 added-5 removed
8 unmodified lines
9const { Help } = require('./help.js');10const { Option, splitOptionFlags, DualOptions } = require('./option.js');11const { suggestSimilar } = require('./suggestSimilar');1213// @ts-check1413class Command extends EventEmitter {14 /**15 * Initialize a new `Command`.16 *
743 unmodified lines
760 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 lines
modified:lib/error.js-2 removed
modified:lib/help.js-2 removed
6 unmodified lines
7 * @typedef { import("./command.js").Command } Command8 * @typedef { import("./option.js").Option } Option9 */1011// @ts-check1211// Although this is a class, methods are static in style to allow override using subclass or just functions.12class Help {13 constructor() {14 this.helpWidth = undefined;
448 unmodified lines
modified:lib/option.js-2 removed
1const { InvalidArgumentError } = require('./error.js');23// @ts-check43class Option {4 /**5 * Initialize a new `Option` with the given `flags` and `description`.6 *
322 unmodified lines
modified:tests/commander.configureCommand.test.js+7 added-7 removed
83 unmodified lines
84 program.storeOptionsAsProperties();85 }).toThrow();86});8788test('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 lines
1516const 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 lines
modified:index.js-2 removed
2 unmodified lines
3const { CommanderError, InvalidArgumentError } = require('./lib/error.js');4const { Help } = require('./lib/help.js');5const { Option } = require('./lib/option.js');67// @ts-check87exports.program = new Command();89exports.createCommand = (name) => new Command(name);10exports.createOption = (flags, description) => new Option(flags, description);
14 unmodified lines
modified:jest.config.js+1 added-1 removed
1const 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 lines
modified:package.json+4 added-4 removed
20 unmodified lines
21 "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 lines
modified:Readme.md+3 added-3 removed
325 unmodified lines
326327Options with an optional option-argument are not greedy and will ignore arguments starting with a dash.328So `id` behaves as a boolean option for `--id -5`, but you can use a combined form if needed like `--id=-5`.329330For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).330For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).331332### Required option333334You 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 lines
378Options: { number: [ '1', '2', '3' ], letter: true }379Remaining arguments: [ 'operand' ]380```381382For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-taking-varying-arguments.md).382For information about possible ambiguous cases, see [options taking varying arguments](./docs/options-in-depth.md).383384### Version option385386The 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 lines
11301131There is more information available about:11321133- [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)11361137## Support1138
10 unmodified lines
added: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",1617 "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,2526 "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}