Skip to content
Myr

Fix flag completion (#1438)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Fix flag completion The flag completion functions should not be stored in the root cmd. There is no requirement that the root cmd should be the same when `RegisterFlagCompletionFunc` was called. Storing the flags there does not work when you add the the flags to your cmd struct before you add the cmd to the parent/root cmd. The flags can no longer be found in the rigth place when the completion command is called and thus the flag completion does not work. Also #1423 claims that this would be thread safe but we still have a map which will fail when accessed concurrently. To truly fix this issue use a RWMutex. Fixes #1437 Fixes #1320 Signed-off-by: Paul Holzinger <pholzing@redhat.com> * Fix trailing whitespaces in fish comp scripts

authored by Paul Holzinger · committed by GitHub · parent 07861c8 · Browse files · 5 files+54 added−13 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Signed-off-by: Paul Holzinger <pholzing@redhat.com>

Diff stats

5 files+54 added−13 removed

  • other:+54 added−13 removed

5 files+54 added−13 removed

modified:bash_completions.go+3 added-1 removed
510 unmodified lines
511}512513// Setup annotations for go completions for registered flags514func prepareCustomAnnotationsForFlags(cmd *Command) {515 flagCompletionMutex.RLock()516 defer flagCompletionMutex.RUnlock()515 for flag := range cmd.Root().flagCompletionFunctions {517 for flag := range flagCompletionFunctions {518 // Make sure the completion script calls the __*_go_custom_completion function for519 // every registered flag. We need to do this here (and not when the flag was registered520 // for completion) so that we can know the root command name for the prefix521 // of __<prefix>_go_custom_completion
164 unmodified lines
modified:command.go-3 removed
140 unmodified lines
141 // globNormFunc is the global normalization function142 // that we can use on every pflag set and children commands143 globNormFunc func(f *flag.FlagSet, name string) flag.NormalizedName144145 //flagCompletionFunctions is map of flag completion functions.146 flagCompletionFunctions map[*flag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)147145 // usageFunc is usage func defined by user.146 usageFunc func(*Command) error147 // usageTemplate is usage template defined by user.148 usageTemplate string
1532 unmodified lines
modified:completions_test.go+35 added
1969 unmodified lines
1970 t.Errorf("expected: %q, got: %q", expected, output)1971 }1972}19731974func TestFlagCompletionWorksRootCommandAddedAfterFlags(t *testing.T) {1975 rootCmd := &Command{Use: "root", Run: emptyRun}1976 childCmd := &Command{1977 Use: "child",1978 Run: emptyRun,1979 ValidArgsFunction: func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1980 return []string{"--validarg", "test"}, ShellCompDirectiveDefault1981 },1982 }1983 childCmd.Flags().Bool("bool", false, "test bool flag")1984 childCmd.Flags().String("string", "", "test string flag")1985 _ = childCmd.RegisterFlagCompletionFunc("string", func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {1986 return []string{"myval"}, ShellCompDirectiveDefault1987 })19881989 // Important: This is a test for https://github.com/spf13/cobra/issues/14371990 // Only add the subcommand after RegisterFlagCompletionFunc was called, do not change this order!1991 rootCmd.AddCommand(childCmd)19921993 // Test that flag completion works for the subcmd1994 output, err := executeCommand(rootCmd, ShellCompRequestCmd, "child", "--string", "")1995 if err != nil {1996 t.Errorf("Unexpected error: %v", err)1997 }19981999 expected := strings.Join([]string{2000 "myval",2001 ":0",2002 "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")20032004 if output != expected {2005 t.Errorf("expected: %q, got: %q", expected, output)2006 }2007}20082009func TestFlagCompletionInGoWithDesc(t *testing.T) {2010 rootCmd := &Command{2011 Use: "root",2012 Run: emptyRun,
533 unmodified lines
modified:completions.go+14 added-7 removed
2 unmodified lines
3import (4 "fmt"5 "os"6 "strings"7 "sync"89 "github.com/spf13/pflag"10)11
5 unmodified lines
17 // completion results without their description. It is used by the shell completion scripts.18 ShellCompNoDescRequestCmd = "__completeNoDesc"19)2021// Global map of flag completion functions. Make sure to use flagCompletionMutex before you try to read and write from it.22var flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}2324// lock for reading and writing from flagCompletionFunctions25var flagCompletionMutex = &sync.RWMutex{}2627// ShellCompDirective is a bit map representing the different behaviors the shell28// can be instructed to have once completions have been provided.29type ShellCompDirective int30
75 unmodified lines
106 flag := c.Flag(flagName)107 if flag == nil {108 return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' does not exist", flagName)109 }110 flagCompletionMutex.Lock()111 defer flagCompletionMutex.Unlock()112104 root := c.Root()105 if _, exists := root.flagCompletionFunctions[flag]; exists {113 if _, exists := flagCompletionFunctions[flag]; exists {114 return fmt.Errorf("RegisterFlagCompletionFunc: flag '%s' already registered", flagName)115 }108 if root.flagCompletionFunctions == nil {109 root.flagCompletionFunctions = map[*pflag.Flag]func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective){}110 }111 root.flagCompletionFunctions[flag] = f116 flagCompletionFunctions[flag] = f117 return nil118}119120// Returns a string listing the different directive enabled in the specified parameter
285 unmodified lines
406407 // Find the completion function for the flag or command408 var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)409 if flag != nil && flagCompletion {410 flagCompletionMutex.RLock()405 completionFn = c.Root().flagCompletionFunctions[flag]411 completionFn = flagCompletionFunctions[flag]412 flagCompletionMutex.RUnlock()413 } else {414 completionFn = finalCmd.ValidArgsFunction415 }416 if completionFn != nil {
365 unmodified lines
modified:fish_completions.go+2 added-2 removed
150 unmodified lines
151 # able to check what the actual completion will be.152 # We don't need descriptions anyway since there is only a single153 # real completion which the shell will expand immediately.154 set -l split (string split --max 1 \t $__%[1]s_comp_results[1])155 155156 # Fish won't add a space if the completion ends with any157 # of the following characters: @=/:.,158 set -l lastChar (string sub -s -1 -- $split)159 if not string match -r -q "[@=/:.,]" -- "$lastChar" 159 if not string match -r -q "[@=/:.,]" -- "$lastChar"160 # In other cases, to support the "nospace" directive we trick the shell161 # by outputting an extra, longer completion.162 __%[1]s_debug "Adding second completion to perform nospace directive"163 set --global __%[1]s_comp_results $split[1] $split[1].
56 unmodified lines