/
file_matcher.go
53 lines (46 loc) · 1.03 KB
/
file_matcher.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
package main
import (
"fmt"
"regexp"
"strings"
)
type matcher func(path string) bool
type matchers []matcher
func (m matchers) match(path string) bool {
for _, matcher := range m {
if matcher(path) {
return true
}
}
return false
}
func newFileMatcher(root string, pattern string) matcher {
prepared := regexp.QuoteMeta(pattern)
prepared = strings.ReplaceAll(prepared, "\\*\\*", ".*")
prepared = strings.ReplaceAll(prepared, "\\*", "[^/]*")
starting := ""
if prepared[0] == '/' {
starting = "^"
}
regex := regexp.MustCompile(
fmt.Sprintf(`%s%s(/.+)?$`, starting, prepared))
if root != "" && root[len(root)-1] != '/' {
root += "/"
}
return func(path string) bool {
if strings.Index(path, root) != 0 {
return false
}
if root != "" && root != "/" {
path = path[len(root)-1:]
}
return regex.MatchString(path)
}
}
func newFileMatchers(path string, patterns []string) matchers {
var list matchers
for _, pattern := range patterns {
list = append(list, newFileMatcher(path, pattern))
}
return list
}