complete/command.go

67 lines
1.5 KiB
Go
Raw Normal View History

2017-05-05 08:57:22 -05:00
package complete
type Commands map[string]Command
type Flags map[string]Predicate
2017-05-05 08:57:22 -05:00
type Command struct {
Name string
Sub Commands
Flags Flags
Args Predicate
2017-05-05 08:57:22 -05:00
}
// options returns all available complete options for the given command
// args are all except the last command line arguments relevant to the command
2017-05-05 13:57:21 -05:00
func (c *Command) options(args []string) (options []Option, only bool) {
2017-05-05 08:57:22 -05:00
// remove the first argument, which is the command name
args = args[1:]
last := last(args)
2017-05-05 08:57:22 -05:00
// if prev has something that needs to follow it,
// it is the most relevant completion
if predicate, ok := c.Flags[last]; ok && predicate != nil {
return predicate.predict(last), true
2017-05-05 08:57:22 -05:00
}
sub, options, only := c.searchSub(args)
if only {
return
}
// if no subcommand was entered in any of the args, add the
// subcommands as complete options.
if sub == "" {
options = append(options, c.subCommands()...)
}
// add global available complete options
for flag := range c.Flags {
2017-05-05 13:57:21 -05:00
options = append(options, Arg(flag))
2017-05-05 08:57:22 -05:00
}
// add additional expected argument of the command
options = append(options, c.Args.predict(last)...)
2017-05-05 08:57:22 -05:00
return
}
2017-05-05 13:57:21 -05:00
func (c *Command) searchSub(args []string) (sub string, all []Option, only bool) {
2017-05-05 08:57:22 -05:00
for i, arg := range args {
if cmd, ok := c.Sub[arg]; ok {
sub = arg
all, only = cmd.options(args[i:])
return
}
}
return "", nil, false
}
2017-05-05 13:57:21 -05:00
func (c *Command) subCommands() []Option {
subs := make([]Option, 0, len(c.Sub))
2017-05-05 08:57:22 -05:00
for sub := range c.Sub {
2017-05-05 13:57:21 -05:00
subs = append(subs, Arg(sub))
2017-05-05 08:57:22 -05:00
}
return subs
}