I'm developing some CLI utility with Cobra. For my RootCmd
I've set up some persistent flags (i.e. flags which also affect all the commands). But some of the commands don't use those flags, so I'd like to make them hidden for these particular commands, so those flags won't be displayed with myutil help mycmd
or myutil mycmd --help
.
The following snippet does the job, but as for me it's a bit ugly and rather hard to maintain:
func init() {
RootCmd.PersistentFlags().StringVar(&someVar, "some-flag", "", "Nothing to see here, move along.")
origHelpFunc := TidalCmd.HelpFunc()
RootCmd.SetHelpFunc(func(cmd *cobra.Command, args []string) {
if cmd.Name() == "no-flags-cmd" || (cmd.Parent() != nil && cmd.Parent().Name() == "no-flags-cmd") {
cmd.Flags().MarkHidden("some-flag")
}
origHelpFunc(cmd, args)
})
}
Is there any better way to hide some global persistent flags for some commands?
Persistent Flags A flag can be 'persistent', meaning that this flag will be available to the command it's assigned to as well as every command under that command. For global flags, assign a flag as a persistent flag on the root.
cobra-cli is a command line program to generate cobra applications and command files. It will bootstrap your application scaffolding to rapidly develop a Cobra-based application. It is the easiest way to incorporate Cobra into your application.
Exceptions should be applied to exception cases.
You should override/set the help function for the command you want the flag to be hidden for instead of your root command. This way you can keep your customized logic packaged with your command and it will help maintaining it.
Example:
mySubCommand := &cobra.Command{
Use: "no-flags-cmd [command]",
Short: "Takes no flags for an argument",
RunE: func(cmd *cobra.Command, args []string) error {
return nil
},
}
mySubCommand.SetHelpFunc(func(command *cobra.Command, strings []string) {
// Hide flag for this command
command.Flags().MarkHidden("some-flag")
// Call parent help func
command.Parent().HelpFunc()(command, strings)
})
rootCmd.AddCommand(mySubCommand)
NOTE: This is just an example. You may need to check and handle any errors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With