|
3 | 3 | // const commander = require('commander'); // (normal include)
|
4 | 4 | const commander = require('../'); // include commander in git clone of commander repo
|
5 | 5 |
|
6 |
| -// Use a class override of createCommand to customise subcommands, |
7 |
| -// in this example by adding --debug option. |
| 6 | +// Use a class override to customise the command and its subcommands. |
| 7 | +// |
| 8 | +// Configuring the command for compatibility with Commander v6 defaults behaviours. |
| 9 | + |
| 10 | +class Command6 extends commander.Command { |
| 11 | + constructor(name) { |
| 12 | + super(name); |
| 13 | + |
| 14 | + // Revert to Commander v6 behaviours. |
| 15 | + this.storeOptionsAsProperties(); |
| 16 | + this.allowExcessArguments(); |
| 17 | + } |
8 | 18 |
|
9 |
| -class MyCommand extends commander.Command { |
10 | 19 | createCommand(name) {
|
11 |
| - const cmd = new MyCommand(name); |
12 |
| - cmd.option('-d,--debug', 'output options'); |
13 |
| - return cmd; |
| 20 | + return new Command6(name); |
14 | 21 | }
|
15 | 22 | };
|
16 | 23 |
|
17 |
| -const program = new MyCommand(); |
| 24 | +function inspectCommand(command, optionName) { |
| 25 | + // The option value is stored as property on command because we called .storeOptionsAsProperties() |
| 26 | + console.log(`Inspecting '${command.name()}'`); |
| 27 | + console.log(`option '${optionName}': ${command[optionName]}`); |
| 28 | + console.log(`args: ${command.args}`); |
| 29 | +}; |
| 30 | + |
| 31 | +const program = new Command6('program') |
| 32 | + .option('-p, --port <number>') |
| 33 | + .action(() => { |
| 34 | + inspectCommand(program, 'port'); |
| 35 | + }); |
| 36 | + |
18 | 37 | program
|
19 |
| - .command('serve') |
20 |
| - .option('--port <port-number>', 'specify port number', 80) |
21 |
| - .action((options) => { |
22 |
| - if (options.debug) { |
23 |
| - console.log('Options:'); |
24 |
| - console.log(options); |
25 |
| - console.log(); |
26 |
| - } |
27 |
| - |
28 |
| - console.log(`Start serve on port ${options.port}`); |
| 38 | + .command('sub') |
| 39 | + .option('-d, --debug') |
| 40 | + .action((options, command) => { |
| 41 | + inspectCommand(command, 'debug'); |
29 | 42 | });
|
30 | 43 |
|
31 | 44 | program.parse();
|
32 | 45 |
|
| 46 | +// We can pass excess arguments without an error as we called .allowExcessArguments() |
| 47 | +// |
33 | 48 | // Try the following:
|
34 |
| -// node custom-command-class.js help serve |
35 |
| -// node custom-command-class.js serve --debug |
36 |
| -// node custom-command-class.js serve --debug --port 8080 |
| 49 | +// node custom-command-class.js --port 80 extra arguments |
| 50 | +// node custom-command-class.js sub --debug extra arguments |
0 commit comments