| 1 |
package koanf |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding" |
| 6 |
"fmt" |
| 7 |
"reflect" |
| 8 |
"sort" |
| 9 |
"strconv" |
| 10 |
"sync" |
| 11 |
|
| 12 |
"github.com/go-viper/mapstructure/v2" |
| 13 |
"github.com/knadh/koanf/maps" |
| 14 |
"github.com/mitchellh/copystructure" |
| 15 |
) |
| 16 |
|
| 17 |
// Koanf is the configuration apparatus. |
| 18 |
type Koanf struct { |
| 19 |
confMap map[string]any |
| 20 |
confMapFlat map[string]any |
| 21 |
keyMap KeyMap |
| 22 |
conf Conf |
| 23 |
mu sync.RWMutex |
| 24 |
} |
| 25 |
|
| 26 |
// Conf is the Koanf configuration. |
| 27 |
type Conf struct { |
| 28 |
// Delim is the delimiter to use |
| 29 |
// when specifying config key paths, for instance a . for `parent.child.key` |
| 30 |
// or a / for `parent/child/key`. |
| 31 |
Delim string |
| 32 |
|
| 33 |
// StrictMerge makes the merging behavior strict. |
| 34 |
// Meaning when loading two files that have the same key, |
| 35 |
// the first loaded file will define the desired type, and if the second file loads |
| 36 |
// a different type will cause an error. |
| 37 |
StrictMerge bool |
| 38 |
} |
| 39 |
|
| 40 |
// KeyMap represents a map of flattened delimited keys and the non-delimited |
| 41 |
// parts as their slices. For nested keys, the map holds all levels of path combinations. |
| 42 |
// For example, the nested structure `parent -> child -> key` will produce the map: |
| 43 |
// parent.child.key => [parent, child, key] |
| 44 |
// parent.child => [parent, child] |
| 45 |
// parent => [parent] |
| 46 |
type KeyMap map[string][]string |
| 47 |
|
| 48 |
// UnmarshalConf represents configuration options used by |
| 49 |
// Unmarshal() to unmarshal conf maps into arbitrary structs. |
| 50 |
type UnmarshalConf struct { |
| 51 |
// Tag is the struct field tag to unmarshal. |
| 52 |
// `koanf` is used if left empty. |
| 53 |
Tag string |
| 54 |
|
| 55 |
// If this is set to true, instead of unmarshalling nested structures |
| 56 |
// based on the key path, keys are taken literally to unmarshal into |
| 57 |
// a flat struct. For example: |
| 58 |
// ``` |
| 59 |
// type MyStuff struct { |
| 60 |
// Child1Name string `koanf:"parent1.child1.name"` |
| 61 |
// Child2Name string `koanf:"parent2.child2.name"` |
| 62 |
// Type string `koanf:"json"` |
| 63 |
// } |
| 64 |
// ``` |
| 65 |
FlatPaths bool |
| 66 |
DecoderConfig *mapstructure.DecoderConfig |
| 67 |
} |
| 68 |
|
| 69 |
// New returns a new instance of Koanf. delim is the delimiter to use |
| 70 |
// when specifying config key paths, for instance a . for `parent.child.key` |
| 71 |
// or a / for `parent/child/key`. |
| 72 |
func New(delim string) *Koanf { |
| 73 |
return NewWithConf(Conf{ |
| 74 |
Delim: delim, |
| 75 |
StrictMerge: false, |
| 76 |
}) |
| 77 |
} |
| 78 |
|
| 79 |
// NewWithConf returns a new instance of Koanf based on the Conf. |
| 80 |
func NewWithConf(conf Conf) *Koanf { |
| 81 |
return &Koanf{ |
| 82 |
confMap: make(map[string]any), |
| 83 |
confMapFlat: make(map[string]any), |
| 84 |
keyMap: make(KeyMap), |
| 85 |
conf: conf, |
| 86 |
} |
| 87 |
} |
| 88 |
|
| 89 |
// Load takes a Provider that either provides a parsed config map[string]any |
| 90 |
// in which case pa (Parser) can be nil, or raw bytes to be parsed, where a Parser |
| 91 |
// can be provided to parse. Additionally, options can be passed which modify the |
| 92 |
// load behavior, such as passing a custom merge function. |
| 93 |
func (ko *Koanf) Load(p Provider, pa Parser, opts ...Option) error { |
| 94 |
var ( |
| 95 |
mp map[string]any |
| 96 |
err error |
| 97 |
) |
| 98 |
|
| 99 |
if p == nil { |
| 100 |
return fmt.Errorf("load received a nil provider") |
| 101 |
} |
| 102 |
|
| 103 |
// No Parser is given. Call the Provider's Read() method to get |
| 104 |
// the config map. |
| 105 |
if pa == nil { |
| 106 |
mp, err = p.Read() |
| 107 |
if err != nil { |
| 108 |
return err |
| 109 |
} |
| 110 |
} else { |
| 111 |
// There's a Parser. Get raw bytes from the Provider to parse. |
| 112 |
b, err := p.ReadBytes() |
| 113 |
if err != nil { |
| 114 |
return err |
| 115 |
} |
| 116 |
mp, err = pa.Unmarshal(b) |
| 117 |
if err != nil { |
| 118 |
return err |
| 119 |
} |
| 120 |
} |
| 121 |
|
| 122 |
return ko.merge(mp, newOptions(opts)) |
| 123 |
} |
| 124 |
|
| 125 |
// Keys returns the slice of all flattened keys in the loaded configuration |
| 126 |
// sorted alphabetically. |
| 127 |
func (ko *Koanf) Keys() []string { |
| 128 |
ko.mu.RLock() |
| 129 |
out := make([]string, 0, len(ko.confMapFlat)) |
| 130 |
for k := range ko.confMapFlat { |
| 131 |
out = append(out, k) |
| 132 |
} |
| 133 |
ko.mu.RUnlock() |
| 134 |
sort.Strings(out) |
| 135 |
return out |
| 136 |
} |
| 137 |
|
| 138 |
// KeyMap returns a map of flattened keys and the individual parts of the |
| 139 |
// key as slices. eg: "parent.child.key" => ["parent", "child", "key"]. |
| 140 |
func (ko *Koanf) KeyMap() KeyMap { |
| 141 |
ko.mu.RLock() |
| 142 |
out := make(KeyMap, len(ko.keyMap)) |
| 143 |
for key, parts := range ko.keyMap { |
| 144 |
out[key] = make([]string, len(parts)) |
| 145 |
copy(out[key], parts) |
| 146 |
} |
| 147 |
ko.mu.RUnlock() |
| 148 |
return out |
| 149 |
} |
| 150 |
|
| 151 |
// All returns a map of all flattened key paths and their values. |
| 152 |
// Note that it uses maps.Copy to create a copy that uses |
| 153 |
// json.Marshal which changes the numeric types to float64. |
| 154 |
func (ko *Koanf) All() map[string]any { |
| 155 |
ko.mu.RLock() |
| 156 |
defer ko.mu.RUnlock() |
| 157 |
return maps.Copy(ko.confMapFlat) |
| 158 |
} |
| 159 |
|
| 160 |
// Raw returns a copy of the full raw conf map. |
| 161 |
// Note that it uses maps.Copy to create a copy that uses |
| 162 |
// json.Marshal which changes the numeric types to float64. |
| 163 |
func (ko *Koanf) Raw() map[string]any { |
| 164 |
ko.mu.RLock() |
| 165 |
defer ko.mu.RUnlock() |
| 166 |
return maps.Copy(ko.confMap) |
| 167 |
} |
| 168 |
|
| 169 |
// Sprint returns a key -> value string representation |
| 170 |
// of the config map with keys sorted alphabetically. |
| 171 |
func (ko *Koanf) Sprint() string { |
| 172 |
b := bytes.Buffer{} |
| 173 |
keys := ko.Keys() |
| 174 |
ko.mu.RLock() |
| 175 |
for _, k := range keys { |
| 176 |
v := ko.confMapFlat[k] |
| 177 |
b.WriteString(fmt.Sprintf("%s -> %v\n", k, v)) |
| 178 |
} |
| 179 |
ko.mu.RUnlock() |
| 180 |
return b.String() |
| 181 |
} |
| 182 |
|
| 183 |
// Print prints a key -> value string representation |
| 184 |
// of the config map with keys sorted alphabetically. |
| 185 |
func (ko *Koanf) Print() { |
| 186 |
fmt.Print(ko.Sprint()) |
| 187 |
} |
| 188 |
|
| 189 |
// Cut cuts the config map at a given key path into a sub map and |
| 190 |
// returns a new Koanf instance with the cut config map loaded. |
| 191 |
// For instance, if the loaded config has a path that looks like |
| 192 |
// parent.child.sub.a.b, `Cut("parent.child")` returns a new Koanf |
| 193 |
// instance with the config map `sub.a.b` where everything above |
| 194 |
// `parent.child` are cut out. |
| 195 |
func (ko *Koanf) Cut(path string) *Koanf { |
| 196 |
out := make(map[string]any) |
| 197 |
|
| 198 |
// Cut only makes sense if the requested key path is a map. |
| 199 |
if v, ok := ko.Get(path).(map[string]any); ok { |
| 200 |
out = v |
| 201 |
} |
| 202 |
|
| 203 |
n := New(ko.conf.Delim) |
| 204 |
_ = n.merge(out, new(options)) |
| 205 |
return n |
| 206 |
} |
| 207 |
|
| 208 |
// Copy returns a copy of the Koanf instance. |
| 209 |
func (ko *Koanf) Copy() *Koanf { |
| 210 |
return ko.Cut("") |
| 211 |
} |
| 212 |
|
| 213 |
// Merge merges the config map of a given Koanf instance into |
| 214 |
// the current instance. |
| 215 |
func (ko *Koanf) Merge(in *Koanf) error { |
| 216 |
return ko.merge(in.Raw(), new(options)) |
| 217 |
} |
| 218 |
|
| 219 |
// MergeAt merges the config map of a given Koanf instance into |
| 220 |
// the current instance as a sub map, at the given key path. |
| 221 |
// If all or part of the key path is missing, it will be created. |
| 222 |
// If the key path is `""`, this is equivalent to Merge. |
| 223 |
func (ko *Koanf) MergeAt(in *Koanf, path string) error { |
| 224 |
// No path. Merge the two config maps. |
| 225 |
if path == "" { |
| 226 |
return ko.Merge(in) |
| 227 |
} |
| 228 |
|
| 229 |
// Unflatten the config map with the given key path. |
| 230 |
n := maps.Unflatten(map[string]any{ |
| 231 |
path: in.Raw(), |
| 232 |
}, ko.conf.Delim) |
| 233 |
|
| 234 |
return ko.merge(n, new(options)) |
| 235 |
} |
| 236 |
|
| 237 |
// Set sets the value at a specific key. |
| 238 |
func (ko *Koanf) Set(key string, val any) error { |
| 239 |
// Unflatten the config map with the given key path. |
| 240 |
n := maps.Unflatten(map[string]any{ |
| 241 |
key: val, |
| 242 |
}, ko.conf.Delim) |
| 243 |
|
| 244 |
return ko.merge(n, new(options)) |
| 245 |
} |
| 246 |
|
| 247 |
// Marshal takes a Parser implementation and marshals the config map into bytes, |
| 248 |
// for example, to TOML or JSON bytes. |
| 249 |
func (ko *Koanf) Marshal(p Parser) ([]byte, error) { |
| 250 |
return p.Marshal(ko.Raw()) |
| 251 |
} |
| 252 |
|
| 253 |
// Unmarshal unmarshals a given key path into the given struct using |
| 254 |
// the mapstructure lib. If no path is specified, the whole map is unmarshalled. |
| 255 |
// `koanf` is the struct field tag used to match field names. To customize, |
| 256 |
// use UnmarshalWithConf(). It uses the mitchellh/mapstructure package. |
| 257 |
func (ko *Koanf) Unmarshal(path string, o any) error { |
| 258 |
return ko.UnmarshalWithConf(path, o, UnmarshalConf{}) |
| 259 |
} |
| 260 |
|
| 261 |
// UnmarshalWithConf is like Unmarshal but takes configuration params in UnmarshalConf. |
| 262 |
// See mitchellh/mapstructure's DecoderConfig for advanced customization |
| 263 |
// of the unmarshal behaviour. |
| 264 |
func (ko *Koanf) UnmarshalWithConf(path string, o any, c UnmarshalConf) error { |
| 265 |
if c.DecoderConfig == nil { |
| 266 |
c.DecoderConfig = &mapstructure.DecoderConfig{ |
| 267 |
DecodeHook: mapstructure.ComposeDecodeHookFunc( |
| 268 |
mapstructure.StringToTimeDurationHookFunc(), |
| 269 |
textUnmarshalerHookFunc()), |
| 270 |
Metadata: nil, |
| 271 |
WeaklyTypedInput: true, |
| 272 |
} |
| 273 |
} |
| 274 |
|
| 275 |
c.DecoderConfig.Result = o |
| 276 |
|
| 277 |
if c.Tag == "" { |
| 278 |
c.DecoderConfig.TagName = "koanf" |
| 279 |
} else { |
| 280 |
c.DecoderConfig.TagName = c.Tag |
| 281 |
} |
| 282 |
|
| 283 |
d, err := mapstructure.NewDecoder(c.DecoderConfig) |
| 284 |
if err != nil { |
| 285 |
return err |
| 286 |
} |
| 287 |
|
| 288 |
// Unmarshal using flat key paths. |
| 289 |
mp := ko.Get(path) |
| 290 |
if c.FlatPaths { |
| 291 |
if f, ok := mp.(map[string]any); ok { |
| 292 |
fmp, _ := maps.Flatten(f, nil, ko.conf.Delim) |
| 293 |
mp = fmp |
| 294 |
} |
| 295 |
} |
| 296 |
|
| 297 |
return d.Decode(mp) |
| 298 |
} |
| 299 |
|
| 300 |
// Delete removes all nested values from a given path. |
| 301 |
// Clears all keys/values if no path is specified. |
| 302 |
// Every empty, key on the path, is recursively deleted. |
| 303 |
func (ko *Koanf) Delete(path string) { |
| 304 |
ko.mu.Lock() |
| 305 |
defer ko.mu.Unlock() |
| 306 |
|
| 307 |
// No path. Erase the entire map. |
| 308 |
if path == "" { |
| 309 |
ko.confMap = make(map[string]any) |
| 310 |
ko.confMapFlat = make(map[string]any) |
| 311 |
ko.keyMap = make(KeyMap) |
| 312 |
return |
| 313 |
} |
| 314 |
|
| 315 |
// Does the path exist? |
| 316 |
p, ok := ko.keyMap[path] |
| 317 |
if !ok { |
| 318 |
return |
| 319 |
} |
| 320 |
maps.Delete(ko.confMap, p) |
| 321 |
|
| 322 |
// Update the flattened version as well. |
| 323 |
ko.confMapFlat, ko.keyMap = maps.Flatten(ko.confMap, nil, ko.conf.Delim) |
| 324 |
ko.keyMap = populateKeyParts(ko.keyMap, ko.conf.Delim) |
| 325 |
} |
| 326 |
|
| 327 |
// Get returns the raw, uncast any value of a given key path |
| 328 |
// in the config map. If the key path does not exist, nil is returned. |
| 329 |
func (ko *Koanf) Get(path string) any { |
| 330 |
// No path. Return the whole conf map. |
| 331 |
if path == "" { |
| 332 |
return ko.Raw() |
| 333 |
} |
| 334 |
|
| 335 |
// Does the path exist? |
| 336 |
ko.mu.RLock() |
| 337 |
defer ko.mu.RUnlock() |
| 338 |
|
| 339 |
p, ok := ko.keyMap[path] |
| 340 |
if !ok { |
| 341 |
return nil |
| 342 |
} |
| 343 |
res := maps.Search(ko.confMap, p) |
| 344 |
|
| 345 |
// Non-reference types are okay to return directly. |
| 346 |
// Other types are "copied" with maps.Copy or json.Marshal |
| 347 |
// that change the numeric types to float64. |
| 348 |
|
| 349 |
switch v := res.(type) { |
| 350 |
case int, int8, int16, int32, int64, float32, float64, string, bool: |
| 351 |
return v |
| 352 |
case map[string]any: |
| 353 |
return maps.Copy(v) |
| 354 |
case nil: |
| 355 |
return nil |
| 356 |
} |
| 357 |
|
| 358 |
// Skip nil pointers before copying. |
| 359 |
if rv := reflect.ValueOf(res); rv.Kind() == reflect.Ptr && rv.IsNil() { |
| 360 |
return res |
| 361 |
} |
| 362 |
|
| 363 |
out, _ := copystructure.Copy(&res) |
| 364 |
if ptrOut, ok := out.(*any); ok { |
| 365 |
return *ptrOut |
| 366 |
} |
| 367 |
return out |
| 368 |
} |
| 369 |
|
| 370 |
// Slices returns a list of Koanf instances constructed out of a |
| 371 |
// []map[string]any interface at the given path. |
| 372 |
func (ko *Koanf) Slices(path string) []*Koanf { |
| 373 |
out := []*Koanf{} |
| 374 |
if path == "" { |
| 375 |
return out |
| 376 |
} |
| 377 |
|
| 378 |
// Does the path exist? |
| 379 |
sl, ok := ko.Get(path).([]any) |
| 380 |
if !ok { |
| 381 |
return out |
| 382 |
} |
| 383 |
|
| 384 |
for _, s := range sl { |
| 385 |
mp, ok := s.(map[string]any) |
| 386 |
if !ok { |
| 387 |
continue |
| 388 |
} |
| 389 |
|
| 390 |
k := New(ko.conf.Delim) |
| 391 |
_ = k.merge(mp, new(options)) |
| 392 |
out = append(out, k) |
| 393 |
} |
| 394 |
|
| 395 |
return out |
| 396 |
} |
| 397 |
|
| 398 |
// Exists returns true if the given key path exists in the conf map. |
| 399 |
func (ko *Koanf) Exists(path string) bool { |
| 400 |
ko.mu.RLock() |
| 401 |
_, ok := ko.keyMap[path] |
| 402 |
ko.mu.RUnlock() |
| 403 |
return ok |
| 404 |
} |
| 405 |
|
| 406 |
// MapKeys returns a sorted string list of keys in a map addressed by the |
| 407 |
// given path. If the path is not a map, an empty string slice is |
| 408 |
// returned. |
| 409 |
func (ko *Koanf) MapKeys(path string) []string { |
| 410 |
var ( |
| 411 |
out = []string{} |
| 412 |
o = ko.Get(path) |
| 413 |
) |
| 414 |
if o == nil { |
| 415 |
return out |
| 416 |
} |
| 417 |
|
| 418 |
mp, ok := o.(map[string]any) |
| 419 |
if !ok { |
| 420 |
return out |
| 421 |
} |
| 422 |
out = make([]string, 0, len(mp)) |
| 423 |
for k := range mp { |
| 424 |
out = append(out, k) |
| 425 |
} |
| 426 |
sort.Strings(out) |
| 427 |
return out |
| 428 |
} |
| 429 |
|
| 430 |
// Delim returns delimiter in used by this instance of Koanf. |
| 431 |
func (ko *Koanf) Delim() string { |
| 432 |
return ko.conf.Delim |
| 433 |
} |
| 434 |
|
| 435 |
func (ko *Koanf) merge(c map[string]any, opts *options) error { |
| 436 |
ko.mu.Lock() |
| 437 |
|
| 438 |
maps.IntfaceKeysToStrings(c) |
| 439 |
if opts.merge != nil { |
| 440 |
// Deep-copy confMap so the custom merge function can safely call |
| 441 |
// ko.Get*() methods (which acquire a read lock) without deadlocking. |
| 442 |
dest := maps.Copy(ko.confMap) |
| 443 |
|
| 444 |
ko.mu.Unlock() |
| 445 |
err := opts.merge(c, dest) |
| 446 |
ko.mu.Lock() |
| 447 |
|
| 448 |
if err != nil { |
| 449 |
ko.mu.Unlock() |
| 450 |
return err |
| 451 |
} |
| 452 |
ko.confMap = dest |
| 453 |
} else if ko.conf.StrictMerge { |
| 454 |
if err := maps.MergeStrict(c, ko.confMap); err != nil { |
| 455 |
ko.mu.Unlock() |
| 456 |
return err |
| 457 |
} |
| 458 |
} else { |
| 459 |
maps.Merge(c, ko.confMap) |
| 460 |
} |
| 461 |
|
| 462 |
// Maintain a flattened version as well. |
| 463 |
ko.confMapFlat, ko.keyMap = maps.Flatten(ko.confMap, nil, ko.conf.Delim) |
| 464 |
ko.keyMap = populateKeyParts(ko.keyMap, ko.conf.Delim) |
| 465 |
|
| 466 |
ko.mu.Unlock() |
| 467 |
return nil |
| 468 |
} |
| 469 |
|
| 470 |
// toInt64 takes an interface value and if it is an integer type, |
| 471 |
// converts and returns int64. If it's any other type, |
| 472 |
// forces it to a string and attempts to do a strconv.Atoi |
| 473 |
// to get an integer out. |
| 474 |
func toInt64(v any) (int64, error) { |
| 475 |
switch i := v.(type) { |
| 476 |
case int: |
| 477 |
return int64(i), nil |
| 478 |
case int8: |
| 479 |
return int64(i), nil |
| 480 |
case int16: |
| 481 |
return int64(i), nil |
| 482 |
case int32: |
| 483 |
return int64(i), nil |
| 484 |
case int64: |
| 485 |
return i, nil |
| 486 |
} |
| 487 |
|
| 488 |
// Force it to a string and try to convert. |
| 489 |
f, err := strconv.ParseFloat(fmt.Sprintf("%v", v), 64) |
| 490 |
if err != nil { |
| 491 |
return 0, err |
| 492 |
} |
| 493 |
|
| 494 |
return int64(f), nil |
| 495 |
} |
| 496 |
|
| 497 |
// toInt64 takes a `v any` value and if it is a float type, |
| 498 |
// converts and returns a `float64`. If it's any other type, forces it to a |
| 499 |
// string and attempts to get a float out using `strconv.ParseFloat`. |
| 500 |
func toFloat64(v any) (float64, error) { |
| 501 |
switch i := v.(type) { |
| 502 |
case float32: |
| 503 |
return float64(i), nil |
| 504 |
case float64: |
| 505 |
return i, nil |
| 506 |
} |
| 507 |
|
| 508 |
// Force it to a string and try to convert. |
| 509 |
f, err := strconv.ParseFloat(fmt.Sprintf("%v", v), 64) |
| 510 |
if err != nil { |
| 511 |
return f, err |
| 512 |
} |
| 513 |
|
| 514 |
return f, nil |
| 515 |
} |
| 516 |
|
| 517 |
// toBool takes an interface value and if it is a bool type, |
| 518 |
// returns it. If it's any other type, forces it to a string and attempts |
| 519 |
// to parse it as a bool using strconv.ParseBool. |
| 520 |
func toBool(v any) (bool, error) { |
| 521 |
if b, ok := v.(bool); ok { |
| 522 |
return b, nil |
| 523 |
} |
| 524 |
|
| 525 |
// Force it to a string and try to convert. |
| 526 |
b, err := strconv.ParseBool(fmt.Sprintf("%v", v)) |
| 527 |
if err != nil { |
| 528 |
return b, err |
| 529 |
} |
| 530 |
return b, nil |
| 531 |
} |
| 532 |
|
| 533 |
// populateKeyParts iterates a key map and generates all possible |
| 534 |
// traversal paths. For instance, `parent.child.key` generates |
| 535 |
// `parent`, and `parent.child`. |
| 536 |
func populateKeyParts(m KeyMap, delim string) KeyMap { |
| 537 |
out := make(KeyMap, len(m)) // The size of the result is at very least same to KeyMap |
| 538 |
for _, parts := range m { |
| 539 |
// parts is a slice of [parent, child, key] |
| 540 |
var nk string |
| 541 |
|
| 542 |
for i := range parts { |
| 543 |
if i == 0 { |
| 544 |
// On first iteration only use first part |
| 545 |
nk = parts[i] |
| 546 |
} else { |
| 547 |
// If nk already contains a part (e.g. `parent`) append delim + `child` |
| 548 |
nk += delim + parts[i] |
| 549 |
} |
| 550 |
if _, ok := out[nk]; ok { |
| 551 |
continue |
| 552 |
} |
| 553 |
out[nk] = make([]string, i+1) |
| 554 |
copy(out[nk], parts[0:i+1]) |
| 555 |
} |
| 556 |
} |
| 557 |
return out |
| 558 |
} |
| 559 |
|
| 560 |
// textUnmarshalerHookFunc is a fixed version of mapstructure.TextUnmarshallerHookFunc. |
| 561 |
// This hook allows to additionally unmarshal text into custom string types that implement the encoding.Text(Un)Marshaler interface(s). |
| 562 |
func textUnmarshalerHookFunc() mapstructure.DecodeHookFuncType { |
| 563 |
return func( |
| 564 |
f reflect.Type, |
| 565 |
t reflect.Type, |
| 566 |
data any, |
| 567 |
) (any, error) { |
| 568 |
if f.Kind() != reflect.String { |
| 569 |
return data, nil |
| 570 |
} |
| 571 |
result := reflect.New(t).Interface() |
| 572 |
unmarshaller, ok := result.(encoding.TextUnmarshaler) |
| 573 |
if !ok { |
| 574 |
return data, nil |
| 575 |
} |
| 576 |
|
| 577 |
// default text representation is the actual value of the `from` string |
| 578 |
var ( |
| 579 |
dataVal = reflect.ValueOf(data) |
| 580 |
text = []byte(dataVal.String()) |
| 581 |
) |
| 582 |
if f.Kind() == t.Kind() { |
| 583 |
// source and target are of underlying type string |
| 584 |
var ( |
| 585 |
err error |
| 586 |
ptrVal = reflect.New(dataVal.Type()) |
| 587 |
) |
| 588 |
if !ptrVal.Elem().CanSet() { |
| 589 |
// cannot set, skip, this should not happen |
| 590 |
if err := unmarshaller.UnmarshalText(text); err != nil { |
| 591 |
return nil, err |
| 592 |
} |
| 593 |
return result, nil |
| 594 |
} |
| 595 |
ptrVal.Elem().Set(dataVal) |
| 596 |
|
| 597 |
// We need to assert that both, the value type and the pointer type |
| 598 |
// do (not) implement the TextMarshaller interface before proceeding and simply |
| 599 |
// using the string value of the string type. |
| 600 |
// it might be the case that the internal string representation differs from |
| 601 |
// the (un)marshalled string. |
| 602 |
|
| 603 |
for _, v := range []reflect.Value{dataVal, ptrVal} { |
| 604 |
if marshaller, ok := v.Interface().(encoding.TextMarshaler); ok { |
| 605 |
text, err = marshaller.MarshalText() |
| 606 |
if err != nil { |
| 607 |
return nil, err |
| 608 |
} |
| 609 |
break |
| 610 |
} |
| 611 |
} |
| 612 |
} |
| 613 |
|
| 614 |
// text is either the source string's value or the source string type's marshaled value |
| 615 |
// which may differ from its internal string value. |
| 616 |
if err := unmarshaller.UnmarshalText(text); err != nil { |
| 617 |
return nil, err |
| 618 |
} |
| 619 |
return result, nil |
| 620 |
} |
| 621 |
} |