You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

glob.go 2.0KB

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