-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
func_replace_match.go
88 lines (77 loc) · 2.38 KB
/
func_replace_match.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
76
77
78
79
80
81
82
83
84
85
86
87
88
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
package ottlfuncs // import "github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl/ottlfuncs"
import (
"context"
"fmt"
"github.com/gobwas/glob"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
)
type ReplaceMatchArguments[K any] struct {
Target ottl.GetSetter[K]
Pattern string
Replacement ottl.StringGetter[K]
Function ottl.Optional[ottl.FunctionGetter[K]]
}
type replaceMatchFuncArgs[K any] struct {
Input ottl.StringGetter[K]
}
func NewReplaceMatchFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("replace_match", &ReplaceMatchArguments[K]{}, createReplaceMatchFunction[K])
}
func createReplaceMatchFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) {
args, ok := oArgs.(*ReplaceMatchArguments[K])
if !ok {
return nil, fmt.Errorf("ReplaceMatchFactory args must be of type *ReplaceMatchArguments[K]")
}
return replaceMatch(args.Target, args.Pattern, args.Replacement, args.Function)
}
func replaceMatch[K any](target ottl.GetSetter[K], pattern string, replacement ottl.StringGetter[K], fn ottl.Optional[ottl.FunctionGetter[K]]) (ottl.ExprFunc[K], error) {
glob, err := glob.Compile(pattern)
if err != nil {
return nil, fmt.Errorf("the pattern supplied to replace_match is not a valid pattern: %w", err)
}
return func(ctx context.Context, tCtx K) (interface{}, error) {
val, err := target.Get(ctx, tCtx)
var replacementVal string
if err != nil {
return nil, err
}
if fn.IsEmpty() {
replacementVal, err = replacement.Get(ctx, tCtx)
if err != nil {
return nil, err
}
} else {
fnVal := fn.Get()
replacementExpr, errNew := fnVal.Get(&replaceMatchFuncArgs[K]{Input: replacement})
if errNew != nil {
return nil, errNew
}
replacementValRaw, errNew := replacementExpr.Eval(ctx, tCtx)
if errNew != nil {
return nil, errNew
}
replacementValStr, ok := replacementValRaw.(string)
if !ok {
return nil, fmt.Errorf("replacement value is not a string")
}
replacementVal = replacementValStr
}
if err != nil {
return nil, err
}
if val == nil {
return nil, nil
}
if valStr, ok := val.(string); ok {
if glob.Match(valStr) {
err = target.Set(ctx, tCtx, replacementVal)
if err != nil {
return nil, err
}
}
}
return nil, nil
}, nil
}