-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathfunc_replace_all_matches.go
54 lines (44 loc) · 1.64 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
// 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] `ottlarg:"0"`
Pattern string `ottlarg:"1"`
Replacement string `ottlarg:"2"`
}
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)
}
func replaceAllMatches[K any](target ottl.PMapGetter[K], pattern string, replacement string) (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)
if err != nil {
return nil, err
}
val.Range(func(key string, value pcommon.Value) bool {
if glob.Match(value.Str()) {
value.SetStr(replacement)
}
return true
})
return nil, nil
}, nil
}