This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 23
/
utils.go
69 lines (57 loc) · 1.63 KB
/
utils.go
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package config
import (
"encoding/json"
"fmt"
"reflect"
"github.com/pkg/errors"
)
// Uses Json marshal/unmarshal to make a deep copy of a config object.
func DeepCopyConfig(config Config) (Config, error) {
raw, err := json.Marshal(config)
if err != nil {
return nil, err
}
t := reflect.TypeOf(config)
ptrValue := reflect.New(t)
newObj := ptrValue.Interface()
if err = json.Unmarshal(raw, newObj); err != nil {
return nil, err
}
return ptrValue.Elem().Interface(), nil
}
func DeepEqual(config1, config2 Config) bool {
return reflect.DeepEqual(config1, config2)
}
func toInterface(config Config) (interface{}, error) {
raw, err := json.Marshal(config)
if err != nil {
return nil, err
}
var m interface{}
err = json.Unmarshal(raw, &m)
return m, err
}
// Builds a generic map out of the root section config and its sub-sections configs.
func AllConfigsAsMap(root Section) (m map[string]interface{}, err error) {
errs := ErrorCollection{}
allConfigs := make(map[string]interface{}, len(root.GetSections()))
if root.GetConfig() != nil {
rootConfig, err := toInterface(root.GetConfig())
if !errs.Append(err) {
if asMap, isCasted := rootConfig.(map[string]interface{}); isCasted {
allConfigs = asMap
} else {
allConfigs[""] = rootConfig
}
}
}
for k, section := range root.GetSections() {
if _, alreadyExists := allConfigs[k]; alreadyExists {
errs.Append(errors.Wrap(ErrChildConfigOverridesConfig,
fmt.Sprintf("section key [%v] overrides an existing native config property", k)))
}
allConfigs[k], err = AllConfigsAsMap(section)
errs.Append(err)
}
return allConfigs, errs.ErrorOrDefault()
}