forked from itaysk/kubectl-neat
/
neat.go
211 lines (188 loc) · 5.81 KB
/
neat.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/*
Copyright © 2019 Itay Shakury @itaysk
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cmd
import (
"fmt"
"strings"
"github.com/zzehring/kubectl-neat/v2/pkg/defaults"
"github.com/tidwall/gjson"
"github.com/tidwall/sjson"
)
// Neat gets a Kubernetes resource json as string and de-clutters it to make it more readable.
func Neat(in string) (string, error) {
var err error
draft := in
if in == "" {
return draft, fmt.Errorf("error in neatPod, input json is empty")
}
if !gjson.Valid(in) {
return draft, fmt.Errorf("error in neatPod, input is not a vaild json: %s", in[:20])
}
kind := gjson.Get(in, "kind").String()
// handle list
if kind == "List" {
items := gjson.Get(draft, "items").Array()
for i, item := range items {
itemNeat, err := Neat(item.String())
if err != nil {
continue
}
draft, err = sjson.SetRaw(draft, fmt.Sprintf("items.%d", i), itemNeat)
if err != nil {
continue
}
}
return draft, nil
}
// defaults neating
draft, err = defaults.NeatDefaults(draft)
if err != nil {
return draft, fmt.Errorf("error in neatDefaults : %v", err)
}
// controllers neating
draft, err = neatScheduler(draft)
if err != nil {
return draft, fmt.Errorf("error in neatScheduler : %v", err)
}
if kind == "Pod" {
draft, err = neatServiceAccount(draft)
if err != nil {
return draft, fmt.Errorf("error in neatServiceAccount : %v", err)
}
}
// general neating
draft, err = neatMetadata(draft)
if err != nil {
return draft, fmt.Errorf("error in neatMetadata : %v", err)
}
draft, err = neatStatus(draft)
if err != nil {
return draft, fmt.Errorf("error in neatStatus : %v", err)
}
draft, err = neatEmpty(draft)
if err != nil {
return draft, fmt.Errorf("error in neatEmpty : %v", err)
}
return draft, nil
}
func neatMetadata(in string) (string, error) {
var err error
in, err = sjson.Delete(in, `metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration`)
if err != nil {
return in, fmt.Errorf("error deleting last-applied-configuration : %v", err)
}
// TODO: prettify this. gjson's @pretty is ok but setRaw the pretty code gives unwanted result
newMeta := gjson.Get(in, "{metadata.name,metadata.namespace,metadata.labels,metadata.annotations}")
in, err = sjson.Set(in, "metadata", newMeta.Value())
if err != nil {
return in, fmt.Errorf("error setting new metadata : %v", err)
}
return in, nil
}
func neatStatus(in string) (string, error) {
return sjson.Delete(in, "status")
}
func neatScheduler(in string) (string, error) {
return sjson.Delete(in, "spec.nodeName")
}
func neatServiceAccount(in string) (string, error) {
var err error
// keep an eye open on https://github.com/tidwall/sjson/issues/11
// when it's implemented, we can do:
// sjson.delete(in, "spec.volumes.#(name%default-token-*)")
// sjson.delete(in, "spec.containers.#.volumeMounts.#(name%default-token-*)")
for vi, v := range gjson.Get(in, "spec.volumes").Array() {
vname := v.Get("name").String()
if strings.HasPrefix(vname, "default-token-") {
in, err = sjson.Delete(in, fmt.Sprintf("spec.volumes.%d", vi))
if err != nil {
continue
}
}
}
for ci, c := range gjson.Get(in, "spec.containers").Array() {
for vmi, vm := range c.Get("volumeMounts").Array() {
vmname := vm.Get("name").String()
if strings.HasPrefix(vmname, "default-token-") {
in, err = sjson.Delete(in, fmt.Sprintf("spec.containers.%d.volumeMounts.%d", ci, vmi))
if err != nil {
continue
}
}
}
}
in, _ = sjson.Delete(in, "spec.serviceAccount") //Deprecated: Use serviceAccountName instead
return in, nil
}
// neatEmpty removes all zero length elements in the json
func neatEmpty(in string) (string, error) {
var err error
jsonResult := gjson.Parse(in)
var empties []string
findEmptyPathsRecursive(jsonResult, "", &empties)
for _, emptyPath := range empties {
// if we just delete emptyPath, it may create empty parents
// so we walk the path and re-check for emptiness at every level
emptyPathParts := strings.Split(emptyPath, ".")
for i := len(emptyPathParts); i > 0; i-- {
curPath := strings.Join(emptyPathParts[:i], ".")
cur := gjson.Get(in, curPath)
if isResultEmpty(cur) {
in, err = sjson.Delete(in, curPath)
if err != nil {
continue
}
}
}
}
return in, nil
}
// findEmptyPathsRecursive builds a list of paths that point to zero length elements
// cur is the current element to look at
// path is the path to cur
// res is a pointer to a list of empty paths to populate
func findEmptyPathsRecursive(cur gjson.Result, path string, res *[]string) {
if isResultEmpty(cur) {
*res = append(*res, path[1:]) //remove '.' from start
return
}
if !(cur.IsArray() || cur.IsObject()) {
return
}
// sjson's ForEach doesn't put track index when iterating arrays, hence the index variable
index := -1
cur.ForEach(func(k gjson.Result, v gjson.Result) bool {
var newPath string
if cur.IsArray() {
index++
newPath = fmt.Sprintf("%s.%d", path, index)
} else {
newPath = fmt.Sprintf("%s.%s", path, k.Str)
}
findEmptyPathsRecursive(v, newPath, res)
return true
})
}
func isResultEmpty(j gjson.Result) bool {
v := j.Value()
switch vt := v.(type) {
// empty string != lack of string. keep empty strings as it's meaningful data
// case string:
// return vt == ""
case []interface{}:
return len(vt) == 0
case map[string]interface{}:
return len(vt) == 0
}
return false
}