DisableFlagParsing must disable flag completion (#1161)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
When a command has set DisableFlagParsing=true, it means Cobra should not be handling flags for that command but should let the command handle them itself. In fact, Cobra normally won't have been told at all about flags for this command. Not knowing about the flags of the command also implies that Cobra cannot perform flag completion as it does not have the necessary info. This commit still tries to do flag name completion, but when DisableFlagParsing==true, it continues on so that ValidArgsFunction will be called; this allows the program to handle completion for its own flags when DisableFlagParsing==true.
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Signed-off-by: Marc Khouzam <marc.khouzam@montreal.ca>
Diff stats
3 files+145 added−62 removed
- other:+145 added−62 removed
Provenance
- Commit
d2c0cb3- Tree
26f7a1e- Author
Marc Khouzam <marc.khouzam@montreal.ca>- Committer
GitHub <noreply@github.com>- Parent
c1973d3
3 files changed+145 added−62 removed
modified:bash_completions.go+13 added-1 removed
191 unmodified lines192 eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"193 fi194 fi195 fi196+197+ if [[ -z "${flag_parsing_disabled}" ]]; then198+ # If flag parsing is enabled, we have completed the flags and can return.199+ # If flag parsing is disabled, we may not know all (or any) of the flags, so we fallthrough200+ # to possibly call handle_go_custom_completion.196- return 0;201+ return 0;202+ fi203 ;;204 esac205 206 # check if we are handling a flag with special work handling192 unmodified lines399 __%[1]s_init_completion -n "=" || return400 fi401 402 local c=0403+ local flag_parsing_disabled=404 local flags=()405 local two_word_flags=()406 local local_nonpersistent_flags=()407 local flags_with_completion=()133 unmodified lines541 flags_with_completion=()542 flags_completion=()543 544 `)545+546+ if cmd.DisableFlagParsing {547+ WriteStringAndCheck(buf, " flag_parsing_disabled=1\n")548+ }549+550 localNonPersistentFlags := cmd.LocalNonPersistentFlags()551 cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {552 if nonCompletableFlag(flag) {553 return144 unmodified linesmodified:completions_test.go+61 added
2541 unmodified lines2542 if output != expected {2543 t.Errorf("expected: %q, got: %q", expected, output)2544 }2545 }2546+2547+func TestCompleteWithDisableFlagParsing(t *testing.T) {2548+2549+ flagValidArgs := func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective) {2550+ return []string{"--flag", "-f"}, ShellCompDirectiveNoFileComp2551+ }2552+2553+ rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}2554+ childCmd := &Command{2555+ Use: "child",2556+ Run: emptyRun,2557+ DisableFlagParsing: true,2558+ ValidArgsFunction: flagValidArgs,2559+ }2560+ rootCmd.AddCommand(childCmd)2561+2562+ rootCmd.PersistentFlags().StringP("persistent", "p", "", "persistent flag")2563+ childCmd.Flags().StringP("nonPersistent", "n", "", "non-persistent flag")2564+2565+ // Test that when DisableFlagParsing==true, ValidArgsFunction is called to complete flag names,2566+ // after Cobra tried to complete the flags it knows about.2567+ childCmd.DisableFlagParsing = true2568+ output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child", "-")2569+ if err != nil {2570+ t.Errorf("Unexpected error: %v", err)2571+ }2572+2573+ expected := strings.Join([]string{2574+ "--persistent",2575+ "-p",2576+ "--nonPersistent",2577+ "-n",2578+ "--flag",2579+ "-f",2580+ ":4",2581+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")2582+2583+ if output != expected {2584+ t.Errorf("expected: %q, got: %q", expected, output)2585+ }2586+2587+ // Test that when DisableFlagParsing==false, Cobra completes the flags itself and ValidArgsFunction is not called2588+ childCmd.DisableFlagParsing = false2589+ output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "child", "-")2590+ if err != nil {2591+ t.Errorf("Unexpected error: %v", err)2592+ }2593+2594+ // Cobra was not told of any flags, so it returns nothing2595+ expected = strings.Join([]string{2596+ "--persistent",2597+ "-p",2598+ "--nonPersistent",2599+ "-n",2600+ ":4",2601+ "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n")2602+2603+ if output != expected {2604+ t.Errorf("expected: %q, got: %q", expected, output)2605+ }2606+}modified:completions.go+71 added-61 removed
264 unmodified lines265 return finalCmd, []string{}, ShellCompDirectiveDefault, flagErr266 }267 }268 269+ // We only remove the flags from the arguments if DisableFlagParsing is not set.270+ // This is important for commands which have requested to do their own flag completion.271+ if !finalCmd.DisableFlagParsing {272+ finalArgs = finalCmd.Flags().Args()273+ }274+275 if flag != nil && flagCompletion {276 // Check if we are completing a flag value subject to annotations277 if validExts, present := flag.Annotations[BashCompFilenameExt]; present {278 if len(validExts) != 0 {16 unmodified lines295 return finalCmd, []string{}, ShellCompDirectiveFilterDirs, nil296 }297 }298 299+ var completions []string300+ var directive ShellCompDirective301+302+ // Note that we want to perform flagname completion even if finalCmd.DisableFlagParsing==true;303+ // doing this allows for completion of persistant flag names even for commands that disable flag parsing.304+ //305 // When doing completion of a flag name, as soon as an argument starts with306 // a '-' we know it is a flag. We cannot use isFlagArg() here as it requires307 // the flag name to be complete308 if flag == nil && len(toComplete) > 0 && toComplete[0] == '-' && !strings.Contains(toComplete, "=") && flagCompletion {297- var completions []string298-309 // First check for required flags310 completions = completeRequireFlags(finalCmd, toComplete)311 312 // If we have not found any required flags, only then can we show regular flags18 unmodified lines331 doCompleteFlags(flag)332 })333 }334 325- directive := ShellCompDirectiveNoFileComp335+ directive = ShellCompDirectiveNoFileComp336 if len(completions) == 1 && strings.HasSuffix(completions[0], "=") {337 // If there is a single completion, the shell usually adds a space338 // after the completion. We don't want that if the flag ends with an =339 directive = ShellCompDirectiveNoSpace340 }331- return finalCmd, completions, directive, nil332- }341 334- // We only remove the flags from the arguments if DisableFlagParsing is not set.335- // This is important for commands which have requested to do their own flag completion.336- if !finalCmd.DisableFlagParsing {337- finalArgs = finalCmd.Flags().Args()338- }339-340- var completions []string341- directive := ShellCompDirectiveDefault342- if flag == nil {343- foundLocalNonPersistentFlag := false344- // If TraverseChildren is true on the root command we don't check for345- // local flags because we can use a local flag on a parent command346- if !finalCmd.Root().TraverseChildren {347- // Check if there are any local, non-persistent flags on the command-line348- localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()349- finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {350- if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {351- foundLocalNonPersistentFlag = true352- }353- })342+ if !finalCmd.DisableFlagParsing {343+ // If DisableFlagParsing==false, we have completed the flags as known by Cobra;344+ // we can return what we found.345+ // If DisableFlagParsing==true, Cobra may not be aware of all flags, so we346+ // let the logic continue to see if ValidArgsFunction needs to be called.347+ return finalCmd, completions, directive, nil348 }349+ } else {350+ directive = ShellCompDirectiveDefault351+ if flag == nil {352+ foundLocalNonPersistentFlag := false353+ // If TraverseChildren is true on the root command we don't check for354+ // local flags because we can use a local flag on a parent command355+ if !finalCmd.Root().TraverseChildren {356+ // Check if there are any local, non-persistent flags on the command-line357+ localNonPersistentFlags := finalCmd.LocalNonPersistentFlags()358+ finalCmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {359+ if localNonPersistentFlags.Lookup(flag.Name) != nil && flag.Changed {360+ foundLocalNonPersistentFlag = true361+ }362+ })363+ }364 356- // Complete subcommand names, including the help command357- if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {358- // We only complete sub-commands if:359- // - there are no arguments on the command-line and360- // - there are no local, non-persistent flags on the command-line or TraverseChildren is true361- for _, subCmd := range finalCmd.Commands() {362- if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {363- if strings.HasPrefix(subCmd.Name(), toComplete) {364- completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))365+ // Complete subcommand names, including the help command366+ if len(finalArgs) == 0 && !foundLocalNonPersistentFlag {367+ // We only complete sub-commands if:368+ // - there are no arguments on the command-line and369+ // - there are no local, non-persistent flags on the command-line or TraverseChildren is true370+ for _, subCmd := range finalCmd.Commands() {371+ if subCmd.IsAvailableCommand() || subCmd == finalCmd.helpCommand {372+ if strings.HasPrefix(subCmd.Name(), toComplete) {373+ completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))374+ }375+ directive = ShellCompDirectiveNoFileComp376 }366- directive = ShellCompDirectiveNoFileComp377 }378 }369- }379 371- // Complete required flags even without the '-' prefix372- completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)380+ // Complete required flags even without the '-' prefix381+ completions = append(completions, completeRequireFlags(finalCmd, toComplete)...)382 374- // Always complete ValidArgs, even if we are completing a subcommand name.375- // This is for commands that have both subcommands and ValidArgs.376- if len(finalCmd.ValidArgs) > 0 {377- if len(finalArgs) == 0 {378- // ValidArgs are only for the first argument379- for _, validArg := range finalCmd.ValidArgs {380- if strings.HasPrefix(validArg, toComplete) {381- completions = append(completions, validArg)383+ // Always complete ValidArgs, even if we are completing a subcommand name.384+ // This is for commands that have both subcommands and ValidArgs.385+ if len(finalCmd.ValidArgs) > 0 {386+ if len(finalArgs) == 0 {387+ // ValidArgs are only for the first argument388+ for _, validArg := range finalCmd.ValidArgs {389+ if strings.HasPrefix(validArg, toComplete) {390+ completions = append(completions, validArg)391+ }392 }383- }384- directive = ShellCompDirectiveNoFileComp393+ directive = ShellCompDirectiveNoFileComp394 386- // If no completions were found within commands or ValidArgs,387- // see if there are any ArgAliases that should be completed.388- if len(completions) == 0 {389- for _, argAlias := range finalCmd.ArgAliases {390- if strings.HasPrefix(argAlias, toComplete) {391- completions = append(completions, argAlias)395+ // If no completions were found within commands or ValidArgs,396+ // see if there are any ArgAliases that should be completed.397+ if len(completions) == 0 {398+ for _, argAlias := range finalCmd.ArgAliases {399+ if strings.HasPrefix(argAlias, toComplete) {400+ completions = append(completions, argAlias)401+ }402 }403 }404 }405+406+ // If there are ValidArgs specified (even if they don't match), we stop completion.407+ // Only one of ValidArgs or ValidArgsFunction can be used for a single command.408+ return finalCmd, completions, directive, nil409 }410 397- // If there are ValidArgs specified (even if they don't match), we stop completion.398- // Only one of ValidArgs or ValidArgsFunction can be used for a single command.399- return finalCmd, completions, directive, nil411+ // Let the logic continue so as to add any ValidArgsFunction completions,412+ // even if we already found sub-commands.413+ // This is for commands that have subcommands but also specify a ValidArgsFunction.414 }401-402- // Let the logic continue so as to add any ValidArgsFunction completions,403- // even if we already found sub-commands.404- // This is for commands that have subcommands but also specify a ValidArgsFunction.415 }416 417 // Find the completion function for the flag or command418 var completionFn func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)373 unmodified lines