spf13--viper/internal/encoding/dotenv/map_utils.go

42 lines
966 B
Go
Raw Normal View History

package dotenv
import (
"strings"
"github.com/spf13/cast"
)
// flattenAndMergeMap recursively flattens the given map into a new map
2023-08-18 13:29:46 +00:00
// Code is based on the function with the same name in the main package.
2023-10-09 14:52:53 +00:00
// TODO: move it to a common place.
2023-11-30 15:45:20 +00:00
func flattenAndMergeMap(shadow, m map[string]any, prefix, delimiter string) map[string]any {
if shadow != nil && prefix != "" && shadow[prefix] != nil {
// prefix is shadowed => nothing more to flatten
return shadow
}
if shadow == nil {
2023-09-26 14:59:38 +00:00
shadow = make(map[string]any)
}
2023-09-26 14:59:38 +00:00
var m2 map[string]any
if prefix != "" {
prefix += delimiter
}
for k, val := range m {
fullKey := prefix + k
switch val := val.(type) {
2023-09-26 14:59:38 +00:00
case map[string]any:
m2 = val
2023-09-26 14:59:38 +00:00
case map[any]any:
m2 = cast.ToStringMap(val)
default:
// immediate value
shadow[strings.ToLower(fullKey)] = val
continue
}
// recursively merge to shadow map
shadow = flattenAndMergeMap(shadow, m2, fullKey, delimiter)
}
return shadow
}