本站源代码
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

81 linhas
2.0KB

  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. }
上海开阖软件有限公司 沪ICP备12045867号-1