Debian Codegraph @

confmap/internal/encoder.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/go-viper/mapstructure/v2"
10
11 encoder "go.opentelemetry.io/collector/confmap/internal/mapstructure"
12 )
13
14 // EncoderConfig returns a default encoder.EncoderConfig that includes
15 // an EncodeHook that handles both TextMarshaler and Marshaler
16 // interfaces.
17 func EncoderConfig(rawVal any, _ MarshalOptions) *encoder.EncoderConfig {
18 return &encoder.EncoderConfig{
19 EncodeHook: mapstructure.ComposeDecodeHookFunc(
20 encoder.YamlMarshalerHookFunc(),
21 encoder.TextMarshalerHookFunc(),
22 marshalerHookFunc(rawVal),
23 ),
24 }
25 }
26
27 // marshalerHookFunc returns a DecodeHookFuncValue that checks structs that aren't
28 // the original to see if they implement the Marshaler interface.
29 func marshalerHookFunc(orig any) mapstructure.DecodeHookFuncValue {
30 origType := reflect.TypeOf(orig)
31 return safeWrapDecodeHookFunc(func(from, _ reflect.Value) (any, error) {
32 if from.Kind() != reflect.Struct {
33 return from.Interface(), nil
34 }
35
36 // ignore original to avoid infinite loop.
37 if from.Type() == origType && reflect.DeepEqual(from.Interface(), orig) {
38 return from.Interface(), nil
39 }
40 marshaler, ok := from.Interface().(Marshaler)
41 if !ok {
42 return from.Interface(), nil
43 }
44 conf := NewFromStringMap(nil)
45 if err := marshaler.Marshal(conf); err != nil {
46 return nil, err
47 }
48
49 stringMap := conf.ToStringMap()
50 if stringMap == nil {
51 // If conf is still nil after marshaling, we want to encode it as an untyped nil
52 // instead of a map-typed nil. This ensures the value is a proper null value
53 // in the final marshaled output instead of an empty map. We hit this case
54 // when marshaling wrapper structs that have no direct representation
55 // in the marshaled output that aren't tagged with "squash" on the fields
56 // they're used on.
57 return nil, nil
58 }
59 return stringMap, nil
60 })
61 }