cobra icon indicating copy to clipboard operation
cobra copied to clipboard

Exclude persistent flag in a sub-command

Open rchaganti opened this issue 2 years ago • 6 comments

When a command has persistent flags defined, these flags get inherited by all sub-commands and nested sub-commands. Let us consider an example.

root

  • --subscription [persistent flag]
  • get
    • config
    • subscription
    • resource
    • support
  • update

The root command has a --subscription flag. This flag is marked as required using the MarkPersistentFlagRequired(). The sub-command get has a few nested sub-commands. I want to exclude the --subscription flag on the get subscription command.

Is this possible? If not, what is the idiomatic way of implementing something like this? I went about creating a persistent flag because most of the sub-commands require the subscription number.

rchaganti avatar Jun 19 '23 07:06 rchaganti

You can try removing the --subscription flag when you are processing the get subscription command.

You can do that in a PreRun function of theget subscription command or, if you want to centralize such logic, in thePersistentPreRun function of the root command.

You can check which command the user has specified through the cmd.CommandPath() function.

This may not work when doing shell completion so you might have to add a bit extra logic for that case.

marckhouzam avatar Jun 19 '23 12:06 marckhouzam

I have a similar issue. But my flag is not marked as required.

How can I hide a persistent flag in one of the commands? I tried the following, but it doesn't work. I still see the flag in the help message.

PreRun: func(cmd *cobra.Command, args []string) {
	cmd.Flags().Lookup("my-flag").Hidden = true
},

maratori avatar Jun 05 '24 13:06 maratori

Try using cmd.InheritedFlags().Lookup() instead of cmd.Flags().Lookup()

marckhouzam avatar Jun 05 '24 16:06 marckhouzam

The result is the same. I still see the flag in --help

maratori avatar Jun 05 '24 19:06 maratori

Oh right. The help code doesn’t run PreRun. I’m not sure what you can do about it. You could try overriding the help function to call PreRun for that command…

marckhouzam avatar Jun 05 '24 21:06 marckhouzam

Here is soluton that works for me, based on answer in https://stackoverflow.com/a/69813652/151641

func NewCmdGet() *cobra.Command {
	cmd := &cobra.Command{
		Use:   "get",
		Short: "Get...",
		Run: func(cmd *cobra.Command, args []string) {
			runCmdGet() // to be defined
		},
	}

	cmd.SetHelpFunc(func(command *cobra.Command, strings []string) {
		command.Flags().MarkHidden("subscription")
		command.Parent().HelpFunc()(command, strings)
	})

	return cmd
}

mloskot avatar Feb 03 '25 02:02 mloskot