-
Notifications
You must be signed in to change notification settings - Fork 2.6k
/
Copy pathparser.go
48 lines (39 loc) · 1.48 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
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package keyvalue // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/stanza/operator/parser/keyvalue"
import (
"context"
"fmt"
"github.com/open-telemetry/opentelemetry-collector-contrib/internal/coreinternal/parseutils"
"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 key value pairs.
type Parser struct {
helper.ParserOperator
delimiter string
pairDelimiter string
}
// Process will parse an entry for key value pairs.
func (p *Parser) Process(ctx context.Context, entry *entry.Entry) error {
return p.ParserOperator.ProcessWith(ctx, entry, p.parse)
}
// parse will parse a value as key values.
func (p *Parser) parse(value any) (any, error) {
switch m := value.(type) {
case string:
return p.parser(m, p.delimiter, p.pairDelimiter)
default:
return nil, fmt.Errorf("type %T cannot be parsed as key value pairs", value)
}
}
func (p *Parser) parser(input string, delimiter string, pairDelimiter string) (map[string]any, error) {
if input == "" {
return nil, fmt.Errorf("parse from field %s is empty", p.ParseFrom.String())
}
pairs, err := parseutils.SplitString(input, pairDelimiter)
if err != nil {
return nil, fmt.Errorf("failed to parse pairs from input: %w", err)
}
return parseutils.ParseKeyValuePairs(pairs, delimiter)
}