-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
83 lines (66 loc) · 1.69 KB
/
main.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
package main
import (
"log"
"os"
"sort"
"gopkg.in/yaml.v3"
)
type DocumentSlice []interface{}
// Implement sort.Interface for DocumentSlice
func (p DocumentSlice) Len() int { return len(p) }
func (p DocumentSlice) Less(i, j int) bool {
// Handle "null" documents from trailing ---
if p[i] == nil {
return true
} else if p[j] == nil {
return false
}
var l = make(map[string]interface{})
for k, v := range p[i].(map[string]interface{}) {
l[k] = v
}
var r = make(map[string]interface{})
for k, v := range p[j].(map[string]interface{}) {
r[k] = v
}
apiLess := l["apiVersion"].(string) < r["apiVersion"].(string)
kindLess := l["apiVersion"].(string) == r["apiVersion"].(string) && l["kind"].(string) < r["kind"].(string)
nameLess := l["apiVersion"] == r["apiVersion"] &&
l["kind"] == r["kind"] &&
l["metadata"].(map[string]interface{})["name"].(string) < (r["metadata"].(map[string]interface{}))["name"].(string)
return apiLess || kindLess || nameLess
}
func (p DocumentSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
func main() {
input := os.Args[1]
// Read YAML file
file, err := os.Open(input)
if err != nil {
log.Fatalf("error: %v", err)
}
defer file.Close()
var documents DocumentSlice
decoder := yaml.NewDecoder(file)
for {
var doc interface{}
err = decoder.Decode(&doc)
if err != nil {
break
}
documents = append(documents, doc)
}
if err.Error() != "EOF" {
log.Fatalf("error: %v", err)
}
sort.Sort(documents)
encoder := yaml.NewEncoder(os.Stdout)
for _, doc := range documents {
err := encoder.Encode(&doc)
if err != nil {
log.Fatalf("error: %v", err)
}
}
if err := encoder.Close(); err != nil {
log.Fatalf("error %v", err)
}
}