From 40db0840e44f6e09170730e11bcf63a720418fd9 Mon Sep 17 00:00:00 2001 From: Mike Donnalley Date: Wed, 4 May 2022 13:21:42 -0600 Subject: [PATCH] fix: improve algo for collating command id --- src/help/util.ts | 13 ++++++------- test/help/util.test.ts | 13 +++++++++++++ 2 files changed, 19 insertions(+), 7 deletions(-) diff --git a/src/help/util.ts b/src/help/util.ts index 9670ab26b..0c8cacbcd 100644 --- a/src/help/util.ts +++ b/src/help/util.ts @@ -39,28 +39,27 @@ export function template(context: any): (t: string) => string { function collateSpacedCmdIDFromArgs(argv: string[], config: IConfig): string[] { if (argv.length === 1) return argv - const ids = collectUsableIds(config.commandIDs) const findId = (argv: string[]): string | undefined => { + const ids = collectUsableIds(config.commandIDs) + const final: string[] = [] const idPresent = (id: string) => ids.includes(id) const isFlag = (s: string) => s.startsWith('-') const isArgWithValue = (s: string) => s.includes('=') const finalizeId = (s?: string) => s ? [...final, s].join(':') : final.join(':') - const hasSubCommandsWithArgs = () => { + const hasArgs = () => { const id = finalizeId() if (!id) return false - // Get a list of sub commands for the current command id. A command is returned as a subcommand if the `id` starts with the current command id. - // e.g. `foo:bar` is a subcommand of `foo` - const subCommands = config.commands.filter(c => (c.id).startsWith(id)) - return Boolean(subCommands.find(cmd => cmd.strict === false || cmd.args?.length > 0)) + const cmd = config.findCommand(id) + return Boolean(cmd && (cmd.strict === false || cmd.args?.length > 0)) } for (const arg of argv) { if (idPresent(finalizeId(arg))) final.push(arg) // If the parent topic has a command that expects positional arguments, then we cannot // assume that any subsequent string could be part of the command name - else if (isArgWithValue(arg) || isFlag(arg) || hasSubCommandsWithArgs()) break + else if (isArgWithValue(arg) || isFlag(arg) || hasArgs()) break else final.push(arg) } diff --git a/test/help/util.test.ts b/test/help/util.test.ts index 12137e0b2..a6ff3a782 100644 --- a/test/help/util.test.ts +++ b/test/help/util.test.ts @@ -65,6 +65,19 @@ describe('util', () => { expect(actual).to.deep.equal(['foo:ba', '--baz']) }) + test + .stub(Config.prototype, 'collectUsableIds', () => ['foo', 'foo:bar']) + .it('should return standardized id when topic separator is a space and has args and command is misspelled', () => { + config.topicSeparator = ' ' + // @ts-expect-error private member + config._commands.set('foo:bar', { + id: 'foo:bar', + args: [{name: 'first'}], + }) + const actual = standardizeIDFromArgv(['foo', 'ba', 'baz'], config) + expect(actual).to.deep.equal(['foo:ba:baz']) + }) + test .stub(Config.prototype, 'collectUsableIds', () => ['foo', 'foo:bar']) .it('should return standardized id when topic separator is a space and has args', () => {