-
Notifications
You must be signed in to change notification settings - Fork 2
/
sglob.go
63 lines (54 loc) · 1.3 KB
/
sglob.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
package fs
import (
"regexp"
"strings"
)
// sglob is a small glob handler
var (
beginRegexp = regexp.MustCompile(`([^/+])/.*\*\.`)
dotEscapeRegexp = regexp.MustCompile(`\.`)
)
const magicStar = "#$~"
type repl struct {
reg *regexp.Regexp
replace string
}
var repls = []repl{
{regexp.MustCompile(`/\*\*/`), `(/|/.+/)`},
{regexp.MustCompile(`\*\*/`), `(|.` + magicStar + `/)`},
{regexp.MustCompile(`/\*\*`), `(|/.` + magicStar + `)`},
{regexp.MustCompile(`\\\*`), `\` + magicStar},
{regexp.MustCompile(`\*`), `([^/]*)`},
}
func CreateSGlob(line string) *regexp.Regexp {
line = strings.TrimRight(line, "\r")
line = strings.TrimSpace(line)
if line == "" {
return nil
}
if beginRegexp.MatchString(line) && line[0] != '/' {
line = "/" + line
}
line = dotEscapeRegexp.ReplaceAllString(line, `\.`)
if strings.HasPrefix(line, "/**/") {
line = line[1:]
}
for _, r := range repls {
line = r.reg.ReplaceAllString(line, r.replace)
}
line = strings.Replace(line, "?", `\?`, -1)
line = strings.Replace(line, magicStar, "*", -1)
var expr = ""
if strings.HasSuffix(line, "/") {
expr = line + "(|.*)$"
} else {
expr = line + "(|/.*)$"
}
if strings.HasPrefix(expr, "/") {
expr = "^(|/)" + expr[1:]
} else {
expr = "^(|.*/)" + expr
}
pattern, _ := regexp.Compile(expr)
return pattern
}