1 package glob 2 3 import ( 4 "github.com/gobwas/glob/compiler" 5 "github.com/gobwas/glob/syntax" 6 ) 7 8 // Glob represents compiled glob pattern. 9 type Glob interface { 10 Match(string) bool 11 } 12 13 // Compile creates Glob for given pattern and strings (if any present after pattern) as separators. 14 // The pattern syntax is: 15 // 16 // pattern: 17 // { term } 18 // 19 // term: 20 // `*` matches any sequence of non-separator characters 21 // `**` matches any sequence of characters 22 // `?` matches any single non-separator character 23 // `[` [ `!` ] { character-range } `]` 24 // character class (must be non-empty) 25 // `{` pattern-list `}` 26 // pattern alternatives 27 // c matches character c (c != `*`, `**`, `?`, `\`, `[`, `{`, `}`) 28 // `\` c matches character c 29 // 30 // character-range: 31 // c matches character c (c != `\\`, `-`, `]`) 32 // `\` c matches character c 33 // lo `-` hi matches character c for lo <= c <= hi 34 // 35 // pattern-list: 36 // pattern { `,` pattern } 37 // comma-separated (without spaces) patterns 38 // 39 func Compile(pattern string, separators ...rune) (Glob, error) { 40 ast, err := syntax.Parse(pattern) 41 if err != nil { 42 return nil, err 43 } 44 45 matcher, err := compiler.Compile(ast, separators) 46 if err != nil { 47 return nil, err 48 } 49 50 return matcher, nil 51 } 52 53 // MustCompile is the same as Compile, except that if Compile returns error, this will panic 54 func MustCompile(pattern string, separators ...rune) Glob { 55 g, err := Compile(pattern, separators...) 56 if err != nil { 57 panic(err) 58 } 59 60 return g 61 } 62 63 // QuoteMeta returns a string that quotes all glob pattern meta characters 64 // inside the argument text; For example, QuoteMeta(`{foo*}`) returns `\[foo\*\]`. 65 func QuoteMeta(s string) string { 66 b := make([]byte, 2*len(s)) 67 68 // a byte loop is correct because all meta characters are ASCII 69 j := 0 70 for i := 0; i < len(s); i++ { 71 if syntax.Special(s[i]) { 72 b[j] = '\\' 73 j++ 74 } 75 b[j] = s[i] 76 j++ 77 } 78 79 return string(b[0:j]) 80 } 81