Exclude persistent flag in a sub-command
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.
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.
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
},
Try using cmd.InheritedFlags().Lookup() instead of cmd.Flags().Lookup()
The result is the same. I still see the flag in --help
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…
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
}