-
Notifications
You must be signed in to change notification settings - Fork 1
/
sort.go
82 lines (65 loc) · 1.75 KB
/
sort.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
package main
import (
"bytes"
"fmt"
"sort"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/yaml"
)
var (
yamlsep = []byte("---\n")
yamlsepnl = []byte("\n---\n")
)
type object struct {
i int
obj *unstructured.Unstructured
}
func SortYAMLObjects(yamlBytes []byte) ([]byte, error) {
// Split on '---' as per the yaml spec
split := bytes.Split(yamlBytes, yamlsep)
var objs []object
for i, s := range split {
json, err := yaml.ToJSON(s)
if err != nil {
return nil, err
}
// If json returns null then we can ignore as this is not a valid yaml object
if bytes.Equal(json, []byte("null")) {
continue
}
runObj, _, err := unstructured.UnstructuredJSONScheme.Decode(json, nil, nil)
if err != nil {
return nil, err
}
obj, ok := runObj.(*unstructured.Unstructured)
if !ok {
return nil, fmt.Errorf("failed to convert runtime object to unstructured: %+v", runObj)
}
objs = append(objs, object{
i: i,
obj: obj,
})
}
if len(objs) == 0 {
return nil, fmt.Errorf("failed to find any kubernetes objects:\n%s",
yamlBytes)
}
sort.SliceStable(objs, func(i, j int) bool {
if objs[i].obj.GetAPIVersion() != objs[j].obj.GetAPIVersion() {
return objs[i].obj.GetAPIVersion() < objs[j].obj.GetAPIVersion()
}
if objs[i].obj.GetKind() != objs[j].obj.GetKind() {
return objs[i].obj.GetKind() < objs[j].obj.GetKind()
}
if objs[i].obj.GetNamespace() != objs[j].obj.GetNamespace() {
return objs[i].obj.GetNamespace() < objs[j].obj.GetNamespace()
}
return objs[i].obj.GetName() < objs[j].obj.GetName()
})
output := yamlsep
for _, obj := range objs {
output = append(output, bytes.TrimSpace(split[obj.i])...)
output = append(output, yamlsepnl...)
}
return output, nil
}