File: command_handler.go

package info (click to toggle)
bettercap 2.33.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,668 kB
  • sloc: sh: 154; makefile: 76; python: 52; ansic: 9
file content (43 lines) | stat: -rw-r--r-- 924 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package session

import (
	"regexp"
	"sync"

	"github.com/bettercap/readline"
)

type CommandHandler struct {
	*sync.Mutex
	Name        string
	Description string
	Completer   *readline.PrefixCompleter
	Parser      *regexp.Regexp
	exec        func(args []string, s *Session) error
}

func NewCommandHandler(name string, expr string, desc string, exec func(args []string, s *Session) error) CommandHandler {
	return CommandHandler{
		Mutex:       &sync.Mutex{},
		Name:        name,
		Description: desc,
		Completer:   nil,
		Parser:      regexp.MustCompile(expr),
		exec:        exec,
	}
}

func (h *CommandHandler) Parse(line string) (bool, []string) {
	result := h.Parser.FindStringSubmatch(line)
	if len(result) == h.Parser.NumSubexp()+1 {
		return true, result[1:]
	} else {
		return false, nil
	}
}

func (h *CommandHandler) Exec(args []string, s *Session) error {
	h.Lock()
	defer h.Unlock()
	return h.exec(args, s)
}