This repository has been archived by the owner on Apr 4, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathconfig_items.go
92 lines (70 loc) · 1.87 KB
/
config_items.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"encoding/json"
"io/ioutil"
"reflect"
)
type ConfigMismatch struct {
Missing ConfigItems
}
func (c ConfigMismatch) Error() string {
return "Config found that is present in the CDN config but not in the local config"
}
type ConfigItems map[string]interface{}
type ConfigItemForUpdate struct {
Current interface{}
Expected interface{}
}
type ConfigItemsForUpdate map[string]ConfigItemForUpdate
func CompareConfigItemsForUpdate(current, expected ConfigItems) (ConfigItemsForUpdate, error) {
union := UnionConfigItems(current, expected)
differenceCurrentAndUnion := DifferenceConfigItems(current, union)
differenceExpectedAndUnion := DifferenceConfigItems(expected, union)
if len(differenceExpectedAndUnion) > len(differenceCurrentAndUnion) {
return nil, ConfigMismatch{Missing: differenceExpectedAndUnion}
}
update := ConfigItemsForUpdate{}
for key, val := range differenceCurrentAndUnion {
update[key] = ConfigItemForUpdate{
Current: current[key],
Expected: val,
}
}
return update, nil
}
func DifferenceConfigItems(from, to ConfigItems) ConfigItems {
config := ConfigItems{}
for key, val := range to {
if innerVal, _ := from[key]; !reflect.DeepEqual(val, innerVal) {
config[key] = val
}
}
return config
}
func LoadConfigItems(file string) (ConfigItems, error) {
bs, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
var config ConfigItems
err = json.Unmarshal(bs, &config)
return config, err
}
func SaveConfigItems(config ConfigItems, file string) error {
bs, err := json.MarshalIndent(config, "", " ")
if err != nil {
return err
}
err = ioutil.WriteFile(file, bs, 0644)
return err
}
func UnionConfigItems(first, second ConfigItems) ConfigItems {
config := ConfigItems{}
for key, val := range first {
config[key] = val
}
for key, val := range second {
config[key] = val
}
return config
}