Make new excess arguments error opt-in (#1429)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Make allowExcessArguments opt-in (again) and inherited configuration * Remove stale JSDoc * Update documentation for allowExcessArguments being opt-in * Make comment more specific about what is being checked for excess arguments * Rework example class override
authored by John Gee · committed by GitHub · parent 8ac84ec · Browse files · 6 files·+42 added−66 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+42 added−66 removed
- tests:+4 added−4 removed
- other:+38 added−62 removed
Provenance
- Commit
e2670f4- Tree
f8c873e- Author
John Gee <john@ruru.gen.nz>- Committer
GitHub <noreply@github.com>- Parent
8ac84ec
6 files changed+42 added−66 removed
modified:examples/custom-command-class.js+27 added-27 removed
2 unmodified lines3456787101112131415161718892010111213141516241718262719202122233132333424252627282930383940413132333435363738394041424344464745495046474849502 unmodified lines// const commander = require('commander'); // (normal include)const commander = require('../'); // include commander in git clone of commander repo
// Use a class override to customise the command and its subcommands.//// Configuring the command for compatibility with Commander v6 defaults behaviours.
class Command6 extends commander.Command { constructor(name) { super(name);
// Revert to Commander v6 behaviours. this.storeOptionsAsProperties(); this.allowExcessArguments(); }
class CommandWithTrace extends commander.Command { createCommand(name) { return new Command6(name); const cmd = new CommandWithTrace(name); // Add an option to subcommands created using `.command()` cmd.option('-t, --trace', 'display extra information when run command'); return cmd; }};
function inspectCommand(command, optionName) {function inpectCommand(command) { // The option value is stored as property on command because we called .storeOptionsAsProperties() console.log(`Inspecting '${command.name()}'`); console.log(`option '${optionName}': ${command[optionName]}`); console.log(`Called '${command.name()}'`); console.log(`args: ${command.args}`); console.log('opts: %o', command.opts());};
const program = new Command6('program') .option('-p, --port <number>') .action(() => { inspectCommand(program, 'port');const program = new CommandWithTrace('program') .option('-v, ---verbose') .action((options, command) => { inpectCommand(command); });
program .command('sub') .option('-d, --debug') .action((options, command) => { inspectCommand(command, 'debug'); .command('serve [params...]') .option('-p, --port <number>', 'port number') .action((params, options, command) => { inpectCommand(command); });
program .command('build <target>') .action((buildTarget, options, command) => { inpectCommand(command); });
program.parse();
// We can pass excess arguments without an error as we called .allowExcessArguments()//// Try the following:// node custom-command-class.js --port 80 extra arguments// node custom-command-class.js sub --debug extra arguments// node custom-command-class.js --help// node custom-command-class.js serve --help// node custom-command-class.js serve -t -p 80 a b c// node custom-command-class.js build --help// node custom-command-class.js build --trace foomodified:tests/command.allowExcessArguments.test.js+4 added-4 removed
16 unmodified lines1718192021212223242526272829293031323330 unmodified lines646566676868697071727374757677777879808164 unmodified lines16 unmodified lines afterAll(() => { writeErrorSpy.mockRestore(); });
test('when specify excess program argument then error by default', () => { test('when specify excess program argument then no error by default', () => { const program = new commander.Command(); program .exitOverride() .action(() => {});
expect(() => { program.parse(['excess'], { from: 'user' }); }).toThrow(); }).not.toThrow(); });
test('when specify excess program argument and allowExcessArguments(false) then error', () => { const program = new commander.Command();30 unmodified lines program.parse(['excess'], { from: 'user' }); }).not.toThrow(); });
test('when specify excess command argument then error (by default)', () => { test('when specify excess command argument then no error (by default)', () => { const program = new commander.Command(); program .exitOverride() .command('sub') .action(() => { });
expect(() => { program.parse(['sub', 'excess'], { from: 'user' }); }).toThrow(); }).not.toThrow(); });
test('when specify excess command argument and allowExcessArguments(false) then error', () => { const program = new commander.Command();64 unmodified linesmodified:typings/index.d.ts+1 added-1 removed
400 unmodified lines401 */402 allowUnknownOption(allowUnknown?: boolean): this;403 404 /**405- * Allow excess arguments on the command line.405+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.406 *407 * @returns `this` command for chaining408 */409 allowExcessArguments(allowExcess?: boolean): this;212 unmodified linesmodified:CHANGELOG.md+1 added-28 removed
10 unmodified lines11 ## [7.0.0] (date goes here)12 13 ### Added14 15-- *Breaking:* error message if there are too many command-arguments on command line for the action handler ([#1409])16- - if should be allowed then declare extra arguments, or use `.allowExcessArguments()`15+- `.allowExcessArguments(false)` to show an error message if there are too many command-arguments on command line for the action handler ([#1409])16 - `.configureOutput()` to modify use of stdout and stderr or customise display of errors ([#1387])17 - use `.addHelpText()` to add text before or after the built-in help, for just current command or also for all subcommands ([#1296])18 - enhance Option class ([#1331])19 - allow hiding options from help98 unmodified lines118 if (command.opts().trace) console.log(`Command name is ${command.name()}`);119 });120 ```121 123-**excess command-arguments**124-125-There is now an error if there are too many command-arguments on the command line (only checked if there is an action handler).126-If the extra arguments are supported by your command then you can either declare the expected arguments, or allow excess arguments.127-128-```js129-// Old code before Commander 7130-program131- .action(() => {});132-program.parse(['a', 'b', 'c'], { from: 'user' }); // now causes an error133-```134-135-```js136-// New code, declare arguments137-program138- .arguments('[args...]')139- .action(() => {});140-```141-142-```js143-// New code, allow excess arguments144-program145- .allowExcessArguments()146- .action(() => {});147-```148-122 ## [7.0.0-2] (2020-12-14)123 124 (Released in 7.0.0)125 265 unmodified linesmodified:index.js+4 added-4 removed
533 unmodified lines534 this.commands = [];535 this.options = [];536 this.parent = null;537 this._allowUnknownOption = false;538- this._allowExcessArguments = false;538+ this._allowExcessArguments = true;539 this._args = [];540 this.rawArgs = null;541 this._scriptPath = null;542 this._name = name || '';91 unmodified lines634 cmd._helpConfiguration = this._helpConfiguration;635 cmd._exitCallback = this._exitCallback;636 cmd._storeOptionsAsProperties = this._storeOptionsAsProperties;637 cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue;638+ cmd._allowExcessArguments = this._allowExcessArguments;639 cmd._enablePositionalOptions = this._enablePositionalOptions;640 641 cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor642 this.commands.push(cmd);483 unmodified lines1126 return this;1127 };1128 1129 /**1129- * Allow excess arguments on the command line.1130+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.1131 *1132 * @param {Boolean} [allowExcess=true] - if `true` or omitted, no error will be thrown1133 * for excess arguments.1134 */589 unmodified lines1724 this._displayError(1, 'commander.missingArgument', message);1725 };1726 1727 /**1727- * `Option` is missing an argument, but received `flag` or nothing.1728+ * `Option` is missing an argument.1729 *1730 * @param {Option} option1730- * @param {string} [flag]1731 * @api private1732 */1733 1734 optionMissingArgument(option) {466 unmodified linesmodified:Readme.md+5 added-2 removed
481 unmodified lines482 await program.parseAsync(process.argv);483 }484 ```485 486-A command's options and arguments on the command line are validated when the command is used. Any unknown options or unexpected command-arguments will be reported as an error, or you can suppress these checks with `.allowUnknownOption()` and `.allowExcessArguments()`.486+A command's options and arguments on the command line are validated when the command is used. Any unknown options or missing arguments will be reported as an error. You can suppress the unknown option checks with `.allowUnknownOption()`. By default it is not an error to487+pass more arguments than declared, but you can make this an error with `.allowExcessArguments(false)`.488 489 ### Stand-alone executable (sub)commands490 491 When `.command()` is invoked with a description argument, this tells Commander that you're going to use stand-alone executables for subcommands.223 unmodified lines715 program --port=80 arg716 program arg --port=80717 ```718 718-719 By default the option processing shows an error for an unknown option. To have an unknown option treated as an ordinary command-argument and continue looking for options, use `.allowUnknownOption()`. This lets you mix known and unknown options.720 721+By default the argument processing does not display an error for more command-arguments than expected.722+To display an error for excess arguments, use`.allowExcessArguments(false)`.723+724 ### Legacy options as properties 725 726 Before Commander 7, the option values were stored as properties on the command.727 This was convenient to code but the downside was possible clashes with187 unmodified lines