help.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package app
  2. import (
  3. "fmt"
  4. "github.com/fatih/color"
  5. "github.com/spf13/cobra"
  6. "github.com/spf13/pflag"
  7. "strings"
  8. )
  9. const (
  10. flagHelp = "help"
  11. flagHelpShorthand = "h"
  12. )
  13. func helpCommand(name string) *cobra.Command {
  14. return &cobra.Command{
  15. Use: "help [command]",
  16. Short: "Help about any command.",
  17. Long: `Help provides help for any command in the application.
  18. Simply type ` + name + ` help [path to command] for full details.`,
  19. Run: func(c *cobra.Command, args []string) {
  20. cmd, _, e := c.Root().Find(args)
  21. if cmd == nil || e != nil {
  22. c.Printf("Unknown help topic %#q\n", args)
  23. _ = c.Root().Usage()
  24. } else {
  25. cmd.InitDefaultHelpFlag() // make possible 'help' flag to be shown
  26. _ = cmd.Help()
  27. }
  28. },
  29. }
  30. }
  31. func addHelpFlag(name string, fs *pflag.FlagSet) {
  32. fs.BoolP(flagHelp, flagHelpShorthand, false, fmt.Sprintf("Help for %s.", name))
  33. }
  34. func addHelpCommandFlag(usage string, fs *pflag.FlagSet) {
  35. fs.BoolP(
  36. flagHelp,
  37. flagHelpShorthand,
  38. false,
  39. fmt.Sprintf("Help for the %s command.", color.GreenString(strings.Split(usage, " ")[0])),
  40. )
  41. }