-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
func_replace_all_matches.go
85 lines (74 loc) · 2.63 KB
/
func_replace_all_matches.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
// 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"
"go.opentelemetry.io/collector/pdata/pcommon"
"github.com/open-telemetry/opentelemetry-collector-contrib/pkg/ottl"
)
type ReplaceAllMatchesArguments[K any] struct {
Target ottl.PMapGetter[K]
Pattern string
Replacement ottl.StringGetter[K]
Function ottl.Optional[ottl.FunctionGetter[K]]
ReplacementFormat ottl.Optional[ottl.StringGetter[K]]
}
type replaceAllMatchesFuncArgs[K any] struct {
Input ottl.StringGetter[K]
}
func NewReplaceAllMatchesFactory[K any]() ottl.Factory[K] {
return ottl.NewFactory("replace_all_matches", &ReplaceAllMatchesArguments[K]{}, createReplaceAllMatchesFunction[K])
}
func createReplaceAllMatchesFunction[K any](_ ottl.FunctionContext, oArgs ottl.Arguments) (ottl.ExprFunc[K], error) {
args, ok := oArgs.(*ReplaceAllMatchesArguments[K])
if !ok {
return nil, fmt.Errorf("ReplaceAllMatchesFactory args must be of type *ReplaceAllMatchesArguments[K]")
}
return replaceAllMatches(args.Target, args.Pattern, args.Replacement, args.Function, args.ReplacementFormat)
}
func replaceAllMatches[K any](target ottl.PMapGetter[K], pattern string, replacement ottl.StringGetter[K], fn ottl.Optional[ottl.FunctionGetter[K]], replacementFormat ottl.Optional[ottl.StringGetter[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) (any, 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(&replaceAllMatchesFuncArgs[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, err = applyReplaceFormat(ctx, tCtx, replacementFormat, replacementValStr)
if err != nil {
return nil, err
}
}
val.Range(func(_ string, value pcommon.Value) bool {
if glob.Match(value.Str()) {
value.SetStr(replacementVal)
}
return true
})
return nil, nil
}, nil
}