glob.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. // Go over the leading parts and ensure they match.
  26. for i := 0; i < end; i++ {
  27. idx := strings.Index(subj, parts[i])
  28. switch i {
  29. case 0:
  30. // Check the first section. Requires special handling.
  31. if !leadingGlob && idx != 0 {
  32. return false
  33. }
  34. default:
  35. // Check that the middle parts match.
  36. if idx < 0 {
  37. return false
  38. }
  39. }
  40. // Trim evaluated text from subj as we loop over the pattern.
  41. subj = subj[idx+len(parts[i]):]
  42. }
  43. // Reached the last section. Requires special handling.
  44. return trailingGlob || strings.HasSuffix(subj, parts[end])
  45. }