-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathparser.go
63 lines (52 loc) · 1.38 KB
/
parser.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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package regex // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/parser/regex"
import (
"context"
"fmt"
"regexp"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/entry"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/helper"
)
// Parser is an operator that parses regex in an entry.
type Parser struct {
helper.ParserOperator
regexp *regexp.Regexp
cache cache
}
func (p *Parser) Stop() error {
if p.cache != nil {
p.cache.stop()
}
return nil
}
// Process will parse an entry for regex.
func (p *Parser) Process(ctx context.Context, entry *entry.Entry) error {
return p.ParserOperator.ProcessWith(ctx, entry, p.parse)
}
// parse will parse a value using the supplied regex.
func (p *Parser) parse(value any) (any, error) {
var raw string
switch m := value.(type) {
case string:
raw = m
default:
return nil, fmt.Errorf("type '%T' cannot be parsed as regex", value)
}
return p.match(raw)
}
func (p *Parser) match(value string) (any, error) {
if p.cache != nil {
if x := p.cache.get(value); x != nil {
return x, nil
}
}
parsedValues, err := helper.MatchValues(value, p.regexp)
if err != nil {
return nil, err
}
if p.cache != nil {
p.cache.add(value, parsedValues)
}
return parsedValues, nil
}