diff --git a/lib/command.js b/lib/command.js index 590a271dd..e4b5d1699 100644 --- a/lib/command.js +++ b/lib/command.js @@ -272,6 +272,8 @@ class Command extends EventEmitter { this.commands.push(cmd); cmd.parent = this; + cmd._checkForBrokenPassThrough(); + return this; } @@ -735,12 +737,20 @@ Expecting one of '${allowedValues.join("', '")}'`); */ passThroughOptions(passThrough = true) { this._passThroughOptions = !!passThrough; - if (!!this.parent && passThrough && !this.parent._enablePositionalOptions) { - throw new Error('passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)'); - } + this._checkForBrokenPassThrough(); return this; } + /** + * @api private + */ + + _checkForBrokenPassThrough() { + if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) { + throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`); + } + } + /** * Whether to store option values as properties on command object, * or store separately (specify false). In both cases the option values can be accessed using .opts(). diff --git a/tests/command.positionalOptions.test.js b/tests/command.positionalOptions.test.js index d130b7835..82011e136 100644 --- a/tests/command.positionalOptions.test.js +++ b/tests/command.positionalOptions.test.js @@ -362,13 +362,25 @@ describe('program with action handler and positionalOptions and subcommand', () // ------------------------------------------------------------------------------ -test('when program not positional and turn on passthrough in subcommand then error', () => { - const program = new commander.Command(); - const sub = program.command('sub'); +describe('broken passThrough', () => { + test('when program not positional and turn on passThroughOptions in subcommand then error', () => { + const program = new commander.Command(); + const sub = program.command('sub'); + + expect(() => { + sub.passThroughOptions(); + }).toThrow(); + }); - expect(() => { - sub.passThroughOptions(); - }).toThrow(); + test('when program not positional and add subcommand with passThroughOptions then error', () => { + const program = new commander.Command(); + const sub = new commander.Command('sub') + .passThroughOptions(); + + expect(() => { + program.addCommand(sub); + }).toThrow(); + }); }); // ------------------------------------------------------------------------------