From c772dd8d154585516ba2094205fdc5ef1ea03c3c Mon Sep 17 00:00:00 2001 From: Paul Holzinger Date: Fri, 2 Jul 2021 11:04:49 +0200 Subject: [PATCH] Fix flag completion The flag completion functions should be stored on their cmd struct and not the root cmd. Using the root cmd does not work when you create the cmd and add flags before you join this cmd struct to your parent command. Fixes #1437 Signed-off-by: Paul Holzinger --- completions.go | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/completions.go b/completions.go index 4687674aa3..26c3509077 100644 --- a/completions.go +++ b/completions.go @@ -101,14 +101,13 @@ func (c *Command) RegisterFlagCompletionFunc(flagName string, f func(cmd *Comman return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName) } - root := c.Root() - if _, exists := root.flagCompletionFunctions[flag]; exists { + if _, exists := c.flagCompletionFunctions[flag]; exists { return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName) } - if root.flagCompletionFunctions == nil { - root.flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){} + if c.flagCompletionFunctions == nil { + c.flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){} } - root.flagCompletionFunctions[flag] = f + c.flagCompletionFunctions[flag] = f return nil } @@ -402,7 +401,7 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi // Find the completion function for the flag or command var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) if flag != nil && flagCompletion { - completionFn = c.Root().flagCompletionFunctions[flag] + completionFn = finalCmd.flagCompletionFunctions[flag] } else { completionFn = finalCmd.ValidArgsFunction }