-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathpattern.go
69 lines (57 loc) · 1.37 KB
/
pattern.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
package gitignore
import (
"path/filepath"
"strings"
)
var Separator = string(filepath.Separator)
type pattern struct {
hasRootPrefix bool
hasDirSuffix bool
pathDepth int
matcher pathMatcher
onlyEqualizedPath bool
}
func newPattern(path string) pattern {
hasRootPrefix := path[0] == '/'
hasDirSuffix := path[len(path)-1] == '/'
var pathDepth int
if !hasRootPrefix {
pathDepth = strings.Count(path, "/")
}
var matcher pathMatcher
matchingPath := strings.Trim(path, "/")
if hasMeta(path) {
matcher = filepathMatcher{path: matchingPath}
} else {
matcher = simpleMatcher{path: matchingPath}
}
return pattern{
hasRootPrefix: hasRootPrefix,
hasDirSuffix: hasDirSuffix,
pathDepth: pathDepth,
matcher: matcher,
}
}
func newPatternForEqualizedPath(path string) pattern {
pattern := newPattern(path)
pattern.onlyEqualizedPath = true
return pattern
}
func (p pattern) match(path string, isDir bool) bool {
if p.hasDirSuffix && !isDir {
return false
}
var targetPath string
if p.hasRootPrefix || p.onlyEqualizedPath {
// absolute pattern or only equalized path mode
targetPath = path
} else {
// relative pattern
targetPath = p.equalizeDepth(path)
}
return p.matcher.match(targetPath)
}
func (p pattern) equalizeDepth(path string) string {
equalizedPath, _ := cutLastN(path, p.pathDepth+1)
return equalizedPath
}