From 2a33038c66c88a4d29b5d44f9db79af603e0ac89 Mon Sep 17 00:00:00 2001 From: Scott Andrews Date: Tue, 13 Jul 2021 22:35:17 -0400 Subject: [PATCH] Skip flag completion for commands with disabled flag parsing When a command disabled flag parsing, the shell completion for that command should not offer flags. This allows completions for args to be processed like normal. This behavior is particularly useful for invoking a CLI plugin that has its own sub commands, arguments, flags, and completion rules. Signed-off-by: Scott Andrews --- completions.go | 5 +++++ completions_test.go | 24 +++++++++++++++++++++++- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/completions.go b/completions.go index b849b9c8..683deacc 100644 --- a/completions.go +++ b/completions.go @@ -266,6 +266,11 @@ func (c *Command) getCompletions(args []string) (*Command, []string, ShellCompDi } } + // Skip flag completion for commands that have disabled flag parsing + if finalCmd.DisableFlagParsing && flagCompletion { + flagCompletion = false + } + if flag != nil && flagCompletion { // Check if we are completing a flag value subject to annotations if validExts, present := flag.Annotations[BashCompFilenameExt]; present { diff --git a/completions_test.go b/completions_test.go index 70c455af..cbdad7e6 100644 --- a/completions_test.go +++ b/completions_test.go @@ -482,11 +482,18 @@ func TestFlagNameCompletionInGo(t *testing.T) { Use: "childCmd", Run: emptyRun, } - rootCmd.AddCommand(childCmd) + disabledFlagsCmd := &Command{ + Use: "disabledFlags", + Short: "A command with flag parsing disabled", + DisableFlagParsing: true, + Run: emptyRun, + } + rootCmd.AddCommand(childCmd, disabledFlagsCmd) rootCmd.Flags().IntP("first", "f", -1, "first flag") rootCmd.PersistentFlags().BoolP("second", "s", false, "second flag") childCmd.Flags().String("subFlag", "", "sub flag") + disabledFlagsCmd.Flags().String("disabledFlag", "", "disabled flag") // Test that flag names are not shown if the user has not given the '-' prefix output, err := executeCommand(rootCmd, ShellCompNoDescRequestCmd, "") @@ -497,6 +504,7 @@ func TestFlagNameCompletionInGo(t *testing.T) { expected := strings.Join([]string{ "childCmd", "completion", + "disabledFlags", "help", ":4", "Completion ended with directive: ShellCompDirectiveNoFileComp", ""}, "\n") @@ -554,6 +562,20 @@ func TestFlagNameCompletionInGo(t *testing.T) { if output != expected { t.Errorf("expected: %q, got: %q", expected, output) } + + // Test that flag names are not completed when flag parsing is disabled + output, err = executeCommand(rootCmd, ShellCompNoDescRequestCmd, "disabledFlags", "-") + if err != nil { + t.Errorf("Unexpected error: %v", err) + } + + expected = strings.Join([]string{ + ":0", + "Completion ended with directive: ShellCompDirectiveDefault", ""}, "\n") + + if output != expected { + t.Errorf("expected: %q, got: %q", expected, output) + } } func TestFlagNameCompletionInGoWithDesc(t *testing.T) {