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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright (c) 2020 Shivaram Lingamneni <slingamn@cs.stanford.edu>
  2. // released under the MIT license
  3. package utils
  4. import (
  5. "regexp"
  6. "regexp/syntax"
  7. "strings"
  8. )
  9. // yet another glob implementation in Go
  10. func addRegexp(buf *strings.Builder, glob string, submatch bool) (err error) {
  11. for _, r := range glob {
  12. switch r {
  13. case '*':
  14. if submatch {
  15. buf.WriteString("(.*)")
  16. } else {
  17. buf.WriteString(".*")
  18. }
  19. case '?':
  20. if submatch {
  21. buf.WriteString("(.)")
  22. } else {
  23. buf.WriteString(".")
  24. }
  25. case 0xFFFD:
  26. return &syntax.Error{Code: syntax.ErrInvalidUTF8, Expr: glob}
  27. default:
  28. buf.WriteString(regexp.QuoteMeta(string(r)))
  29. }
  30. }
  31. return
  32. }
  33. func CompileGlob(glob string, submatch bool) (result *regexp.Regexp, err error) {
  34. var buf strings.Builder
  35. buf.WriteByte('^')
  36. err = addRegexp(&buf, glob, submatch)
  37. if err != nil {
  38. return
  39. }
  40. buf.WriteByte('$')
  41. return regexp.Compile(buf.String())
  42. }
  43. // Compile a list of globs into a single or-expression that matches any one of them.
  44. // This is used for channel ban/invite/exception lists. It's applicable to k-lines
  45. // but we're not using it there yet.
  46. func CompileMasks(masks []string) (result *regexp.Regexp, err error) {
  47. var buf strings.Builder
  48. buf.WriteString("^(")
  49. for i, mask := range masks {
  50. err = addRegexp(&buf, mask, false)
  51. if err != nil {
  52. return
  53. }
  54. if i != len(masks)-1 {
  55. buf.WriteByte('|')
  56. }
  57. }
  58. buf.WriteString(")$")
  59. return regexp.Compile(buf.String())
  60. }