Skip to content

Commit

Permalink
fix: improve algo for collating command id (#415)
Browse files Browse the repository at this point in the history
  • Loading branch information
mdonnalley committed May 10, 2022
1 parent 0019cda commit 1a9bfdb
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 7 deletions.
13 changes: 6 additions & 7 deletions src/help/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}

Expand Down
13 changes: 13 additions & 0 deletions test/help/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down

0 comments on commit 1a9bfdb

Please sign in to comment.