| 1 | package session |
| 2 | |
| 3 | import ( |
| 4 | "regexp" |
| 5 | "sync" |
| 6 | |
| 7 | "github.com/bettercap/readline" |
| 8 | ) |
| 9 | |
| 10 | type CommandHandler struct { |
| 11 | *sync.Mutex |
| 12 | Name string |
| 13 | Description string |
| 14 | Completer *readline.PrefixCompleter |
| 15 | Parser *regexp.Regexp |
| 16 | exec func(args []string, s *Session) error |
| 17 | } |
| 18 | |
| 19 | func NewCommandHandler(name string, expr string, desc string, exec func(args []string, s *Session) error) CommandHandler { |
| 20 | return CommandHandler{ |
| 21 | Mutex: &sync.Mutex{}, |
| 22 | Name: name, |
| 23 | Description: desc, |
| 24 | Completer: nil, |
| 25 | Parser: regexp.MustCompile(expr), |
| 26 | exec: exec, |
| 27 | } |
| 28 | } |
| 29 | |
| 30 | func (h *CommandHandler) Parse(line string) (bool, []string) { |
| 31 | result := h.Parser.FindStringSubmatch(line) |
| 32 | if len(result) == h.Parser.NumSubexp()+1 { |
| 33 | return true, result[1:] |
| 34 | } else { |
| 35 | return false, nil |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | func (h *CommandHandler) Exec(args []string, s *Session) error { |
| 40 | h.Lock() |
| 41 | defer h.Unlock() |
| 42 | return h.exec(args, s) |
| 43 | } |