-
Notifications
You must be signed in to change notification settings - Fork 199
/
common.go
108 lines (89 loc) · 2.13 KB
/
common.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
99
100
101
102
103
104
105
106
107
108
package path_matcher
import (
"path/filepath"
"strings"
"github.com/bmatcuk/doublestar"
"github.com/werf/werf/pkg/util"
)
func matchGlobs(pathPart string, globs []string) (inProgressGlobs []string, matchedGlobs []string) {
for _, glob := range globs {
inProgressGlob, matchedGlob := matchGlob(pathPart, glob)
if inProgressGlob != "" {
inProgressGlobs = append(inProgressGlobs, inProgressGlob)
} else if matchedGlob != "" {
matchedGlobs = append(matchedGlobs, matchedGlob)
}
}
return
}
func matchGlob(pathPart string, glob string) (inProgressGlob, matchedGlob string) {
globParts := util.SplitFilepath(glob)
isMatched, err := doublestar.PathMatch(globParts[0], pathPart)
if err != nil {
panic(err)
}
if !isMatched {
return "", ""
}
if strings.Contains(globParts[0], "**") {
return glob, ""
}
if len(globParts) > 1 {
return filepath.Join(globParts[1:]...), ""
}
return "", glob
}
func hasUniversalGlob(globs []string) bool {
for _, glob := range globs {
if glob == "." {
return true
}
if trimRightAsterisks(glob) == "" {
return true
}
}
return false
}
func isAnyPatternMatched(path string, patterns []string) bool {
for _, pattern := range patterns {
if isPathMatched(path, pattern) {
return true
}
}
return false
}
func isPathMatched(filePath, glob string) bool {
// The glob as-is.
// The glob without asterisks on the right (path/*/dir/**/*, path/*/dir/**, path/*/dir/*/*/** -> path/*/dir).
// The previous glob with the universal part `**/*` (path/*/dir/**/*).
for _, g := range []string{
glob,
trimRightAsterisks(glob),
filepath.Join(trimRightAsterisks(glob), "**", "*"),
} {
matched, err := doublestar.PathMatch(g, filePath)
if err != nil {
panic(err)
}
if matched {
return true
}
}
return false
}
func trimRightAsterisks(pattern string) string {
return strings.TrimRight(pattern, "*\\/")
}
func formatPaths(paths []string) []string {
var result []string
for _, path := range paths {
result = append(result, formatPath(path))
}
return result
}
func formatPath(path string) string {
if path == "" || path == "." {
return ""
}
return filepath.Clean(path)
}