Skip to content

Commit

Permalink
cobra: fix registering prediction for persistent flag
Browse files Browse the repository at this point in the history
  • Loading branch information
coxley committed Oct 17, 2024
1 parent 138fb75 commit 2229ad5
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
6 changes: 5 additions & 1 deletion cmpcobra/completer.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cmpcobra

import (
"cmp"
"fmt"
"strings"

Expand All @@ -26,7 +27,10 @@ var (
// command "factories" to share that value around. The registered values are unique
// pointers so overwriting won't happen.
func RegisterFlag(cmd *cobra.Command, name string, predictor predict.Predictor) {
flag := cmd.Flags().Lookup(name)
local := cmd.Flags().Lookup(name)
persistent := cmd.PersistentFlags().Lookup(name)

flag := cmp.Or(local, persistent)
if flag == nil {
panic(fmt.Sprintf("flag %q doesn't exist on %q", name, cmd.Name()))
}
Expand Down
13 changes: 13 additions & 0 deletions cmpcobra/completer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,19 @@ func TestQuery(t *testing.T) {
cmptest.Assert(t, New(cmd), "query -c <TAB> -c colX table2", []string{})
}

func TestPersistentRegister(t *testing.T) {
root := &cobra.Command{
Use: "root",
}
root.PersistentFlags().String("env", "", "")
pred := predict.Func(func(args args.Args) []string {
return []string{"foo"}
})
RegisterFlag(root, "env", pred)

cmptest.Assert(t, New(root), "root --env <TAB>", []string{"foo"})
}

func TestPersistent(t *testing.T) {
// Test that the child command can get access to persistent flags without looking
// at the root
Expand Down

0 comments on commit 2229ad5

Please sign in to comment.