-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpattern.go
More file actions
93 lines (80 loc) · 1.63 KB
/
Copy pathpattern.go
File metadata and controls
93 lines (80 loc) · 1.63 KB
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
package mud
import (
"bytes"
"fmt"
"regexp"
"sync"
)
type Pattern string
type result struct {
*regexp.Regexp
err error
}
var pcache struct {
sync.RWMutex
patterns map[Pattern]result
}
func init() {
pcache.patterns = make(map[Pattern]result)
}
func (p Pattern) get() (*regexp.Regexp, error) {
pcache.RLock()
re, ok := pcache.patterns[p]
pcache.RUnlock()
if ok {
return re.Regexp, re.err
}
compiled, err := regexp.Compile(string(p))
pcache.Lock()
pcache.patterns[p] = result{
Regexp: compiled,
err: err,
}
pcache.Unlock()
return compiled, err
}
func (p Pattern) Match(s []byte) bool {
re, err := p.get()
if err != nil {
fmt.Println(err)
return false
}
return re.Match(s)
}
func (p Pattern) Expand(content []byte, template string) string {
re, err := p.get()
if err != nil {
fmt.Println(err)
return ""
}
var result []byte
for _, submatch := range re.FindAllSubmatchIndex(content, -1) {
// Apply the captured submatches to the template and append the output
// to the result.
result = re.Expand(result, []byte(template), content, submatch)
}
return string(result)
}
func (p Pattern) Color(s []byte, color *Color) []byte {
re, err := p.get()
if err != nil {
fmt.Println(err)
return s
}
var parts [][]byte
var prevIndex int
for _, match := range re.FindAllIndex(s, -1) {
prev := s[prevIndex:match[0]]
if len(prev) > 0 {
parts = append(parts, prev)
}
colored := []byte(color.Sprint(string(s[match[0]:match[1]])))
parts = append(parts, colored)
prevIndex = match[1]
}
final := s[prevIndex:]
if len(final) > 0 {
parts = append(parts, final)
}
return bytes.Join(parts, []byte{})
}