forked from vjeantet/grok
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathgrokpattern.go
62 lines (50 loc) · 1.39 KB
/
grokpattern.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
package grok
import (
"fmt"
"regexp"
"strings"
)
type grokPattern struct {
expression string
typeHints typeHintByKey
}
var (
namedReference = regexp.MustCompile(`%{(\w+(?::\w+(?::\w+)?)?)}`)
)
func newPattern(pattern string, knownPatterns patternMap, namedOnly bool) (*grokPattern, error) {
typeHints := typeHintByKey{}
for _, keys := range namedReference.FindAllStringSubmatch(pattern, -1) {
names := strings.Split(keys[1], ":")
refKey, refAlias := names[0], names[0]
if len(names) > 1 {
refAlias = names[1]
}
// Add type cast information only if type set, and not string
if len(names) == 3 {
if names[2] != "string" {
typeHints[refAlias] = names[2]
}
}
refPattern, patternExists := knownPatterns[refKey]
if !patternExists {
return nil, fmt.Errorf("no pattern found for %%{%s}", refKey)
}
var refExpression string
if !namedOnly || (namedOnly && len(names) > 1) {
refExpression = fmt.Sprintf("(?P<%s>%s)", refAlias, refPattern.expression)
} else {
refExpression = fmt.Sprintf("(%s)", refPattern.expression)
}
// Add new type Informations
for key, typeName := range refPattern.typeHints {
if _, hasTypeHint := typeHints[key]; !hasTypeHint {
typeHints[key] = strings.ToLower(typeName)
}
}
pattern = strings.Replace(pattern, keys[0], refExpression, -1)
}
return &grokPattern{
expression: pattern,
typeHints: typeHints,
}, nil
}