glob.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package glob
  2. import "strings"
  3. // The character which is treated like a glob
  4. const GLOB = "*"
  5. // Glob will test a string pattern, potentially containing globs, against a
  6. // subject string. The result is a simple true/false, determining whether or
  7. // not the glob pattern matched the subject text.
  8. func Glob(pattern, subj string) bool {
  9. // Empty pattern can only match empty subject
  10. if pattern == "" {
  11. return subj == pattern
  12. }
  13. // If the pattern _is_ a glob, it matches everything
  14. if pattern == GLOB {
  15. return true
  16. }
  17. parts := strings.Split(pattern, GLOB)
  18. if len(parts) == 1 {
  19. // No globs in pattern, so test for equality
  20. return subj == pattern
  21. }
  22. leadingGlob := strings.HasPrefix(pattern, GLOB)
  23. trailingGlob := strings.HasSuffix(pattern, GLOB)
  24. end := len(parts) - 1
  25. for i, part := range parts {
  26. switch i {
  27. case 0:
  28. if leadingGlob {
  29. continue
  30. }
  31. if !strings.HasPrefix(subj, part) {
  32. return false
  33. }
  34. case end:
  35. if len(subj) > 0 {
  36. return trailingGlob || strings.HasSuffix(subj, part)
  37. }
  38. default:
  39. if !strings.Contains(subj, part) {
  40. return false
  41. }
  42. }
  43. // Trim evaluated text from subj as we loop over the pattern.
  44. idx := strings.Index(subj, part) + len(part)
  45. subj = subj[idx:]
  46. }
  47. // All parts of the pattern matched
  48. return true
  49. }