command.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // This file is subject to a 1-clause BSD license.
  2. // Its contents can be found in the enclosed LICENSE file.
  3. package cmd
  4. import (
  5. "regexp"
  6. "strings"
  7. "github.com/monkeybird/autimaat/irc"
  8. )
  9. // Handler defines a callbck function for a registered command.
  10. type Handler func(irc.ResponseWriter, *irc.Request, ParamList)
  11. // Command defines a single command which can be called by IRC users.
  12. type Command struct {
  13. Name string // Name by which the command is called.
  14. Handler Handler // Command handler.
  15. Params []Param // Command parameter list.
  16. Restricted bool // Command may only be run by authorized users.
  17. }
  18. // newCommand creates a new command.
  19. func newCommand(name string, restricted bool, handler Handler) *Command {
  20. c := new(Command)
  21. c.Name = strings.ToLower(name)
  22. c.Restricted = restricted
  23. c.Handler = handler
  24. return c
  25. }
  26. // Add adds a new command parameter.
  27. func (c *Command) Add(name string, required bool, pattern *regexp.Regexp) *Command {
  28. var p Param
  29. p.Name = strings.ToLower(name)
  30. p.Required = required
  31. if pattern == nil {
  32. p.Pattern = RegAny
  33. } else {
  34. p.Pattern = pattern
  35. }
  36. c.Params = append(c.Params, p)
  37. return c
  38. }
  39. // RequiredParamCount returns the amunt of required parameters for this command.
  40. func (c *Command) RequiredParamCount() int {
  41. var count int
  42. for i := range c.Params {
  43. if c.Params[i].Required {
  44. count++
  45. }
  46. }
  47. return count
  48. }