-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
config.go
75 lines (64 loc) · 1.57 KB
/
config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package filter // import "go.opentelemetry.io/collector/filter"
import (
"errors"
"regexp"
)
// Config configures the matching behavior of a Filter.
type Config struct {
Strict string `mapstructure:"strict"`
Regex string `mapstructure:"regexp"`
}
func (c Config) Validate() error {
if c.Strict == "" && c.Regex == "" {
return errors.New("must specify either strict or regex")
}
if c.Strict != "" && c.Regex != "" {
return errors.New("strict and regex cannot be used together")
}
if c.Regex != "" {
_, err := regexp.Compile(c.Regex)
if err != nil {
return err
}
}
return nil
}
type combinedFilter struct {
stricts map[any]struct{}
regexes []*regexp.Regexp
}
// Deprecated: [v0.103.0] This type will be removed in the future.
type CombinedFilter combinedFilter
// CreateFilter creates a Filter out of a set of Config configuration objects.
func CreateFilter(configs []Config) Filter {
cf := &combinedFilter{
stricts: make(map[any]struct{}),
}
for _, config := range configs {
if config.Strict != "" {
cf.stricts[config.Strict] = struct{}{}
}
if config.Regex != "" {
// Validate() call above ensures that the regex is valid.
re := regexp.MustCompile(config.Regex)
cf.regexes = append(cf.regexes, re)
}
}
return cf
}
func (cf *combinedFilter) Matches(toMatch any) bool {
_, ok := cf.stricts[toMatch]
if ok {
return ok
}
if str, ok := toMatch.(string); ok {
for _, re := range cf.regexes {
if re.MatchString(str) {
return true
}
}
}
return false
}