-
Notifications
You must be signed in to change notification settings - Fork 5
/
yamlhelper.go
57 lines (53 loc) · 1.79 KB
/
yamlhelper.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
package utils
import (
"encoding/json"
"fmt"
"github.com/pmezard/go-difflib/difflib"
"gopkg.in/yaml.v2"
)
// function to get the yaml output of an object
// marshal/unmarshal to and from json in order to maintain consistency between json and yaml
// currently k8s objects have json field tags, so this helps in skipping empty fields
// and give consistent output yaml similar to json
func getYamlOfObject(object interface{}) (string, error) {
if b, err := json.Marshal(object); err != nil {
return "", fmt.Errorf("error while encoding %+v into JSON: %s", object, err)
} else {
var v map[string]interface{}
if err := json.Unmarshal(b, &v); err != nil {
return "", fmt.Errorf("error while decoding JSON %s into an object: %s", v, err)
} else {
if y, err := yaml.Marshal(&v); err != nil {
return "", fmt.Errorf("error while encoding Map %s into YAML: %s", v, err)
} else {
return string(y), nil
}
}
}
}
func generateYamlDiff(yaml1 string, yaml2 string, context int) string {
diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
A: difflib.SplitLines(yaml1),
B: difflib.SplitLines(yaml2),
FromFile: "Old",
FromDate: "",
ToFile: "New",
ToDate: "",
Context: context,
})
return diff
}
// func to generate yaml diff of objects used for hashing
// context : number of context lines to use for generating diff
// for more reference on context : https://www.gnu.org/software/diffutils/manual/html_node/Unified-Format.html#Unified-Format
func GetYamlDiffForObjects(objectOld interface{}, objectNew interface{}, context int) (string, error) {
yamlOld, err := getYamlOfObject(objectOld)
if err != nil {
return "", err
}
yamlNew, err := getYamlOfObject(objectNew)
if err != nil {
return "", err
}
return generateYamlDiff(yamlOld, yamlNew, context), nil
}