commander 7.2.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/Readme.md CHANGED
@@ -22,16 +22,20 @@ Read this in other languages: English | [简体中文](./Readme_zh-CN.md)
22
22
  - [More configuration](#more-configuration)
23
23
  - [Custom option processing](#custom-option-processing)
24
24
  - [Commands](#commands)
25
- - [Specify the argument syntax](#specify-the-argument-syntax)
25
+ - [Command-arguments](#command-arguments)
26
+ - [More configuration](#more-configuration-1)
27
+ - [Custom argument processing](#custom-argument-processing)
26
28
  - [Action handler](#action-handler)
27
29
  - [Stand-alone executable (sub)commands](#stand-alone-executable-subcommands)
30
+ - [Life cycle hooks](#life-cycle-hooks)
28
31
  - [Automated help](#automated-help)
29
32
  - [Custom help](#custom-help)
33
+ - [Display help after errors](#display-help-after-errors)
30
34
  - [Display help from code](#display-help-from-code)
31
35
  - [.usage and .name](#usage-and-name)
32
36
  - [.helpOption(flags, description)](#helpoptionflags-description)
33
37
  - [.addHelpCommand()](#addhelpcommand)
34
- - [More configuration](#more-configuration-1)
38
+ - [More configuration](#more-configuration-2)
35
39
  - [Custom event listeners](#custom-event-listeners)
36
40
  - [Bits and pieces](#bits-and-pieces)
37
41
  - [.parse() and .parseAsync()](#parse-and-parseasync)
@@ -94,7 +98,10 @@ const program = new Command();
94
98
 
95
99
  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 ('|').
96
100
 
97
- The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler. Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.
101
+ The parsed options can be accessed by calling `.opts()` on a `Command` object, and are passed to the action handler.
102
+ You can also use `.getOptionValue()` and `.setOptionValue()` to work with a single option value.
103
+
104
+ Multi-word options such as "--template-engine" are camel-cased, becoming `program.opts().templateEngine` etc.
98
105
 
99
106
  Multiple 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).
100
107
  For example `-a -b -p 80` may be written as `-ab -p80` or even `-abp80`.
@@ -126,12 +133,9 @@ if (options.pizzaType) console.log(`- ${options.pizzaType}`);
126
133
  ```
127
134
 
128
135
  ```bash
129
- $ pizza-options -d
130
- { debug: true, small: undefined, pizzaType: undefined }
131
- pizza details:
132
136
  $ pizza-options -p
133
137
  error: option '-p, --pizza-type <type>' argument missing
134
- $ pizza-options -ds -p vegetarian
138
+ $ pizza-options -d -s -p vegetarian
135
139
  { debug: true, small: true, pizzaType: 'vegetarian' }
136
140
  pizza details:
137
141
  - small pizza size
@@ -342,7 +346,7 @@ function myParseInt(value, dummyPrevious) {
342
346
  // parseInt takes a string and a radix
343
347
  const parsedValue = parseInt(value, 10);
344
348
  if (isNaN(parsedValue)) {
345
- throw new commander.InvalidOptionArgumentError('Not a number.');
349
+ throw new commander.InvalidArgumentError('Not a number.');
346
350
  }
347
351
  return parsedValue;
348
352
  }
@@ -394,7 +398,7 @@ $ custom --list x,y,z
394
398
 
395
399
  You can specify (sub)commands using `.command()` or `.addCommand()`. There are two ways these can be implemented: using an action handler attached to the command, or as a stand-alone executable file (described in more detail later). The subcommands may be nested ([example](./examples/nestedCommands.js)).
396
400
 
397
- In the first parameter to `.command()` you specify the command name and any command-arguments. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.
401
+ In the first parameter to `.command()` you specify the command name. You may append the command-arguments after the command name, or specify them separately using `.argument()`. The arguments may be `<required>` or `[optional]`, and the last argument may also be `variadic...`.
398
402
 
399
403
  You can use `.addCommand()` to add an already configured subcommand to the program.
400
404
 
@@ -410,7 +414,7 @@ program
410
414
  console.log('clone command called');
411
415
  });
412
416
 
413
- // Command implemented using stand-alone executable file (description is second parameter to `.command`)
417
+ // Command implemented using stand-alone executable file, indicated by adding description as second parameter to `.command`.
414
418
  // Returns `this` for adding more commands.
415
419
  program
416
420
  .command('start <service>', 'start named service')
@@ -426,36 +430,37 @@ Configuration options can be passed with the call to `.command()` and `.addComma
426
430
  remove the command from the generated help output. Specifying `isDefault: true` will run the subcommand if no other
427
431
  subcommand is specified ([example](./examples/defaultCommand.js)).
428
432
 
429
- ### Specify the argument syntax
433
+ ### Command-arguments
434
+
435
+ For subcommands, you can specify the argument syntax in the call to `.command()` (as shown above). This
436
+ is the only method usable for subcommands implemented using a stand-alone executable, but for other subcommands
437
+ you can instead use the following method.
430
438
 
431
- You use `.arguments` to specify the expected command-arguments for the top-level command, and for subcommands they are usually
432
- included in the `.command` call. Angled brackets (e.g. `<required>`) indicate required command-arguments.
433
- Square brackets (e.g. `[optional]`) indicate optional command-arguments.
434
- You can optionally describe the arguments in the help by supplying a hash as second parameter to `.description()`.
439
+ To configure a command, you can use `.argument()` to specify each expected command-argument.
440
+ You supply the argument name and an optional description. The argument may be `<required>` or `[optional]`.
441
+ You can specify a default value for an optional command-argument.
435
442
 
436
- Example file: [arguments.js](./examples/arguments.js)
443
+ Example file: [argument.js](./examples/argument.js)
437
444
 
438
445
  ```js
439
446
  program
440
447
  .version('0.1.0')
441
- .arguments('<username> [password]')
442
- .description('test command', {
443
- username: 'user to login',
444
- password: 'password for user, if required'
445
- })
448
+ .argument('<username>', 'user to login')
449
+ .argument('[password]', 'password for user, if required', 'no password given')
446
450
  .action((username, password) => {
447
451
  console.log('username:', username);
448
- console.log('environment:', password || 'no password given');
452
+ console.log('password:', password);
449
453
  });
450
454
  ```
451
455
 
452
456
  The last argument of a command can be variadic, and only the last argument. To make an argument variadic you
453
- append `...` to the argument name. For example:
457
+ append `...` to the argument name. A variadic argument is passed to the action handler as an array. For example:
454
458
 
455
459
  ```js
456
460
  program
457
461
  .version('0.1.0')
458
- .command('rmdir <dirs...>')
462
+ .command('rmdir')
463
+ .argument('<dirs...>')
459
464
  .action(function (dirs) {
460
465
  dirs.forEach((dir) => {
461
466
  console.log('rmdir %s', dir);
@@ -463,7 +468,47 @@ program
463
468
  });
464
469
  ```
465
470
 
466
- The variadic argument is passed to the action handler as an array.
471
+ There is a convenience method to add multiple arguments at once, but without descriptions:
472
+
473
+ ```js
474
+ program
475
+ .arguments('<username> <password>');
476
+ ```
477
+
478
+ #### More configuration
479
+
480
+ There are some additional features available by constructing an `Argument` explicitly for less common cases.
481
+
482
+ Example file: [arguments-extra.js](./examples/arguments-extra.js)
483
+
484
+ ```js
485
+ program
486
+ .addArgument(new commander.Argument('<drink-size>', 'drink cup size').choices(['small', 'medium', 'large']))
487
+ .addArgument(new commander.Argument('[timeout]', 'timeout in seconds').default(60, 'one minute'))
488
+ ```
489
+
490
+ #### Custom argument processing
491
+
492
+ You may specify a function to do custom processing of command-arguments (like for option-arguments).
493
+ The callback function receives two parameters, the user specified command-argument and the previous value for the argument.
494
+ It returns the new value for the argument.
495
+
496
+ The processed argument values are passed to the action handler, and saved as `.processedArgs`.
497
+
498
+ You can optionally specify the default/starting value for the argument after the function parameter.
499
+
500
+ Example file: [arguments-custom-processing.js](./examples/arguments-custom-processing.js)
501
+
502
+ ```js
503
+ program
504
+ .command('add')
505
+ .argument('<first>', 'integer argument', myParseInt)
506
+ .argument('[second]', 'integer argument', myParseInt, 1000)
507
+ .action((first, second) => {
508
+ console.log(`${first} + ${second} = ${first + second}`);
509
+ })
510
+ ;
511
+ ```
467
512
 
468
513
  ### Action handler
469
514
 
@@ -474,7 +519,7 @@ Example file: [thank.js](./examples/thank.js)
474
519
 
475
520
  ```js
476
521
  program
477
- .arguments('<name>')
522
+ .argument('<name>')
478
523
  .option('-t, --title <honorific>', 'title to use before name')
479
524
  .option('-d, --debug', 'display some debugging')
480
525
  .action((name, options, command) => {
@@ -525,6 +570,33 @@ program.parse(process.argv);
525
570
 
526
571
  If the program is designed to be installed globally, make sure the executables have proper modes, like `755`.
527
572
 
573
+ ### Life cycle hooks
574
+
575
+ You can add callback hooks to a command for life cycle events.
576
+
577
+ Example file: [hook.js](./examples/hook.js)
578
+
579
+ ```js
580
+ program
581
+ .option('-t, --trace', 'display trace statements for commands')
582
+ .hook('preAction', (thisCommand, actionCommand) => {
583
+ if (thisCommand.opts().trace) {
584
+ console.log(`About to call action handler for subcommand: ${actionCommand.name()}`);
585
+ console.log('arguments: %O', actionCommand.args);
586
+ console.log('options: %o', actionCommand.opts());
587
+ }
588
+ });
589
+ ```
590
+
591
+ The callback hook can be `async`, in which case you call `.parseAsync` rather than `.parse`. You can add multiple hooks per event.
592
+
593
+ The supported events are:
594
+
595
+ - `preAction`: called before action handler for this command and its subcommands
596
+ - `postAction`: called after action handler for this command and its subcommands
597
+
598
+ The hook is passed the command it was added to, and the command running the action handler.
599
+
528
600
  ## Automated help
529
601
 
530
602
  The help information is auto-generated based on the information commander already knows about your program. The default
@@ -599,6 +671,23 @@ The second parameter can be a string, or a function returning a string. The func
599
671
  - error: a boolean for whether the help is being displayed due to a usage error
600
672
  - command: the Command which is displaying the help
601
673
 
674
+ ### Display help after errors
675
+
676
+ The default behaviour for usage errors is to just display a short error message.
677
+ You can change the behaviour to show the full help or a custom help message after an error.
678
+
679
+ ```js
680
+ program.showHelpAfterError();
681
+ // or
682
+ program.showHelpAfterError('(add --help for additional information)');
683
+ ```
684
+
685
+ ```sh
686
+ $ pizza --unknown
687
+ error: unknown option '--unknown'
688
+ (add --help for additional information)
689
+ ```
690
+
602
691
  ### Display help from code
603
692
 
604
693
  `.help()`: display help information and exit immediately. You can optionally pass `{ error: true }` to display on stderr and exit with an error status.
@@ -905,7 +994,7 @@ More samples can be found in the [examples](https://github.com/tj/commander.js/t
905
994
 
906
995
  ## Support
907
996
 
908
- The current version of Commander is fully supported on Long Term Support versions of node, and requires at least node v10.
997
+ The current version of Commander is fully supported on Long Term Support versions of node, and requires at least node v12.
909
998
  (For older versions of node, use an older version of Commander. Commander version 2.x has the widest support.)
910
999
 
911
1000
  The main forum for free and community support is the project [Issues](https://github.com/tj/commander.js/issues) on GitHub.
package/esm.mjs CHANGED
@@ -1,4 +1,15 @@
1
1
  import commander from './index.js';
2
2
 
3
3
  // wrapper to provide named exports for ESM.
4
- export const { program, Option, Command, CommanderError, InvalidOptionArgumentError, Help, createCommand } = commander;
4
+ export const {
5
+ program,
6
+ createCommand,
7
+ createArgument,
8
+ createOption,
9
+ CommanderError,
10
+ InvalidArgumentError,
11
+ Command,
12
+ Argument,
13
+ Option,
14
+ Help
15
+ } = commander;