-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpattern.go
58 lines (47 loc) · 1.03 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
package filehealth
import (
"fmt"
"regexp"
"strings"
)
// Pattern is a file matching pattern based on regular expressions.
type Pattern struct {
Expression *regexp.Regexp
}
// UnmarshalText unmarshals the given text as a pattern in p.
func (p *Pattern) UnmarshalText(text []byte) error {
re := string(text)
// Interpret special values as no-ops
if re == "" || re == "_" {
p.Expression = nil
return nil
}
// Compile the pattern
exp, err := compileRegex(re)
if err != nil {
return err
}
p.Expression = exp
return nil
}
// String returns a string representation of the pattern.
func (p Pattern) String() string {
if p.Expression == nil {
return "*"
}
return p.Expression.String()
}
func compileRegex(re string) (*regexp.Regexp, error) {
if re == "" {
return nil, nil
}
// Force case-insensitive matching
if !strings.HasPrefix(re, "(?i)") {
re = "(?i)" + re
}
c, err := regexp.Compile(re)
if err != nil {
return nil, fmt.Errorf("unable to compile regular expression \"%s\": %v", re, err)
}
return c, nil
}