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?