Allow un-ambiguous prefixes for command names

This commit is contained in:
Kovid Goyal 2022-09-30 15:37:03 +05:30
parent 75ead358a2
commit 0dab006733
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
3 changed files with 33 additions and 5 deletions

View File

@ -333,6 +333,18 @@ func (self *Command) FindSubCommand(name string) *Command {
return nil
}
func (self *Command) FindSubCommands(prefix string) []*Command {
c := self.FindSubCommand(prefix)
if c != nil {
return []*Command{c}
}
ans := make([]*Command, 0, 4)
for _, g := range self.SubCommandGroups {
ans = g.FindSubCommands(prefix, ans)
}
return ans
}
func (self *Command) AddOptionGroup(title string) *OptionGroup {
for _, g := range self.OptionGroups {
if g.Title == title {

View File

@ -48,6 +48,15 @@ func (self *CommandGroup) FindSubCommand(name string) *Command {
return nil
}
func (self *CommandGroup) FindSubCommands(prefix string, matches []*Command) []*Command {
for _, c := range self.SubCommands {
if strings.HasPrefix(c.Name, prefix) {
matches = append(matches, c)
}
}
return matches
}
type OptionGroup struct {
Options []*Option
Title string

View File

@ -95,13 +95,20 @@ func (self *Command) parse_args(ctx *Context, args []string) error {
options_allowed = false
}
if self.HasSubCommands() {
sc := self.FindSubCommand(arg)
if sc == nil {
if !self.SubCommandIsOptional {
possible_cmds := self.FindSubCommands(arg)
if len(possible_cmds) == 1 {
return possible_cmds[0].parse_args(ctx, args_to_parse)
}
if !self.SubCommandIsOptional {
if len(possible_cmds) == 0 {
return &ParseError{Message: fmt.Sprintf(":yellow:`%s` is not a known subcommand for :emph:`%s`. Use --help to get a list of valid subcommands.", arg, self.Name)}
}
} else {
return sc.parse_args(ctx, args_to_parse)
cn := make([]string, len(possible_cmds))
for i, x := range possible_cmds {
cn[i] = x.Name
}
return &ParseError{Message: fmt.Sprintf(
":yellow:`%s` is not a known subcommand for :emph:`%s`. Did you mean:\n\t%s", arg, self.Name, strings.Join(cn, "\n\t"))}
}
}
self.Args = append(self.Args, arg)