Skip to content
Myr

Merge remote-tracking branch 'origin/develop' into release/7.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 a05a8bc, 3998dd6 · Browse files · 6 files+258 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+258 added−1 removed

  • tests:+19 added−0 removed
  • other:+239 added−1 removed

6 files+258 added−1 removed

added:docs/options-taking-varying-arguments.md+220 added
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)13 - [Terminology](#terminology)1415Certain options take a varying number of arguments:1617```js18program19 .option('-c, --compress [percentage]') // 0 or 120 .option('--preprocess <file...>') // 1 or more21 .option('--test [name...]') // 0 or more22```2324This page uses examples with options taking 0 or 1 arguments, but the discussions also apply to variadic options taking more arguments.2526## Parsing ambiguity2728There is a potential downside to be aware of. If a command has both29command-arguments and options with varying option-arguments, this introduces a parsing ambiguity which may affect the user of your program.30Commander looks for option-arguments first, but the user may31intend the argument following the option as a command or command-argument.3233```js34program35 .name('cook')36 .arguments('[technique]')37 .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')38 .action((technique, options) => {39 console.log(`technique: ${technique}`);40 const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;41 console.log(`ingredient: ${ingredient}`);42 });4344program.parse();45```4647```sh48$ cook scrambled49technique: scrambled50ingredient: undefined5152$ cook -i53technique: undefined54ingredient: cheese5556$ cook -i egg57technique: undefined58ingredient: egg5960$ cook -i scrambled # oops61technique: undefined62ingredient: scrambled63```6465The explicit way to resolve this is use `--` to indicate the end of the options and option-arguments:6667```sh68$ node cook.js -i -- egg69technique: egg70ingredient: cheese71```7273If you want to avoid your users needing to learn when to use `--`, there are a few approaches you could take.7475### Alternative: Make `--` part of your syntax7677Rather than trying to teach your users what `--` does, you could just make it part of your syntax.7879```js80program.usage('[options] -- [technique]');81```8283```sh84$ cook --help85Usage: cook [options] -- [technique]8687Options:88 -i, --ingredient [ingredient] add cheese or given ingredient89 -h, --help display help for command9091$ cook -- scrambled92technique: scrambled93ingredient: undefined9495$ cook -i -- scrambled96technique: scrambled97ingredient: cheese98```99100### Alternative: Put options last101102Commander follows the GNU convention for parsing and allows options before or after the command-arguments, or intermingled.103So by putting the options last, the command-arguments do not get confused with the option-arguments.104105```js106program.usage('[technique] [options]');107```108109```sh110$ cook --help111Usage: cook [technique] [options]112113Options:114 -i, --ingredient [ingredient] add cheese or given ingredient115 -h, --help display help for command116117$ node cook.js scrambled -i118technique: scrambled119ingredient: cheese120```121122### Alternative: Use options instead of command-arguments123124This is a bit more radical, but completely avoids the parsing ambiguity!125126```js127program128 .name('cook')129 .option('-t, --technique <technique>', 'cooking technique')130 .option('-i, --ingredient [ingredient]', 'add cheese or given ingredient')131 .action((options) => {132 console.log(`technique: ${options.technique}`);133 const ingredient = (options.ingredient === true) ? 'cheese' : options.ingredient;134 console.log(`ingredient: ${ingredient}`);135 });136```137138```sh139$ cook -i -t scrambled140technique: scrambled141ingredient: cheese142```143## Combining short options, and options taking arguments144145Multiple boolean short options can be combined after a single `-`, like `ls -al`. You can also include just146a single short option which might take a value, as any following characters will147be taken as the value.148149This means that by default you can not combine short options which may take an argument.150151```js152program153 .name('collect')154 .option("-o, --other [count]", "other serving(s)")155 .option("-v, --vegan [count]", "vegan serving(s)")156 .option("-l, --halal [count]", "halal serving(s)");157program.parse(process.argv);158159const opts = program.opts();160if (opts.other) console.log(`other servings: ${opts.other}`);161if (opts.vegan) console.log(`vegan servings: ${opts.vegan}`);162if (opts.halal) console.log(`halal servings: ${opts.halal}`);163```164165```sh166$ collect -o 3167other servings: 3168$ collect -o3 169other servings: 3170$ collect -l -v171vegan servings: true172halal servings: true173$ collect -lv # oops174halal servings: v175```176177If you wish to use options taking varying arguments as boolean options, you need to specify them separately.178179```180$ collect -a -v -l181any servings: true182vegan servings: true183halal servings: true184```185186### Combining short options as if boolean187188Before Commander v5, combining a short option and the value was not supported, and combined short flags were always expanded.189So `-avl` expanded to `-a -v -l`.190191If you want backwards compatible behaviour, or prefer combining short options as booleans to combining short option and value, 192you may change the behavior.193194To modify the parsing of options taking an optional value:195196```js197.combineFlagAndOptionalValue(true) // `-v45` is treated like `--vegan=45`, this is the default behaviour198.combineFlagAndOptionalValue(false) // `-vl` is treated like `-v -l`199```200201## Terminology202203_Work in progress: this section may move to the main README, or a page of its own._204205The command line arguments are made up of options, option-arguments, commands, and command-arguments.206207| Term | Explanation |208| --- | --- |209| option | an argument which is a `-` followed by a character, or `--` followed by a word (or hyphenated words), like `-s` or `--short` |210| option-argument| some options can take an argument |211| command | a program or command can have subcommands |212| command-argument | argument for the command (and not an option or option-argument) |213214For example:215216```sh217my-utility command -o --option option-argument command-argument-1 command-argument-2218```219220In other references options are sometimes called flags, and command-arguments are sometimes called positional arguments or operands.
modified:examples/env+9 added
10 unmodified lines
1112program13 .version('0.0.1')14 .arguments('<cmd> [env]')15 .description('test command', {16 cmd: 'command to run',17 env: 'environment to run test in'18 })19 .action(function(cmdValue, envValue) {20 console.log('command:', cmdValue);21 console.log('environment:', envValue || 'no environment given');22 });2324program.parse(process.argv);2526// Try the following:27// node env --help28// node env add29// node env add browser
modified:tests/command.help.test.js+19 added
200 unmodified lines
201 .addOption(new commander.Option('-c, --colour <colour>').choices(['red', 'blue']).default('red'));202 const helpInformation = program.helpInformation();203 expect(helpInformation).toMatch('(choices: "red", "blue", default: "red")');204});205206test('when arguments then included in helpInformation', () => {207 const program = new commander.Command();208 program209 .name('foo')210 .arguments('<file>');211 const helpInformation = program.helpInformation();212 expect(helpInformation).toMatch('Usage: foo [options] <file>');213});214215test('when arguments described then included in helpInformation', () => {216 const program = new commander.Command();217 program218 .arguments('<file>')219 .helpOption(false)220 .description('description', { file: 'input source' });221 const helpInformation = program.helpInformation();222 expect(helpInformation).toMatch(/Arguments:\n\n +file +input source/); // [sic], extra line223});
modified:.gitignore+1 added
1 unmodified line
2node_modules3*.sock4.idea5.vscode/6coverage/
modified:package.json+3 added
modified:Readme.md+6 added-1 removed
75 unmodified lines
76Options 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 ('|').7778The options can be accessed as properties on the Command object. Multi-word options such as "--template-engine" are camel-cased, becoming `program.templateEngine` etc. See also optional new behaviour to [avoid name clashes](#avoiding-option-name-clashes).7980Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, the last flag may take a value, and the value.80Multiple short flags may optionally be combined in a single argument following the dash: boolean flags, followed by a single option taking a value (possibly followed by the value).81For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.8283You can use `--` to indicate the end of the options, and any remaining arguments will be used without being interpreted.84This is particularly useful for passing options through to another
310 unmodified lines
395396### Specify the argument syntax397398You use `.arguments` to specify the arguments for the top-level command, and for subcommands they are usually included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required input. Square brackets (e.g. `[optional]`) indicate optional input.399You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`.400401Example file: [env](./examples/env)402403```js404program405 .version('0.1.0')406 .arguments('<cmd> [env]')407 .description('test command', {408 cmd: 'command to run',409 env: 'environment to run test in'410 })411 .action(function (cmd, env) {412 console.log('command:', cmd);413 console.log('environment:', env || 'no environment given');414 });
403 unmodified lines