Skip to content

DisableFlagParsing not respected by completion logic #1160

@marckhouzam

Description

@marckhouzam

When a command sets DisableFlagParsing=true it requests that Cobra not handle flags but instead pass them directly to the Run functions to let the command handle them itself. However, the completion logic does not do the same. Instead, it attempts to complete flag names even if DisableFlagParsing==true.

The completion logic should instead ignore flags when DisableFlagParsing==true and pass them directly to ValidArgsFunction to let the command handle them itself.

Here is the usecase. helm supports plugins which are loaded at runtime. A plugin supports its own flags of which helm (and consequently Cobra) is not aware. helm registers a command with Cobra to represent the plugin and sets DisableFlagParsing=true to let the plugin itself handle its flags. helm also defines a ValidArgsFunction which calls the plugin in question to perform completion. The problem is that when completing flag names, Cobra attempts to do the completion itself instead of calling ValidArgsFunction, so the plugin is not asked to provide completion for its flags.

Here is a concrete example of the problem.
If we define the following command:

var plugin = &cobra.Command{
	Use:   "plugin",
	Short: "plugin with disable flags",
	ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		cobra.CompDebugln(fmt.Sprintf("ValidArgsFunction called with args %v and toComplete %s\n", args, toComplete), true)
		return nil, cobra.ShellCompDirectiveDefault
	},
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Printf("Run function called with args: %v\n", args)
	},
	DisableFlagParsing: true,
}

then the Run command is properly called:

$ ./testprog plugin --randomflag
Run function called with args: [--randomflag]

but the ValidArgsFunction is not:

$ ./testprog __complete plugin --randomfl
:4
Completion ended with directive: ShellCompDirectiveNoFileComp
# We should have seen the debug printout saying ValidArgsFunction was called

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions