Debian Codegraph @

confmap/internal/merge.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package internal // import "go.opentelemetry.io/collector/confmap/internal"
5
6 import (
7 "reflect"
8
9 "github.com/gobwas/glob"
10 "github.com/knadh/koanf/maps"
11 )
12
13 func mergeAppend(src, dest map[string]any) error {
14 // mergeAppend recursively merges the src map into the dest map (left to right),
15 // modifying and expanding the dest map in the process.
16 // This function does not overwrite component lists, and ensures that the
17 // final value is a name-aware copy of lists from src and dest.
18
19 // Compile the globs once
20 patterns := []string{
21 "service::extensions",
22 "service::**::receivers",
23 "service::**::exporters",
24 }
25 var globs []glob.Glob
26 for _, p := range patterns {
27 if g, err := glob.Compile(p); err == nil {
28 globs = append(globs, g)
29 }
30 }
31
32 // Flatten both source and destination maps
33 srcFlat, _ := maps.Flatten(src, []string{}, KeyDelimiter)
34 destFlat, _ := maps.Flatten(dest, []string{}, KeyDelimiter)
35
36 for sKey, sVal := range srcFlat {
37 if !isMatch(sKey, globs) {
38 continue
39 }
40
41 dVal, dOk := destFlat[sKey]
42 if !dOk {
43 continue // Let maps.Merge handle missing keys
44 }
45
46 srcVal := reflect.ValueOf(sVal)
47 destVal := reflect.ValueOf(dVal)
48
49 // Only merge if the value is a slice or array; let maps.Merge handle other types
50 if srcVal.Kind() == reflect.Slice || srcVal.Kind() == reflect.Array {
51 srcFlat[sKey] = mergeSlice(srcVal, destVal)
52 }
53 }
54
55 // Unflatten and merge
56 mergedSrc := maps.Unflatten(srcFlat, KeyDelimiter)
57 maps.Merge(mergedSrc, dest)
58
59 return nil
60 }
61
62 // isMatch checks if a key matches any glob in the list
63 func isMatch(key string, globs []glob.Glob) bool {
64 for _, g := range globs {
65 if g.Match(key) {
66 return true
67 }
68 }
69 return false
70 }
71
72 func mergeSlice(src, dest reflect.Value) any {
73 slice := reflect.MakeSlice(src.Type(), 0, src.Cap()+dest.Cap())
74 for i := 0; i < dest.Len(); i++ {
75 slice = reflect.Append(slice, dest.Index(i))
76 }
77
78 for i := 0; i < src.Len(); i++ {
79 if isPresent(slice, src.Index(i)) {
80 continue
81 }
82 slice = reflect.Append(slice, src.Index(i))
83 }
84 return slice.Interface()
85 }
86
87 func isPresent(slice, val reflect.Value) bool {
88 for i := 0; i < slice.Len(); i++ {
89 if reflect.DeepEqual(val.Interface(), slice.Index(i).Interface()) {
90 return true
91 }
92 }
93 return false
94 }