pgbot-go/matcher/matcher.go

66 lines
1.3 KiB
Go

package matcher
import (
"regexp"
"mechanus.net/pgbot/config"
)
type tokenSpec struct {
Token string `yaml:"token"`
Regex []string `yaml:"regex"`
}
type Matcher struct {
tokens []TokenCompiled
}
type TokenCompiled struct {
token string
regex []*regexp.Regexp
}
func createToken(spec tokenSpec) TokenCompiled {
result := new(TokenCompiled)
result.token = spec.Token
result.regex = make([]*regexp.Regexp, len(spec.Regex))
for i, regex := range spec.Regex {
result.regex[i] = regexp.MustCompile(regex)
}
return *result
}
func (t TokenCompiled) match(input string) (bool, string) {
for _, regex := range t.regex {
if regex.MatchString(input) {
return true, t.token
}
}
return false, ""
}
func (m *Matcher) Tokenize(input string) []string {
result := make([]string, 0, 10)
for _, token := range m.tokens {
ok, matchedToken := token.match(input)
if ok {
result = append(result, matchedToken)
}
}
return result
}
func InitMatcher(tokenPath string) *Matcher {
var list []tokenSpec
_ = config.Parse(tokenPath, &list)
tokens := make([]TokenCompiled, 0, len(list))
for _, spec := range list {
tokensCompiled := createToken(spec)
tokens = append(tokens, tokensCompiled)
}
result := new(Matcher)
result.tokens = tokens
return result
}