matcher.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2017 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package labels
  14. import (
  15. "fmt"
  16. "regexp"
  17. )
  18. // MatchType is an enum for label matching types.
  19. type MatchType int
  20. // Possible MatchTypes.
  21. const (
  22. MatchEqual MatchType = iota
  23. MatchNotEqual
  24. MatchRegexp
  25. MatchNotRegexp
  26. )
  27. func (m MatchType) String() string {
  28. typeToStr := map[MatchType]string{
  29. MatchEqual: "=",
  30. MatchNotEqual: "!=",
  31. MatchRegexp: "=~",
  32. MatchNotRegexp: "!~",
  33. }
  34. if str, ok := typeToStr[m]; ok {
  35. return str
  36. }
  37. panic("unknown match type")
  38. }
  39. // Matcher models the matching of a label.
  40. type Matcher struct {
  41. Type MatchType
  42. Name string
  43. Value string
  44. re *regexp.Regexp
  45. }
  46. // NewMatcher returns a matcher object.
  47. func NewMatcher(t MatchType, n, v string) (*Matcher, error) {
  48. m := &Matcher{
  49. Type: t,
  50. Name: n,
  51. Value: v,
  52. }
  53. if t == MatchRegexp || t == MatchNotRegexp {
  54. re, err := regexp.Compile("^(?:" + v + ")$")
  55. if err != nil {
  56. return nil, err
  57. }
  58. m.re = re
  59. }
  60. return m, nil
  61. }
  62. func (m *Matcher) String() string {
  63. return fmt.Sprintf("%s%s%q", m.Name, m.Type, m.Value)
  64. }
  65. // Matches returns whether the matcher matches the given string value.
  66. func (m *Matcher) Matches(s string) bool {
  67. switch m.Type {
  68. case MatchEqual:
  69. return s == m.Value
  70. case MatchNotEqual:
  71. return s != m.Value
  72. case MatchRegexp:
  73. return m.re.MatchString(s)
  74. case MatchNotRegexp:
  75. return !m.re.MatchString(s)
  76. }
  77. panic("labels.Matcher.Matches: invalid match type")
  78. }