Redo HelpFunc() to work things other than the help subcommand

Today the HelpFunc() seemed to be tailor built for the `help`
subcommand. Which has a rather weird purpose as its `Run` needs to
find the actual command we want to get help about.

Instead make the HelpFunc() for a command be about that command,
rather than having it search for some other command...
This commit is contained in:
Eric Paris 2015-09-01 13:58:55 -04:00
parent 1f92281ffc
commit 27bf24802c
1 changed files with 24 additions and 25 deletions

View File

@ -188,35 +188,24 @@ func (c *Command) UsageFunc() (f func(*Command) error) {
} }
} }
} }
// HelpFunc returns either the function set by SetHelpFunc for this command
// or a parent, or it returns a function which calls c.Help()
func (c *Command) HelpFunc() func(*Command, []string) { func (c *Command) HelpFunc() func(*Command, []string) {
if c.helpFunc != nil { cmd := c
return c.helpFunc for cmd != nil {
if cmd.helpFunc != nil {
return cmd.helpFunc
} }
cmd = cmd.parent
if c.HasParent() {
return c.parent.HelpFunc()
} else {
return func(c *Command, args []string) {
if len(args) == 0 {
// Help called without any topic, calling on root
c.Root().Help()
return
} }
return func(*Command, []string) {
cmd, _, e := c.Root().Find(args) err := c.Help()
if cmd == nil || e != nil {
c.Printf("Unknown help topic %#q.", args)
c.Root().Usage()
} else {
err := cmd.Help()
if err != nil { if err != nil {
c.Println(err) c.Println(err)
} }
} }
} }
}
}
var minUsagePadding int = 25 var minUsagePadding int = 25
@ -620,9 +609,19 @@ func (c *Command) initHelpCmd() {
Short: "Help about any command", Short: "Help about any command",
Long: `Help provides help for any command in the application. Long: `Help provides help for any command in the application.
Simply type ` + c.Name() + ` help [path to command] for full details.`, Simply type ` + c.Name() + ` help [path to command] for full details.`,
Run: c.HelpFunc(),
PersistentPreRun: func(cmd *Command, args []string) {}, PersistentPreRun: func(cmd *Command, args []string) {},
PersistentPostRun: func(cmd *Command, args []string) {}, PersistentPostRun: func(cmd *Command, args []string) {},
Run: func(c *Command, args []string) {
cmd, _, e := c.Root().Find(args)
if cmd == nil || e != nil {
c.Printf("Unknown help topic %#q.", args)
c.Root().Usage()
} else {
helpFunc := cmd.HelpFunc()
helpFunc(cmd, args)
}
},
} }
} }
c.AddCommand(c.helpCommand) c.AddCommand(c.helpCommand)