diff --git a/lib/command.ts b/lib/command.ts index 243786fa3..eea42ded0 100644 --- a/lib/command.ts +++ b/lib/command.ts @@ -263,6 +263,7 @@ export class CommandInstance { if (isCommandBuilderCallback(builder)) { // A function can be provided, which builds // up a yargs chain and possibly returns it. + yargs.getInternalMethods().getUsageInstance().freeze(); const builderOutput = builder( yargs.getInternalMethods().reset(aliases), helpOrVersionSet @@ -284,6 +285,7 @@ export class CommandInstance { } else if (isCommandBuilderOptionDefinitions(builder)) { // as a short hand, an object can instead be provided, specifying // the options that a command takes. + yargs.getInternalMethods().getUsageInstance().freeze(); innerYargs = yargs.getInternalMethods().reset(aliases); Object.keys(commandHandler.builder).forEach(key => { innerYargs.option(key, builder[key]); diff --git a/test/usage.cjs b/test/usage.cjs index 9b4c50ec0..8c7466fb0 100644 --- a/test/usage.cjs +++ b/test/usage.cjs @@ -3991,6 +3991,57 @@ describe('usage tests', () => { ' --arg2 arg2 desc [string]', ]); }); + + // See: https://github.com/yargs/yargs/issues/2291 + it('should display help output for nested default command on failure', () => { + const r = checkUsage(() => + yargs() + .command( + 'root', + 'root command', + y => { + y.command({ + command: 'nested', + desc: 'nested command', + builder: y => { + y.command({ + command: 'deep-a', + aliases: ['$0'], + desc: 'deeply nested default', + builder: noop, + handler: noop, + }).command({ + command: 'deep-b', + desc: 'a deeply nested command', + builder: noop, + handler: noop, + }); + }, + handler: noop, + }); + }, + () => {} + ) + .strict() + .demandCommand() + .parse(['root', 'nested', 'bloop']) + ); + r.errors[0] + .split('\n') + .should.deep.equal([ + 'usage root nested', + '', + 'nested command', + '', + 'Commands:', + ' usage root nested deep-a deeply nested default [default]', + ' usage root nested deep-b a deeply nested command', + '', + 'Options:', + ' --help Show help [boolean]', + ' --version Show version number [boolean]', + ]); + }); }); describe('positional', () => {