move config parsing into a separate module, fix project name

This commit is contained in:
Von Random 2025-02-09 16:06:39 +02:00
parent 0ab510adef
commit d6d8b1a9a6
4 changed files with 46 additions and 25 deletions

View file

@ -1,12 +1,16 @@
package matcher
import (
"os"
"regexp"
"gopkg.in/yaml.v3"
"mechanus.net/pgbot/config"
)
type tokenSpec struct {
Token string `yaml:"token"`
Regex []string `yaml:"regex"`
}
type Matcher struct {
tokens []TokenCompiled
}
@ -16,11 +20,11 @@ type TokenCompiled struct {
regex []*regexp.Regexp
}
func createToken(token string, regexList []string) TokenCompiled {
func createToken(spec tokenSpec) TokenCompiled {
result := new(TokenCompiled)
result.token = token
result.regex = make([]*regexp.Regexp, len(regexList))
for i, regex := range regexList {
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
@ -46,22 +50,14 @@ func (m *Matcher) Tokenize(input string) []string {
return result
}
func InitMatcher(config string) *Matcher {
configData, err := os.ReadFile(config)
if err != nil {
panic(err)
}
var configMap map[string][]string
func InitMatcher(tokenPath string) *Matcher {
var list []tokenSpec
_ = config.Parse(tokenPath, &list)
err = yaml.Unmarshal(configData, &configMap)
if err != nil {
panic(err)
}
tokens := make([]TokenCompiled, 0, len(list))
tokens := make([]TokenCompiled, 0, len(configMap))
for k, v := range configMap {
tokensCompiled := createToken(k, v)
for _, spec := range list {
tokensCompiled := createToken(spec)
tokens = append(tokens, tokensCompiled)
}
result := new(Matcher)