| 1 |
// Copyright The OpenTelemetry Authors |
| 2 |
// SPDX-License-Identifier: Apache-2.0 |
| 3 |
|
| 4 |
package mapstructure // import "go.opentelemetry.io/collector/confmap/internal/mapstructure" |
| 5 |
|
| 6 |
import ( |
| 7 |
"encoding" |
| 8 |
"errors" |
| 9 |
"fmt" |
| 10 |
"maps" |
| 11 |
"reflect" |
| 12 |
"strings" |
| 13 |
|
| 14 |
"github.com/go-viper/mapstructure/v2" |
| 15 |
yaml "go.yaml.in/yaml/v3" |
| 16 |
) |
| 17 |
|
| 18 |
const ( |
| 19 |
tagNameMapStructure = "mapstructure" |
| 20 |
optionSeparator = "," |
| 21 |
optionOmitEmpty = "omitempty" |
| 22 |
optionSquash = "squash" |
| 23 |
optionRemain = "remain" |
| 24 |
optionSkip = "-" |
| 25 |
) |
| 26 |
|
| 27 |
var errNonStringEncodedKey = errors.New("non string-encoded key") |
| 28 |
|
| 29 |
// tagInfo stores the mapstructure tag details. |
| 30 |
type tagInfo struct { |
| 31 |
name string |
| 32 |
omitEmpty bool |
| 33 |
squash bool |
| 34 |
} |
| 35 |
|
| 36 |
// An Encoder takes structured data and converts it into an |
| 37 |
// interface following the mapstructure tags. |
| 38 |
type Encoder struct { |
| 39 |
config *EncoderConfig |
| 40 |
} |
| 41 |
|
| 42 |
// EncoderConfig is the configuration used to create a new encoder. |
| 43 |
type EncoderConfig struct { |
| 44 |
// EncodeHook, if set, is a way to provide custom encoding. It |
| 45 |
// will be called before structs and primitive types. |
| 46 |
EncodeHook mapstructure.DecodeHookFunc |
| 47 |
} |
| 48 |
|
| 49 |
// New returns a new encoder for the configuration. |
| 50 |
func New(cfg *EncoderConfig) *Encoder { |
| 51 |
return &Encoder{config: cfg} |
| 52 |
} |
| 53 |
|
| 54 |
// Encode takes the input and uses reflection to encode it to |
| 55 |
// an interface based on the mapstructure spec. |
| 56 |
func (e *Encoder) Encode(input any) (any, error) { |
| 57 |
return e.encode(reflect.ValueOf(input)) |
| 58 |
} |
| 59 |
|
| 60 |
// encode processes the value based on the reflect.Kind. |
| 61 |
func (e *Encoder) encode(value reflect.Value) (any, error) { |
| 62 |
if value.IsValid() { |
| 63 |
switch value.Kind() { |
| 64 |
case reflect.Interface, reflect.Ptr: |
| 65 |
return e.encode(value.Elem()) |
| 66 |
case reflect.Map: |
| 67 |
return e.encodeMap(value) |
| 68 |
case reflect.Slice: |
| 69 |
return e.encodeSlice(value) |
| 70 |
case reflect.Struct: |
| 71 |
return e.encodeStruct(value) |
| 72 |
default: |
| 73 |
return e.encodeHook(value) |
| 74 |
} |
| 75 |
} |
| 76 |
return nil, nil |
| 77 |
} |
| 78 |
|
| 79 |
// encodeHook calls the EncodeHook in the EncoderConfig with the value passed in. |
| 80 |
// This is called before processing structs and for primitive data types. |
| 81 |
func (e *Encoder) encodeHook(value reflect.Value) (any, error) { |
| 82 |
if e.config != nil && e.config.EncodeHook != nil { |
| 83 |
out, err := mapstructure.DecodeHookExec(e.config.EncodeHook, value, value) |
| 84 |
if err != nil { |
| 85 |
return nil, fmt.Errorf("error running encode hook: %w", err) |
| 86 |
} |
| 87 |
return out, nil |
| 88 |
} |
| 89 |
return value.Interface(), nil |
| 90 |
} |
| 91 |
|
| 92 |
// encodeStruct encodes the struct by iterating over the fields, getting the |
| 93 |
// mapstructure tagInfo for each exported field, and encoding the value. |
| 94 |
func (e *Encoder) encodeStruct(value reflect.Value) (any, error) { |
| 95 |
if value.Kind() != reflect.Struct { |
| 96 |
return nil, &reflect.ValueError{ |
| 97 |
Method: "encodeStruct", |
| 98 |
Kind: value.Kind(), |
| 99 |
} |
| 100 |
} |
| 101 |
out, err := e.encodeHook(value) |
| 102 |
if err != nil { |
| 103 |
return nil, err |
| 104 |
} |
| 105 |
value = reflect.ValueOf(out) |
| 106 |
// if the output of encodeHook is no longer a struct, |
| 107 |
// call encode against it. |
| 108 |
if value.Kind() != reflect.Struct { |
| 109 |
return e.encode(value) |
| 110 |
} |
| 111 |
result := make(map[string]any) |
| 112 |
for i := 0; i < value.NumField(); i++ { |
| 113 |
field := value.Field(i) |
| 114 |
if field.CanInterface() { |
| 115 |
info := getTagInfo(value.Type().Field(i)) |
| 116 |
if (info.omitEmpty && field.IsZero()) || info.name == optionSkip { |
| 117 |
continue |
| 118 |
} |
| 119 |
encoded, err := e.encode(field) |
| 120 |
if err != nil { |
| 121 |
return nil, fmt.Errorf("error encoding field %q: %w", info.name, err) |
| 122 |
} |
| 123 |
if info.squash { |
| 124 |
if m, ok := encoded.(map[string]any); ok { |
| 125 |
maps.Copy(result, m) |
| 126 |
} |
| 127 |
} else { |
| 128 |
result[info.name] = encoded |
| 129 |
} |
| 130 |
} |
| 131 |
} |
| 132 |
return result, nil |
| 133 |
} |
| 134 |
|
| 135 |
// encodeSlice iterates over the slice and encodes each of the elements. |
| 136 |
func (e *Encoder) encodeSlice(value reflect.Value) (any, error) { |
| 137 |
if value.Kind() != reflect.Slice { |
| 138 |
return nil, &reflect.ValueError{ |
| 139 |
Method: "encodeSlice", |
| 140 |
Kind: value.Kind(), |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
if value.IsNil() { |
| 145 |
return []any(nil), nil |
| 146 |
} |
| 147 |
|
| 148 |
result := make([]any, value.Len()) |
| 149 |
for i := 0; i < value.Len(); i++ { |
| 150 |
var err error |
| 151 |
if result[i], err = e.encode(value.Index(i)); err != nil { |
| 152 |
return nil, fmt.Errorf("error encoding element in slice at index %d: %w", i, err) |
| 153 |
} |
| 154 |
} |
| 155 |
return result, nil |
| 156 |
} |
| 157 |
|
| 158 |
// encodeMap encodes a map by encoding the key and value. Returns errNonStringEncodedKey |
| 159 |
// if the key is not encoded into a string. |
| 160 |
func (e *Encoder) encodeMap(value reflect.Value) (any, error) { |
| 161 |
if value.Kind() != reflect.Map { |
| 162 |
return nil, &reflect.ValueError{ |
| 163 |
Method: "encodeMap", |
| 164 |
Kind: value.Kind(), |
| 165 |
} |
| 166 |
} |
| 167 |
|
| 168 |
var result map[string]any |
| 169 |
if value.Len() > 0 || !value.IsNil() { |
| 170 |
result = make(map[string]any) |
| 171 |
} |
| 172 |
|
| 173 |
iterator := value.MapRange() |
| 174 |
for iterator.Next() { |
| 175 |
encoded, err := e.encode(iterator.Key()) |
| 176 |
if err != nil { |
| 177 |
return nil, fmt.Errorf("error encoding key: %w", err) |
| 178 |
} |
| 179 |
|
| 180 |
v := reflect.ValueOf(encoded) |
| 181 |
var key string |
| 182 |
|
| 183 |
switch v.Kind() { |
| 184 |
case reflect.String: |
| 185 |
key = v.String() |
| 186 |
default: |
| 187 |
return nil, fmt.Errorf("%w, key: %q, kind: %v, type: %T", errNonStringEncodedKey, iterator.Key().Interface(), iterator.Key().Kind(), encoded) |
| 188 |
} |
| 189 |
|
| 190 |
if _, ok := result[key]; ok { |
| 191 |
return nil, fmt.Errorf("duplicate key %q while encoding", key) |
| 192 |
} |
| 193 |
if result[key], err = e.encode(iterator.Value()); err != nil { |
| 194 |
return nil, fmt.Errorf("error encoding map value for key %q: %w", key, err) |
| 195 |
} |
| 196 |
} |
| 197 |
return result, nil |
| 198 |
} |
| 199 |
|
| 200 |
// getTagInfo looks up the mapstructure tag and uses that if available. |
| 201 |
// Uses the lowercase field if not found. Checks for omitempty and squash. |
| 202 |
func getTagInfo(field reflect.StructField) *tagInfo { |
| 203 |
info := tagInfo{} |
| 204 |
if tag, ok := field.Tag.Lookup(tagNameMapStructure); ok { |
| 205 |
options := strings.Split(tag, optionSeparator) |
| 206 |
info.name = options[0] |
| 207 |
if len(options) > 1 { |
| 208 |
for _, option := range options[1:] { |
| 209 |
switch option { |
| 210 |
case optionOmitEmpty: |
| 211 |
info.omitEmpty = true |
| 212 |
case optionSquash, optionRemain: |
| 213 |
info.squash = true |
| 214 |
} |
| 215 |
} |
| 216 |
} |
| 217 |
} else { |
| 218 |
info.name = strings.ToLower(field.Name) |
| 219 |
} |
| 220 |
return &info |
| 221 |
} |
| 222 |
|
| 223 |
// TextMarshalerHookFunc returns a DecodeHookFuncValue that checks |
| 224 |
// for the encoding.TextMarshaler interface and calls the MarshalText |
| 225 |
// function if found. |
| 226 |
func TextMarshalerHookFunc() mapstructure.DecodeHookFuncValue { |
| 227 |
return func(from, _ reflect.Value) (any, error) { |
| 228 |
marshaler, ok := from.Interface().(encoding.TextMarshaler) |
| 229 |
if !ok { |
| 230 |
return from.Interface(), nil |
| 231 |
} |
| 232 |
out, err := marshaler.MarshalText() |
| 233 |
if err != nil { |
| 234 |
return nil, err |
| 235 |
} |
| 236 |
return string(out), nil |
| 237 |
} |
| 238 |
} |
| 239 |
|
| 240 |
// YamlMarshalerHookFunc returns a DecodeHookFuncValue that checks for structs |
| 241 |
// that have yaml tags but no mapstructure tags. If found, it will convert the struct |
| 242 |
// to map[string]any using the yaml package, which respects the yaml tags. Ultimately, |
| 243 |
// this allows mapstructure to later marshal the map[string]any in a generic way. |
| 244 |
func YamlMarshalerHookFunc() mapstructure.DecodeHookFuncValue { |
| 245 |
return func(from, _ reflect.Value) (any, error) { |
| 246 |
if from.Kind() == reflect.Struct { |
| 247 |
for i := 0; i < from.NumField(); i++ { |
| 248 |
if _, ok := from.Type().Field(i).Tag.Lookup("mapstructure"); ok { |
| 249 |
// The struct has at least one mapstructure tag so don't do anything. |
| 250 |
return from.Interface(), nil |
| 251 |
} |
| 252 |
|
| 253 |
if _, ok := from.Type().Field(i).Tag.Lookup("yaml"); ok { |
| 254 |
// The struct has at least one yaml tag, so convert it to map[string]any using yaml. |
| 255 |
yamlBytes, err := yaml.Marshal(from.Interface()) |
| 256 |
if err != nil { |
| 257 |
return nil, err |
| 258 |
} |
| 259 |
var m map[string]any |
| 260 |
err = yaml.Unmarshal(yamlBytes, &m) |
| 261 |
if err != nil { |
| 262 |
return nil, err |
| 263 |
} |
| 264 |
return m, nil |
| 265 |
} |
| 266 |
} |
| 267 |
} |
| 268 |
return from.Interface(), nil |
| 269 |
} |
| 270 |
} |