-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
regexfile.go
98 lines (86 loc) · 1.54 KB
/
regexfile.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"context"
"io"
"regexp"
"runtime/debug"
"strings"
)
func ReadRegex(
ctx context.Context,
logger Logger,
path string,
) []*regexp.Regexp {
var regex []*regexp.Regexp
count := 0
bodies := ReadFiles(ctx, logger, ReadDirectory(ctx, logger, path, ".regex"))
for {
select {
case <-ctx.Done():
return regex
case body, ok := <-bodies:
if !ok {
return regex
}
regex = append(regex, parseRegexFile(ctx, logger, body)...)
count++
}
}
}
func parseRegexFile(
ctx context.Context,
logger Logger,
body io.ReadCloser,
) []*regexp.Regexp {
regex := []*regexp.Regexp{}
defer func() {
r := recover()
if r != nil {
logger.Errorw(
"panic",
"error", r,
"stack", debug.Stack(),
)
}
}()
data, err := io.ReadAll(body)
body.Close()
if err != nil {
logger.Errorw(
"failed to read regex file body",
"error", err,
)
return nil
}
lines := strings.Split(string(data), "\n")
for _, line := range lines {
select {
case <-ctx.Done():
return regex
default:
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
// Remove the comment from the line
commentIndex := strings.Index(line, "#")
if commentIndex != -1 {
line = strings.TrimSpace(
line[:commentIndex],
)
}
var r *regexp.Regexp
r, err = regexp.Compile(line)
if err != nil {
logger.Errorw(
"failed to compile regex",
"regex", line,
"error", err,
)
continue
}
regex = append(regex, r)
}
}
return regex
}