2021-07-20 02:04:13 +03:00
|
|
|
package dotenv
|
|
|
|
|
|
|
|
import (
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/spf13/cast"
|
|
|
|
)
|
|
|
|
|
|
|
|
// flattenAndMergeMap recursively flattens the given map into a new map
|
2023-08-18 16:29:46 +03:00
|
|
|
// Code is based on the function with the same name in the main package.
|
2023-10-09 17:52:53 +03:00
|
|
|
// TODO: move it to a common place.
|
2023-09-26 17:59:38 +03:00
|
|
|
func flattenAndMergeMap(shadow map[string]any, m map[string]any, prefix string, delimiter string) map[string]any {
|
2021-07-20 02:04:13 +03:00
|
|
|
if shadow != nil && prefix != "" && shadow[prefix] != nil {
|
|
|
|
// prefix is shadowed => nothing more to flatten
|
|
|
|
return shadow
|
|
|
|
}
|
|
|
|
if shadow == nil {
|
2023-09-26 17:59:38 +03:00
|
|
|
shadow = make(map[string]any)
|
2021-07-20 02:04:13 +03:00
|
|
|
}
|
|
|
|
|
2023-09-26 17:59:38 +03:00
|
|
|
var m2 map[string]any
|
2021-07-20 02:04:13 +03:00
|
|
|
if prefix != "" {
|
|
|
|
prefix += delimiter
|
|
|
|
}
|
|
|
|
for k, val := range m {
|
|
|
|
fullKey := prefix + k
|
2023-07-27 21:56:32 +03:00
|
|
|
switch val := val.(type) {
|
2023-09-26 17:59:38 +03:00
|
|
|
case map[string]any:
|
2023-07-27 21:56:32 +03:00
|
|
|
m2 = val
|
2023-09-26 17:59:38 +03:00
|
|
|
case map[any]any:
|
2021-07-20 02:04:13 +03:00
|
|
|
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
|
|
|
|
}
|