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 <andrewssc@vmware.com>
This commit is contained in:
Scott Andrews 2021-07-13 22:35:17 -04:00
parent de187e874d
commit 2a33038c66
2 changed files with 28 additions and 1 deletions

View file

@ -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 {

View file

@ -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) {