2017-05-05 08:57:22 -05:00
|
|
|
package complete
|
|
|
|
|
2017-05-05 10:06:31 -05:00
|
|
|
type Commands map[string]Command
|
|
|
|
|
2017-05-05 13:59:10 -05:00
|
|
|
type Flags map[string]Predicate
|
2017-05-05 10:06:31 -05:00
|
|
|
|
2017-05-05 08:57:22 -05:00
|
|
|
type Command struct {
|
2017-05-05 10:06:31 -05:00
|
|
|
Sub Commands
|
|
|
|
Flags Flags
|
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:]
|
|
|
|
|
|
|
|
// if prev has something that needs to follow it,
|
|
|
|
// it is the most relevant completion
|
2017-05-05 13:59:10 -05:00
|
|
|
if predicate, ok := c.Flags[last(args)]; ok && predicate.Expects {
|
|
|
|
return predicate.predict(), 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
|
|
|
}
|
|
|
|
|
|
|
|
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
|
|
|
|
}
|