Hide non-user commands from autocomplete output

This PR hides non-user CLI commands from the list of autocomplete
suggestions.
This commit is contained in:
Alex Dadgar
2017-09-08 11:22:42 -07:00
parent 4fb2dce22a
commit ed8f07f324
4 changed files with 49 additions and 12 deletions

View File

@@ -59,8 +59,20 @@ type CLI struct {
// For example, if the key is "foo bar", then to access it our CLI
// must be accessed with "./cli foo bar". See the docs for CLI for
// notes on how this changes some other behavior of the CLI as well.
//
// The factory should be as cheap as possible, ideally only allocating
// a struct. The factory may be called multiple times in the course
// of a command execution and certain events such as help require the
// instantiation of all commands. Expensive initialization should be
// deferred to function calls within the interface implementation.
Commands map[string]CommandFactory
// HiddenCommands is a list of commands that are "hidden". Hidden
// commands are not given to the help function callback and do not
// show up in autocomplete. The values in the slice should be equivalent
// to the keys in the command map.
HiddenCommands []string
// Name defines the name of the CLI.
Name string
@@ -116,6 +128,7 @@ type CLI struct {
autocomplete *complete.Complete
commandTree *radix.Tree
commandNested bool
commandHidden map[string]struct{}
subcommand string
subcommandArgs []string
topFlags []string
@@ -298,6 +311,14 @@ func (c *CLI) init() {
c.HelpWriter = os.Stderr
}
// Build our hidden commands
if len(c.HiddenCommands) > 0 {
c.commandHidden = make(map[string]struct{})
for _, h := range c.HiddenCommands {
c.commandHidden[h] = struct{}{}
}
}
// Build our command tree
c.commandTree = radix.New()
c.commandNested = false
@@ -419,6 +440,11 @@ func (c *CLI) initAutocompleteSub(prefix string) complete.Command {
return false
}
// If the command is hidden, don't record it at all
if _, ok := c.commandHidden[fullKey]; ok {
return false
}
if cmd.Sub == nil {
cmd.Sub = complete.Commands(make(map[string]complete.Command))
}
@@ -566,6 +592,11 @@ func (c *CLI) helpCommands(prefix string) map[string]CommandFactory {
panic("not found: " + k)
}
// If this is a hidden command, don't show it
if _, ok := c.commandHidden[k]; ok {
continue
}
result[k] = raw.(CommandFactory)
}