Complete subcommands when TraverseChildren is set (#1171)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Complete subcommands when TraverseChildren is true in custom completion The current custom completion logic does not complete subcommands when a local flag is set. This is good unless TraverseChildren is set to true where local flags can be set on parent commands. This commit allows subcommands to be completed if TraverseChildren is set to true on the root cmd. Closes #1170 Signed-off-by: Paul Holzinger <paul.holzinger@web.de> * Complete subcommands when TraverseChildren is true in bash completion The current bash completion logic does not complete subcommands when a local flag is set. There is also a bug where subcommands are sometimes still getting completed. see: #1172 If TraverseChildren is true we should allow subcommands to be completed even if a local flag is set. Closes #1172
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 <paul.holzinger@web.de>
Diff stats
4 files+114 added−13 removed
- other:+114 added−13 removed
Provenance
- Commit
50258f1- Tree
3fc6c70- Author
Luap99 <45212748+Luap99@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
02a0d2f
4 files changed+114 added−13 removed
modified:bash_completions_test.go+25 added
191 unmodified lines192 check(t, output, `two_word_flags+=("-t")`)193 checkOmit(t, output, `two_word_flags+=("--two-w-default")`)194 checkOmit(t, output, `two_word_flags+=("-T")`)195 196+ // check local nonpersistent flag197+ check(t, output, `local_nonpersistent_flags+=("--two")`)198+ check(t, output, `local_nonpersistent_flags+=("--two=")`)199+ check(t, output, `local_nonpersistent_flags+=("-t")`)200+ check(t, output, `local_nonpersistent_flags+=("--two-w-default")`)201+ check(t, output, `local_nonpersistent_flags+=("-T")`)202+203 checkOmit(t, output, deprecatedCmd.Name())204 205 // If available, run shellcheck against the script.206 if err := exec.Command("which", "shellcheck").Run(); err != nil {34 unmodified lines241 if strings.Contains(output, flagName) {242 t.Errorf("expected completion to not include %q flag: Got %v", flagName, output)243 }244 }245+246+func TestBashCompletionTraverseChildren(t *testing.T) {247+ c := &Command{Use: "c", Run: emptyRun, TraverseChildren: true}248+249+ c.Flags().StringP("string-flag", "s", "", "string flag")250+ c.Flags().BoolP("bool-flag", "b", false, "bool flag")251+252+ buf := new(bytes.Buffer)253+ c.GenBashCompletion(buf)254+ output := buf.String()255+256+ // check that local nonpersistent flag are not set since we have TraverseChildren set to true257+ checkOmit(t, output, `local_nonpersistent_flags+=("--string-flag")`)258+ checkOmit(t, output, `local_nonpersistent_flags+=("--string-flag=")`)259+ checkOmit(t, output, `local_nonpersistent_flags+=("-s")`)260+ checkOmit(t, output, `local_nonpersistent_flags+=("--bool-flag")`)261+ checkOmit(t, output, `local_nonpersistent_flags+=("-b")`)262+}modified:bash_completions.go+8 added-4 removed
493 unmodified lines494 }495 496 func writeLocalNonPersistentFlag(buf *bytes.Buffer, flag *pflag.Flag) {497 name := flag.Name498- format := " local_nonpersistent_flags+=(\"--%s"498+ format := " local_nonpersistent_flags+=(\"--%[1]s\")\n"499 if len(flag.NoOptDefVal) == 0 {500- format += "="500+ format += " local_nonpersistent_flags+=(\"--%[1]s=\")\n"501 }502- format += "\")\n"502 buf.WriteString(fmt.Sprintf(format, name))503+ if len(flag.Shorthand) > 0 {504+ buf.WriteString(fmt.Sprintf(" local_nonpersistent_flags+=(\"-%s\")\n", flag.Shorthand))505+ }506 }507 508 // Setup annotations for go completions for registered flags509 func prepareCustomAnnotationsForFlags(cmd *Command) {26 unmodified lines536 writeFlag(buf, flag, cmd)537 if len(flag.Shorthand) > 0 {538 writeShortFlag(buf, flag, cmd)539 }540+ // localNonPersistentFlags are used to stop the completion of subcommands when one is set541+ // if TraverseChildren is true we should allow to complete subcommands538- if localNonPersistentFlags.Lookup(flag.Name) != nil {542+ if localNonPersistentFlags.Lookup(flag.Name) != nil && !cmd.Root().TraverseChildren {543 writeLocalNonPersistentFlag(buf, flag)544 }545 })546 cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {132 unmodified linesmodified:custom_completions_test.go+60 added
137 unmodified lines138 rootCmd := &Command{139 Use: "root",140 Run: emptyRun,141 }142+ rootCmd.Flags().String("localroot", "", "local root flag")143+144 childCmd1 := &Command{145 Use: "childCmd1",146 Short: "First command",147 Args: MinimumNArgs(0),40 unmodified lines188 if output != expected {189 t.Errorf("expected: %q, got: %q", expected, output)190 }191 192+ // Test that sub-command names are completed if a local non-persistent flag is present and TraverseChildren is set to true193+ // set TraverseChildren to true on the root cmd194+ rootCmd.TraverseChildren = true195+196+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "")197+ if err != nil {198+ t.Errorf("Unexpected error: %v", err)199+ }200+ // Reset TraverseChildren for next command201+ rootCmd.TraverseChildren = false202+203+ expected = strings.Join([]string{204+ "childCmd1",205+ "help",206+ ":4",207+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")208+209+ if output != expected {210+ t.Errorf("expected: %q, got: %q", expected, output)211+ }212+213+ // Test that sub-command names from a child cmd are completed if a local non-persistent flag is present214+ // and TraverseChildren is set to true on the root cmd215+ rootCmd.TraverseChildren = true216+217+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "childCmd1", "--nonPersistent", "value", "")218+ if err != nil {219+ t.Errorf("Unexpected error: %v", err)220+ }221+ // Reset TraverseChildren for next command222+ rootCmd.TraverseChildren = false223+ // Reset the flag for the next command224+ nonPersistentFlag.Changed = false225+226+ expected = strings.Join([]string{227+ "childCmd2",228+ ":4",229+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")230+231+ if output != expected {232+ t.Errorf("expected: %q, got: %q", expected, output)233+ }234+235+ // Test that we don't use Traverse when we shouldn't.236+ // This command should not return a completion since the command line is invalid without TraverseChildren.237+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "--localroot", "value", "childCmd1", "")238+ if err != nil {239+ t.Errorf("Unexpected error: %v", err)240+ }241+242+ expected = strings.Join([]string{243+ ":0",244+ "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n")245+246+ if output != expected {247+ t.Errorf("expected: %q, got: %q", expected, output)248+ }249+250 // Test that sub-command names are not completed if a local non-persistent short flag is present251 output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "childCmd1", "-n", "value", "")252 if err != nil {253 t.Errorf("Unexpected error: %v", err)1707 unmodified linesmodified:custom_completions.go+21 added-9 removed
173 unmodified lines174 // should not be part of the list of arguments175 toComplete := args[len(args)-1]176 trimmedArgs := args[:len(args)-1]177 178+ var finalCmd *Command179+ var finalArgs []string180+ var err error181 // Find the real command for which completion must be performed182+ // check if we need to traverse here to parse local flags on parent commands183+ if c.Root().TraverseChildren {184+ finalCmd, finalArgs, err = c.Root().Traverse(trimmedArgs)185+ } else {179- finalCmd, finalArgs, err := c.Root().Find(trimmedArgs)186+ finalCmd, finalArgs, err = c.Root().Find(trimmedArgs)187+ }188 if err != nil {189 // Unable to find the real command. E.g., <program> someInvalidCmd <TAB>190 return c, []string{}, ShellCompDirectiveDefault, fmt.Errorf("Unable to find a command for arguments: %v", trimmedArgs)191 }86 unmodified lines278 279 var completions []string280 directive := ShellCompDirectiveDefault281 if flag == nil {274- // Check if there are any local, non-persistent flags on the command-line282 foundLocalNonPersistentFlag := false283+ // If TraverseChildren is true on the root command we don't check for284+ // local flags because we can use a local flag on a parent command285+ if !finalCmd.Root().TraverseChildren {286+ // Check if there are any local, non-persistent flags on the command-line276- localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()277- finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {278- if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {279- foundLocalNonPersistentFlag = true280- }281- })287+ localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()288+ finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {289+ if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {290+ foundLocalNonPersistentFlag = true291+ }292+ })293+ }294 295 // Complete subcommand names, including the help command296 if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {297 // We only complete sub-commands if:298 // - there are no arguments on the command-line and287- // - there are no local, non-peristent flag on the command-line299+ // - there are no local, non-peristent flag on the command-line or TraverseChildren is true300 for _, subCmd := range finalCmd.Commands() {301 if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {302 if strings.HasPrefix(subCmd.Name(), toComplete) {303 completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))248 unmodified lines