This repository has been archived by the owner on Aug 6, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
config.go
71 lines (55 loc) · 1.68 KB
/
config.go
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package pkg
import (
"regexp"
"text/template"
"strings"
"github.com/Masterminds/sprig"
)
type ParsedTemplates map[string]map[ContentRule]*template.Template
type CompiledRegexes map[*regexp.Regexp]string
type ContentRule struct {
Key string `yaml:"key"`
Equals string `yaml:"equals"`
}
type Configuration struct {
Replacements []struct {
Pattern string `yaml:"pattern"`
Replacement string `yaml:"replacement"`
} `yaml:"replacements"`
Rules []struct {
Name string `yaml:"name"`
Description string `yaml:"description"`
Producer string `yaml:"producer"`
Template string `yaml:"template"`
ContentRule ContentRule `yaml:"contentRule"`
} `yaml:"rules"`
ParsedTemplates ParsedTemplates
CompiledRegexes CompiledRegexes
}
// Warmup parses templates and compiles regex
func (c *Configuration) Warmup() error {
c.ParsedTemplates = ParsedTemplates{}
for _, rule := range c.Rules {
// cleanup template.
cleanTemplate := strings.Replace(rule.Template, "\n", " ", -1)
cleanTemplate = strings.Join(strings.Fields(cleanTemplate), " ")
cleanTemplate = strings.Replace(cleanTemplate, "\\\\", "\\", -1)
ruleTemplate, err := template.New(rule.Producer).Funcs(sprig.TxtFuncMap()).Parse(cleanTemplate)
if err != nil {
return err
}
if c.ParsedTemplates[rule.Producer] == nil {
c.ParsedTemplates[rule.Producer] = make(map[ContentRule]*template.Template, 0)
}
c.ParsedTemplates[rule.Producer][rule.ContentRule] = ruleTemplate
}
c.CompiledRegexes = CompiledRegexes{}
for _, r := range c.Replacements {
rxp, err := regexp.Compile(r.Pattern)
if err != nil {
return err
}
c.CompiledRegexes[rxp] = r.Replacement
}
return nil
}