cobra icon indicating copy to clipboard operation
cobra copied to clipboard

Refactor `HelpFunc()` to have a `DefaultHelpFunc()`

Open m-Bilal opened this issue 3 years ago • 2 comments

Hi folks, the current help function is: https://github.com/spf13/cobra/blob/bf11ab6321f2831be5390fdd71ab0bb2edbd9ed5/command.go#L439-L455

My proposal is to split it into 2 functions, such as:

func (c *Command) HelpFunc() func(*Command, []string) {
	if c.helpFunc != nil {
		return c.helpFunc
	}
	return c.DefaultHelpFunc()
}

func (c *Command) DefaultHelpFunc() func(*Command, []string) {
	if c.HasParent() {
		return c.Parent().HelpFunc()
	}
	return func(c *Command, a []string) {
		c.mergePersistentFlags()
		// The help should be sent to stdout
		// See https://github.com/spf13/cobra/issues/1002
		err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)
		if err != nil {
			c.PrintErrln(err)
		}
	}
}

Basically, Lines 443-454 become a separate function, which is the default behaviour of HelpFunc().

Use case: Recently I was in a situation which required me to change the behaviour of the help function to do some tasks before help output got printed to the terminal. I did not want to change the help output in any way, just do some specific things before it was printed, and I realised that getting the default help behaviour after using SetHelpFunc() is really difficult. It would be nice if there were a DefaultHelpFunc that I could call after my tasks in my custom help function.

I'll be more than happy to raise a PR with the changes if this seems like a reasonable refactor/change.

Thanks for this awesome library!

m-Bilal avatar Jan 02 '23 13:01 m-Bilal

I am just running into this now, I wholeheartedly agree with this proposal! For doing some "pre help" functionality and then just showing the default help, i've been stuck for some time trying to figure it out... btw @m-Bilal did you manage to find out how to do it? I'm quite unsure still...

decentral1se avatar Aug 21 '25 08:08 decentral1se

Related: https://github.com/spf13/cobra/issues/1368 https://github.com/spf13/cobra/issues/702 https://github.com/spf13/cobra/issues/421

decentral1se avatar Aug 21 '25 08:08 decentral1se