forked from databus23/helm-diff
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdiff.go
More file actions
280 lines (242 loc) · 7.51 KB
/
Copy pathdiff.go
File metadata and controls
280 lines (242 loc) · 7.51 KB
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
package diff
import (
"bytes"
"fmt"
"io"
"math"
"sort"
"strings"
"github.com/aryann/difflib"
"github.com/mgutz/ansi"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes/scheme"
"github.com/databus23/helm-diff/v3/manifest"
)
// Manifests diff on manifests
func Manifests(oldIndex, newIndex map[string]*manifest.MappingResult, suppressedKinds []string, showSecrets bool, context int, output string, to io.Writer) bool {
report.setupReportFormat(output)
seenAnyChanges := false
emptyMapping := &manifest.MappingResult{}
for _, key := range sortedKeys(oldIndex) {
oldContent := oldIndex[key]
if newContent, ok := newIndex[key]; ok {
if oldContent.Content != newContent.Content {
// modified
if !showSecrets {
redactSecrets(oldContent, newContent)
}
diffs := diffMappingResults(oldContent, newContent)
if len(diffs) > 0 {
seenAnyChanges = true
}
report.addEntry(key, suppressedKinds, oldContent.Kind, context, diffs, "MODIFY")
}
} else {
// removed
if !showSecrets {
redactSecrets(oldContent, nil)
}
diffs := diffMappingResults(oldContent, emptyMapping)
if len(diffs) > 0 {
seenAnyChanges = true
}
report.addEntry(key, suppressedKinds, oldContent.Kind, context, diffs, "REMOVE")
}
}
for _, key := range sortedKeys(newIndex) {
newContent := newIndex[key]
if _, ok := oldIndex[key]; !ok {
// added
if !showSecrets {
redactSecrets(nil, newContent)
}
diffs := diffMappingResults(emptyMapping, newContent)
if len(diffs) > 0 {
seenAnyChanges = true
}
report.addEntry(key, suppressedKinds, newContent.Kind, context, diffs, "ADD")
}
}
report.print(to)
report.clean()
return seenAnyChanges
}
func redactSecrets(old, new *manifest.MappingResult) {
if (old != nil && old.Kind != "Secret") || (new != nil && new.Kind != "Secret") {
return
}
serializer := json.NewYAMLSerializer(json.DefaultMetaFactory, scheme.Scheme,
scheme.Scheme)
var oldSecret, newSecret v1.Secret
if old != nil {
if err := yaml.NewYAMLToJSONDecoder(bytes.NewBufferString(old.Content)).Decode(&oldSecret); err != nil {
old.Content = fmt.Sprintf("Error parsing old secret: %s", err)
}
}
if new != nil {
if err := yaml.NewYAMLToJSONDecoder(bytes.NewBufferString(new.Content)).Decode(&newSecret); err != nil {
new.Content = fmt.Sprintf("Error parsing new secret: %s", err)
}
}
if old != nil {
oldSecret.StringData = make(map[string]string, len(oldSecret.Data))
for k, v := range oldSecret.Data {
if new != nil && bytes.Equal(v, newSecret.Data[k]) {
oldSecret.StringData[k] = fmt.Sprintf("REDACTED # (%d bytes)", len(v))
} else {
oldSecret.StringData[k] = fmt.Sprintf("-------- # (%d bytes)", len(v))
}
}
}
if new != nil {
newSecret.StringData = make(map[string]string, len(newSecret.Data))
for k, v := range newSecret.Data {
if old != nil && bytes.Equal(v, oldSecret.Data[k]) {
newSecret.StringData[k] = fmt.Sprintf("REDACTED # (%d bytes)", len(v))
} else {
newSecret.StringData[k] = fmt.Sprintf("++++++++ # (%d bytes)", len(v))
}
}
}
// remove Data field now that we are using StringData for serialization
var buf bytes.Buffer
if old != nil {
oldSecret.Data = nil
if err := serializer.Encode(&oldSecret, &buf); err != nil {
}
old.Content = getComment(old.Content) + strings.Replace(strings.Replace(buf.String(), "stringData", "data", 1), " creationTimestamp: null\n", "", 1)
buf.Reset() //reuse buffer for new secret
}
if new != nil {
newSecret.Data = nil
if err := serializer.Encode(&newSecret, &buf); err != nil {
}
new.Content = getComment(new.Content) + strings.Replace(strings.Replace(buf.String(), "stringData", "data", 1), " creationTimestamp: null\n", "", 1)
}
}
// return the first line of a string if its a comment.
// This gives as the # Source: lines from the rendering
func getComment(s string) string {
i := strings.Index(s, "\n")
if i < 0 || !strings.HasPrefix(s, "#") {
return ""
}
return s[:i+1]
}
// Releases reindex the content based on the template names and pass it to Manifests
func Releases(oldIndex, newIndex map[string]*manifest.MappingResult, suppressedKinds []string, showSecrets bool, context int, output string, to io.Writer) bool {
oldIndex = reIndexForRelease(oldIndex)
newIndex = reIndexForRelease(newIndex)
return Manifests(oldIndex, newIndex, suppressedKinds, showSecrets, context, output, to)
}
func diffMappingResults(oldContent *manifest.MappingResult, newContent *manifest.MappingResult) []difflib.DiffRecord {
return diffStrings(oldContent.Content, newContent.Content)
}
func diffStrings(before, after string) []difflib.DiffRecord {
const sep = "\n"
return difflib.Diff(strings.Split(before, sep), strings.Split(after, sep))
}
func printDiffRecords(suppressedKinds []string, kind string, context int, diffs []difflib.DiffRecord, to io.Writer) {
for _, ckind := range suppressedKinds {
if ckind == kind {
str := fmt.Sprintf("+ Changes suppressed on sensitive content of type %s\n", kind)
fmt.Fprintf(to, ansi.Color(str, "yellow"))
return
}
}
if context >= 0 {
distances := calculateDistances(diffs)
omitting := false
for i, diff := range diffs {
if distances[i] > context {
if !omitting {
fmt.Fprintln(to, "...")
omitting = true
}
} else {
omitting = false
printDiffRecord(diff, to)
}
}
} else {
for _, diff := range diffs {
printDiffRecord(diff, to)
}
}
}
func printDiffRecord(diff difflib.DiffRecord, to io.Writer) {
text := diff.Payload
switch diff.Delta {
case difflib.RightOnly:
fmt.Fprintf(to, "%s\n", ansi.Color("+ "+text, "green"))
case difflib.LeftOnly:
fmt.Fprintf(to, "%s\n", ansi.Color("- "+text, "red"))
case difflib.Common:
fmt.Fprintf(to, "%s\n", " "+text)
}
}
// Calculate distance of every diff-line to the closest change
func calculateDistances(diffs []difflib.DiffRecord) map[int]int {
distances := map[int]int{}
// Iterate forwards through diffs, set 'distance' based on closest 'change' before this line
change := -1
for i, diff := range diffs {
if diff.Delta != difflib.Common {
change = i
}
distance := math.MaxInt32
if change != -1 {
distance = i - change
}
distances[i] = distance
}
// Iterate backwards through diffs, reduce 'distance' based on closest 'change' after this line
change = -1
for i := len(diffs) - 1; i >= 0; i-- {
diff := diffs[i]
if diff.Delta != difflib.Common {
change = i
}
if change != -1 {
distance := change - i
if distance < distances[i] {
distances[i] = distance
}
}
}
return distances
}
// reIndexForRelease based on template names
func reIndexForRelease(index map[string]*manifest.MappingResult) map[string]*manifest.MappingResult {
// sort the index to iterate map in the same order
var keys []string
for key := range index {
keys = append(keys, key)
}
sort.Strings(keys)
// holds number of object in a single file
count := make(map[string]int)
newIndex := make(map[string]*manifest.MappingResult)
for key := range keys {
str := strings.Replace(strings.Split(index[keys[key]].Content, "\n")[0], "# Source: ", "", 1)
if _, ok := newIndex[str]; ok {
count[str]++
str += fmt.Sprintf(" %d", count[str])
newIndex[str] = index[keys[key]]
} else {
newIndex[str] = index[keys[key]]
count[str]++
}
}
return newIndex
}
func sortedKeys(manifests map[string]*manifest.MappingResult) []string {
var keys []string
for key := range manifests {
keys = append(keys, key)
}
sort.Strings(keys)
return keys
}