-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathfilter.go
More file actions
115 lines (98 loc) · 2.36 KB
/
filter.go
File metadata and controls
115 lines (98 loc) · 2.36 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"os"
"strings"
)
type Filter struct {
dirNames []string
suffixes []string
patterns []string
}
func NewFilter(excludeRuleStr string, useGitIgnore bool) *Filter {
f := &Filter{}
if excludeRuleStr == "" && !useGitIgnore {
return f
}
if excludeRuleStr != "" {
rules := strings.Split(excludeRuleStr, ",")
for _, rule := range rules {
rule = strings.TrimSpace(rule)
if strings.HasSuffix(rule, "/") {
f.dirNames = append(f.dirNames, strings.TrimSuffix(rule, "/"))
} else if strings.HasPrefix(rule, ".") {
f.suffixes = append(f.suffixes, rule)
} else {
f.patterns = append(f.patterns, rule)
}
}
}
if useGitIgnore {
f.loadGitIgnorePatterns()
}
return f
}
func (f *Filter) loadGitIgnorePatterns() {
gitignorePath := ".gitignore"
content, err := os.ReadFile(gitignorePath)
if err != nil {
// If .gitignore doesn't exist, ignore the error
return
}
lines := strings.Split(string(content), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
// Skip empty lines and comments
if line == "" || strings.HasPrefix(line, "#") {
continue
}
// Process .gitignore rules
if strings.HasSuffix(line, "/") {
// Directory rule
f.dirNames = append(f.dirNames, strings.TrimSuffix(line, "/"))
} else if strings.HasPrefix(line, "*.") {
// Suffix rule, e.g. *.txt
f.suffixes = append(f.suffixes, strings.TrimPrefix(line, "*"))
} else {
// Other patterns
f.patterns = append(f.patterns, line)
}
}
}
func (f *Filter) shouldExclude(name string, isDir bool, path string) bool {
if isDir {
for _, dir := range f.dirNames {
if matchPattern(name, dir) {
return true
}
}
} else {
for _, suffix := range f.suffixes {
if strings.HasSuffix(name, suffix) {
return true
}
}
}
// Check general patterns
for _, pattern := range f.patterns {
if matchPattern(path, pattern) || matchPattern(name, pattern) {
return true
}
}
return false
}
// Simple wildcard matching
func matchPattern(name, pattern string) bool {
// Exact match
if pattern == name {
return true
}
// Prefix star: *suffix
if strings.HasPrefix(pattern, "*") && strings.HasSuffix(name, strings.TrimPrefix(pattern, "*")) {
return true
}
// Suffix star: prefix*
if strings.HasSuffix(pattern, "*") && strings.HasPrefix(name, strings.TrimSuffix(pattern, "*")) {
return true
}
return false
}