Skip to content

fix: match multi-word commands at parse time#173

Open
naveentehrpariya wants to merge 1 commit into
cacjs:mainfrom
naveentehrpariya:fix/multi-word-command-matching
Open

fix: match multi-word commands at parse time#173
naveentehrpariya wants to merge 1 commit into
cacjs:mainfrom
naveentehrpariya:fix/multi-word-command-matching

Conversation

@naveentehrpariya

Copy link
Copy Markdown

Fixes #170.

Problem

A command registered with a multi-word name is shown in --help but never matches while parsing, so matchedCommand is undefined and the action never fires:

const cli = cac('test')
cli.command('creds set <account>', 'set').action(() => {})
cli.command('creds get <account>', 'get').action((account) => {
  console.log('GET', account)
})

cli.parse(['node', 'test', 'creds', 'get', 'foo'])
// nothing runs; cli.matchedCommand === undefined

Cause

Matching compared the command name against only the first positional argument:

const commandName = parsed.args[0]            // 'creds'
if (command.isMatched(commandName)) { ... }   // 'creds get' === 'creds' -> false

The command's name (removeBrackets('creds get <account>')) is 'creds get', so it can never equal a single word.

Fix

Match the command name against as many leading positional arguments as the name has words, and slice off that many args for the command. Single-word commands are unaffected (wordCount === 1 reproduces the previous behaviour).

Tests

Added a multi-word command test asserting the command matches, the remaining args are correct, and the action receives the right value. It fails without this change and passes with it; the full suite (18 tests) is green.

A command registered with a multi-word name such as
`cli.command('creds get <account>')` was listed in `--help` but never
matched while parsing, because matching only compared the command name
against the first positional argument (`parsed.args[0]`, e.g. `creds`)
while the command's name is the full `creds get`. As a result
`matchedCommand` stayed undefined and the action never ran.

Match the command name against as many leading positional arguments as
the name has words, and slice off that many args for the command.

Fixes cacjs#170
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Multi-word commands not matched at parse time (only listed in --help)

1 participant