Add support for custom completions in Go (#1035)
This commit allows programs using Cobra to code their custom completions in Go instead of Bash. The new ValidArgsFunction field is added for commands, similarly to ValidArgs. For flags, the new function Command.RegisterFlagCompletionFunc() is added. When either of the above functions is used, the bash completion script will call the new hidden command '__complete', passing it all command-line arguments. The '__complete' command will call the function specified by Command.ValidArgsFunction or by Command.RegisterFlagCompletionFunc to obtain completions from the program itself. Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
This commit is contained in:
@ -57,6 +57,10 @@ type Command struct {
|
||||
|
||||
// ValidArgs is list of all valid non-flag arguments that are accepted in bash completions
|
||||
ValidArgs []string
|
||||
// ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.
|
||||
// It is a dynamic version of using ValidArgs.
|
||||
// Only one of ValidArgs and ValidArgsFunction can be used for a command.
|
||||
ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, BashCompDirective)
|
||||
|
||||
// Expected arguments
|
||||
Args PositionalArgs
|
||||
@ -911,6 +915,9 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
||||
args = os.Args[1:]
|
||||
}
|
||||
|
||||
// initialize the hidden command to be used for bash completion
|
||||
c.initCompleteCmd(args)
|
||||
|
||||
var flags []string
|
||||
if c.TraverseChildren {
|
||||
cmd, flags, err = c.Traverse(args)
|
||||
|
Reference in New Issue
Block a user