Skip to content

Commit

Permalink
feat: support spaced commands
Browse files Browse the repository at this point in the history
also known as nested commands.

Caveats:
  - Avoid declaring parent commands first. eg: "foo" should come after "foo bar"
  - Support for multiple actions per command has been removed
  • Loading branch information
aleclarson committed Feb 10, 2021
1 parent 15e9f80 commit 227835e
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
8 changes: 4 additions & 4 deletions src/CAC.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,15 +185,15 @@ class CAC extends EventEmitter {
for (const command of this.commands) {
const parsed = this.mri(argv.slice(2), command)

const commandName = parsed.args[0]
if (command.isMatched(commandName)) {
if (command.isMatched(parsed.args)) {
shouldParse = false
const parsedInfo = {
...parsed,
args: parsed.args.slice(1),
}
this.setParsedInfo(parsedInfo, command, commandName)
this.emit(`command:${commandName}`, command)
this.setParsedInfo(parsedInfo, command, command.name)
this.emit(`command:${command.name}`, command)
break
}
}

Expand Down
11 changes: 10 additions & 1 deletion src/Command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ class Command {
aliasNames: string[]
/* Parsed command name */
name: string
path: string[]
args: CommandArg[]
commandAction?: (...args: any[]) => any
usageText?: string
Expand All @@ -51,6 +52,7 @@ class Command {
this.options = []
this.aliasNames = []
this.name = removeBrackets(rawName)
this.path = this.name.split(' ')
this.args = findAllBrackets(rawName)
this.examples = []
}
Expand Down Expand Up @@ -107,7 +109,14 @@ class Command {
* Check if a command name is matched by this command
* @param name Command name
*/
isMatched(name: string) {
isMatched(name: string | readonly string[]) {
if (this.path.length > 1) {
if (Array.isArray(name)) {
return this.path.every((part, i) => name[i] === part)
}
} else if (Array.isArray(name)) {
name = name[0]
}
return this.name === name || this.aliasNames.includes(name)
}

Expand Down

0 comments on commit 227835e

Please sign in to comment.