Home

tmpl @07ccb515849ca1a50462bf2e5059af23c14a516a - refs - log -
-
https://git.jolheiser.com/tmpl.git
Template automation
tmpl / schema / convert.go
- raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package schema

import (
	"fmt"

	"gopkg.in/yaml.v3"
)

// Unmarshal YAML to map[string]any instead of map[any]any.
func Unmarshal(in []byte, out any) error {
	var res any

	if err := yaml.Unmarshal(in, &res); err != nil {
		return err
	}
	*out.(*any) = mapValue(res)

	return nil
}

func mapSlice(in []any) []any {
	res := make([]any, len(in))
	for i, v := range in {
		res[i] = mapValue(v)
	}
	return res
}

func mapMap(in map[any]any) map[string]any {
	res := make(map[string]any)
	for k, v := range in {
		res[fmt.Sprintf("%v", k)] = mapValue(v)
	}
	return res
}

func mapValue(v any) any {
	switch v := v.(type) {
	case []any:
		return mapSlice(v)
	case map[any]any:
		return mapMap(v)
	default:
		return v
	}
}