-
Notifications
You must be signed in to change notification settings - Fork 14
/
filter.go
92 lines (71 loc) · 2 KB
/
filter.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
package pitreos
import (
"fmt"
"regexp"
)
type Filter interface {
Match(relativePath string) bool
}
type FilterFunc func(relativePath string) bool
func (f FilterFunc) Match(relativePath string) bool {
return f(relativePath)
}
var AllFileFilter = FilterFunc(func(relativePath string) bool { return true })
type IncludeThanExcludeFilter struct {
includeFilter *regexp.Regexp
excludeFilter *regexp.Regexp
}
func NewIncludeThanExcludeFilter(includeFilter, excludeFilter string) (*IncludeThanExcludeFilter, error) {
includeFilterRegex, err := filterStringPatternToRegexp(includeFilter)
if err != nil {
return nil, err
}
excludeFilterRegex, err := filterStringPatternToRegexp(excludeFilter)
if err != nil {
return nil, err
}
return &IncludeThanExcludeFilter{
includeFilter: includeFilterRegex,
excludeFilter: excludeFilterRegex,
}, nil
}
func MustNewIncludeThanExcludeFilter(includeFilter, excludeFilter string) *IncludeThanExcludeFilter {
filter, err := NewIncludeThanExcludeFilter(includeFilter, excludeFilter)
if err != nil {
panic(fmt.Errorf("unable to create include than exclude filter: %s", err))
}
return filter
}
func filterStringPatternToRegexp(pattern string) (*regexp.Regexp, error) {
if pattern == "" {
return nil, nil
}
regex, err := regexp.Compile(pattern)
if err != nil {
return nil, err
}
return regex, nil
}
func (f *IncludeThanExcludeFilter) Match(relativePath string) bool {
if f.includeFilter != nil && !f.includeFilter.MatchString(relativePath) {
return false
}
if f.excludeFilter != nil && f.excludeFilter.MatchString(relativePath) {
return false
}
return true
}
func (f *IncludeThanExcludeFilter) String() string {
if f == nil || (f.includeFilter != nil && f.excludeFilter == nil) {
return "<No filtering>"
}
include := "'All'"
if f.includeFilter != nil {
include = f.includeFilter.String()
}
exclude := "'Nothing'"
if f.includeFilter != nil {
include = f.includeFilter.String()
}
return fmt.Sprintf("[Included %s, Excluded %s]", include, exclude)
}