1package doublestar
2
3import "path/filepath"
4
5// Validate a pattern. Patterns are validated while they run in Match(),
6// PathMatch(), and Glob(), so, you normally wouldn't need to call this.
7// However, there are cases where this might be useful: for example, if your
8// program allows a user to enter a pattern that you'll run at a later time,
9// you might want to validate it.
10//
11// ValidatePattern assumes your pattern uses '/' as the path separator.
12//
13func ValidatePattern(s string) bool {
14 return doValidatePattern(s, '/')
15}
16
17// Like ValidatePattern, only uses your OS path separator. In other words, use
18// ValidatePattern if you would normally use Match() or Glob(). Use
19// ValidatePathPattern if you would normally use PathMatch(). Keep in mind,
20// Glob() requires '/' separators, even if your OS uses something else.
21//
22func ValidatePathPattern(s string) bool {
23 return doValidatePattern(s, filepath.Separator)
24}
25
26func doValidatePattern(s string, separator rune) bool {
27 altDepth := 0
28 l := len(s)
29VALIDATE:
30 for i := 0; i < l; i++ {
31 switch s[i] {
32 case '\\':
33 if separator != '\\' {
34 // skip the next byte - return false if there is no next byte
35 if i++; i >= l {
36 return false
37 }
38 }
39 continue
40
41 case '[':
42 if i++; i >= l {
43 // class didn't end
44 return false
45 }
46 if s[i] == '^' || s[i] == '!' {
47 i++
48 }
49 if i >= l || s[i] == ']' {
50 // class didn't end or empty character class
51 return false
52 }
53
54 for ; i < l; i++ {
55 if separator != '\\' && s[i] == '\\' {
56 i++
57 } else if s[i] == ']' {
58 // looks good
59 continue VALIDATE
60 }
61 }
62
63 // class didn't end
64 return false
65
66 case '{':
67 altDepth++
68 continue
69
70 case '}':
71 if altDepth == 0 {
72 // alt end without a corresponding start
73 return false
74 }
75 altDepth--
76 continue
77 }
78 }
79
80 // valid as long as all alts are closed
81 return altDepth == 0
82}