-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate_utils.go
77 lines (73 loc) · 2.05 KB
/
state_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
70
71
72
73
74
75
76
77
package bstates
import (
"fmt"
"reflect"
)
// StatesToMsiStates converts a slice of State pointers into a slice of
// maps containing the corresponding MSI states.
//
// Each State is transformed into a map using the ToMsi() method.
func StatesToMsiStates(states []*State) (out []map[string]interface{}, err error) {
for _, e := range states {
var de map[string]interface{}
if de, err = e.ToMsi(); err != nil {
return
}
out = append(out, de)
}
return
}
// GetDeltaMsiState compares two State objects and returns a map
// containing the values that have changed between them.
func GetDeltaMsiState(from *State, to *State) (map[string]interface{}, error) {
data := map[string]interface{}{}
fields := to.GetFieldsDesc()
fieldNames := []string{}
for _, f := range fields {
fieldNames = append(fieldNames, f.Name)
}
for name := range to.schema.decodedFields {
fieldNames = append(fieldNames, name)
}
for _, name := range fieldNames {
fromValue, err := from.Get(name)
if err != nil {
return nil, fmt.Errorf("field \"%s\" not found in source state", name)
}
toValue, err := to.Get(name)
if err != nil {
return nil, fmt.Errorf("field \"%s\" not found in final state", name)
}
if !reflect.DeepEqual(fromValue, toValue) {
data[name] = toValue
}
}
return data, nil
}
// GetDeltaMsiStates returns a slice of maps that represent the changes
// between each successive pair of State objects in the provided slice.
//
// The first State is converted to its MSI representation, and subsequent
// States are compared to the last seen State using GetDeltaMsiState().
func GetDeltaMsiStates(states []*State) ([]map[string]interface{}, error) {
out := []map[string]interface{}{}
if len(states) > 0 {
evIni := states[0]
evIniMsi, err := evIni.ToMsi()
if err != nil {
return nil, err
}
out = append(out, evIniMsi)
lastEv := evIni
for i := 1; i < len(states); i++ {
ev := states[i]
evMsi, err := GetDeltaMsiState(lastEv, ev)
if err != nil {
return nil, err
}
out = append(out, evMsi)
lastEv = ev
}
}
return out, nil
}