command.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package commands
  2. import (
  3. "flag"
  4. )
  5. // CommandFlags is called before help or command execution to parse command line flags.
  6. // It should return a flag.FlagSet instance and a pointer to the struct that will contain parsed flags
  7. type CommandFlags func() (*flag.FlagSet, any)
  8. // CommandCallback is called when your command should execute.
  9. // fs will be a a pointer to the struct provided by Command.Flags callback, if there was one. -h and -help are reserved
  10. // and handled automatically for you.
  11. // a will be any unconsumed arguments, if no Command.Flags was available this will be all the flags passed in.
  12. // w is the writer to use when sending messages back to the client.
  13. // If an error is returned by the callback it is logged locally, the callback should handle messaging errors to the user
  14. // where appropriate
  15. type CommandCallback func(fs any, a []string, w StringWriter) error
  16. type Command struct {
  17. Name Name
  18. ShortDescription string
  19. Help string
  20. Flags CommandFlags
  21. Callback CommandCallback
  22. }
  23. func execCommand(c *Command, args []string, w StringWriter) error {
  24. var (
  25. fl *flag.FlagSet
  26. fs any
  27. )
  28. if c.Flags != nil {
  29. fl, fs = c.Flags()
  30. if fl != nil {
  31. // SetOutput() here in case fl.Parse dumps usage.
  32. fl.SetOutput(w.GetWriter())
  33. err := fl.Parse(args)
  34. if err != nil {
  35. // fl.Parse has dumped error information to the user via the w writer.
  36. return err
  37. }
  38. args = fl.Args()
  39. }
  40. }
  41. return c.Callback(fs, args, w)
  42. }
  43. func checkHelpArgs(args []string) bool {
  44. for _, a := range args {
  45. if a == "-h" || a == "-help" {
  46. return true
  47. }
  48. }
  49. return false
  50. }