forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
patch.go
434 lines (387 loc) · 12.2 KB
/
patch.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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
/*
Copyright 2014 Google Inc. All rights reserved.
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 strategicpatch
import (
"encoding/json"
"fmt"
"reflect"
"sort"
forkedjson "github.com/GoogleCloudPlatform/kubernetes/third_party/forked/json"
)
// An alternate implementation of JSON Merge Patch
// (https://tools.ietf.org/html/rfc7386) which supports the ability to annotate
// certain fields with metadata that indicates whether the elements of JSON
// lists should be merged or replaced.
//
// For more information, see the PATCH section of docs/api-conventions.md.
func StrategicMergePatchData(original, patch []byte, dataStruct interface{}) ([]byte, error) {
var o map[string]interface{}
err := json.Unmarshal(original, &o)
if err != nil {
return nil, err
}
var p map[string]interface{}
err = json.Unmarshal(patch, &p)
if err != nil {
return nil, err
}
t := reflect.TypeOf(dataStruct)
if t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf("strategic merge patch needs a struct, %s received instead", t.Kind().String())
}
result, err := mergeMap(o, p, t)
if err != nil {
return nil, err
}
return json.Marshal(result)
}
const specialKey = "$patch"
// Merge fields from a patch map into the original map. Note: This may modify
// both the original map and the patch because getting a deep copy of a map in
// golang is highly non-trivial.
func mergeMap(original, patch map[string]interface{}, t reflect.Type) (map[string]interface{}, error) {
// If the map contains "$patch: replace", don't merge it, just use the
// patch map directly. Later on, can add a non-recursive replace that only
// affects the map that the $patch is in.
if v, ok := patch[specialKey]; ok {
if v == "replace" {
delete(patch, specialKey)
return patch, nil
}
return nil, fmt.Errorf("unknown patch type found: %s", v)
}
// nil is an accepted value for original to simplify logic in other places.
// If original is nil, create a map so if patch requires us to modify the
// map, it'll work.
if original == nil {
original = map[string]interface{}{}
}
// Start merging the patch into the original.
for k, patchV := range patch {
// If the value of this key is null, delete the key if it exists in the
// original. Otherwise, skip it.
if patchV == nil {
if _, ok := original[k]; ok {
delete(original, k)
}
continue
}
_, ok := original[k]
if !ok {
// If it's not in the original document, just take the patch value.
original[k] = patchV
continue
}
// If they're both maps or lists, recurse into the value.
// First find the fieldPatchStrategy and fieldPatchMergeKey.
fieldType, fieldPatchStrategy, fieldPatchMergeKey, err := forkedjson.LookupPatchMetadata(t, k)
if err != nil {
return nil, err
}
originalType := reflect.TypeOf(original[k])
patchType := reflect.TypeOf(patchV)
if originalType == patchType {
if originalType.Kind() == reflect.Map && fieldPatchStrategy != "replace" {
typedOriginal := original[k].(map[string]interface{})
typedPatch := patchV.(map[string]interface{})
var err error
original[k], err = mergeMap(typedOriginal, typedPatch, fieldType)
if err != nil {
return nil, err
}
continue
}
if originalType.Kind() == reflect.Slice && fieldPatchStrategy == "merge" {
elemType := fieldType.Elem()
typedOriginal := original[k].([]interface{})
typedPatch := patchV.([]interface{})
var err error
original[k], err = mergeSlice(typedOriginal, typedPatch, elemType, fieldPatchMergeKey)
if err != nil {
return nil, err
}
continue
}
}
// If originalType and patchType are different OR the types are both
// maps or slices but we're just supposed to replace them, just take
// the value from patch.
original[k] = patchV
}
return original, nil
}
// Merge two slices together. Note: This may modify both the original slice and
// the patch because getting a deep copy of a slice in golang is highly
// non-trivial.
func mergeSlice(original, patch []interface{}, elemType reflect.Type, mergeKey string) ([]interface{}, error) {
if len(original) == 0 && len(patch) == 0 {
return original, nil
}
// All the values must be of the same type, but not a list.
t, err := sliceElementType(original, patch)
if err != nil {
return nil, fmt.Errorf("types of list elements need to be the same, type: %s: %v",
elemType.Kind().String(), err)
}
if t.Kind() == reflect.Slice {
return nil, fmt.Errorf("not supporting merging lists of lists yet")
}
// If the elements are not maps, merge the slices of scalars.
if t.Kind() != reflect.Map {
// Maybe in the future add a "concat" mode that doesn't
// uniqify.
both := append(original, patch...)
return uniqifyScalars(both), nil
}
if mergeKey == "" {
return nil, fmt.Errorf("cannot merge lists without merge key for type %s", elemType.Kind().String())
}
// First look for any special $patch elements.
patchWithoutSpecialElements := []interface{}{}
replace := false
for _, v := range patch {
typedV := v.(map[string]interface{})
patchType, ok := typedV[specialKey]
if ok {
if patchType == "delete" {
mergeValue, ok := typedV[mergeKey]
if ok {
_, originalKey, found := findMapInSliceBasedOnKeyValue(original, mergeKey, mergeValue)
if found {
// Delete the element at originalKey.
original = append(original[:originalKey], original[originalKey+1:]...)
}
} else {
return nil, fmt.Errorf("delete patch type with no merge key defined")
}
} else if patchType == "replace" {
replace = true
// Continue iterating through the array to prune any other $patch elements.
} else if patchType == "merge" {
return nil, fmt.Errorf("merging lists cannot yet be specified in the patch")
} else {
return nil, fmt.Errorf("unknown patch type found: %s", patchType)
}
} else {
patchWithoutSpecialElements = append(patchWithoutSpecialElements, v)
}
}
if replace {
return patchWithoutSpecialElements, nil
}
patch = patchWithoutSpecialElements
// Merge patch into original.
for _, v := range patch {
// Because earlier we confirmed that all the elements are maps.
typedV := v.(map[string]interface{})
mergeValue, ok := typedV[mergeKey]
if !ok {
return nil, fmt.Errorf("all list elements need the merge key %s", mergeKey)
}
// If we find a value with this merge key value in original, merge the
// maps. Otherwise append onto original.
originalMap, originalKey, found := findMapInSliceBasedOnKeyValue(original, mergeKey, mergeValue)
if found {
var mergedMaps interface{}
var err error
// Merge into original.
mergedMaps, err = mergeMap(originalMap, typedV, elemType)
if err != nil {
return nil, err
}
original[originalKey] = mergedMaps
} else {
original = append(original, v)
}
}
return original, nil
}
// This panics if any element of the slice is not a map.
func findMapInSliceBasedOnKeyValue(m []interface{}, key string, value interface{}) (map[string]interface{}, int, bool) {
for k, v := range m {
typedV := v.(map[string]interface{})
valueToMatch, ok := typedV[key]
if ok && valueToMatch == value {
return typedV, k, true
}
}
return nil, 0, false
}
// This function takes a JSON map and sorts all the lists that should be merged
// by key. This is needed by tests because in JSON, list order is significant,
// but in Strategic Merge Patch, merge lists do not have significant order.
// Sorting the lists allows for order-insensitive comparison of patched maps.
func sortMergeListsByName(mapJSON []byte, dataStruct interface{}) ([]byte, error) {
var m map[string]interface{}
err := json.Unmarshal(mapJSON, &m)
if err != nil {
return nil, err
}
newM, err := sortMergeListsByNameMap(m, reflect.TypeOf(dataStruct))
if err != nil {
return nil, err
}
return json.Marshal(newM)
}
func sortMergeListsByNameMap(s map[string]interface{}, t reflect.Type) (map[string]interface{}, error) {
newS := map[string]interface{}{}
for k, v := range s {
fieldType, fieldPatchStrategy, fieldPatchMergeKey, err := forkedjson.LookupPatchMetadata(t, k)
if err != nil {
return nil, err
}
// If v is a map or a merge slice, recurse.
if typedV, ok := v.(map[string]interface{}); ok {
var err error
v, err = sortMergeListsByNameMap(typedV, fieldType)
if err != nil {
return nil, err
}
} else if typedV, ok := v.([]interface{}); ok {
if fieldPatchStrategy == "merge" {
var err error
v, err = sortMergeListsByNameArray(typedV, fieldType.Elem(), fieldPatchMergeKey)
if err != nil {
return nil, err
}
}
}
newS[k] = v
}
return newS, nil
}
func sortMergeListsByNameArray(s []interface{}, elemType reflect.Type, mergeKey string) ([]interface{}, error) {
if len(s) == 0 {
return s, nil
}
// We don't support lists of lists yet.
t, err := sliceElementType(s)
if err != nil {
return nil, err
}
if t.Kind() == reflect.Slice {
return nil, fmt.Errorf("not supporting lists of lists yet")
}
// If the elements are not maps...
if t.Kind() != reflect.Map {
// Sort the elements, because they may have been merged out of order.
return uniqifyAndSortScalars(s), nil
}
// Elements are maps - if one of the keys of the map is a map or a
// list, we need to recurse into it.
newS := []interface{}{}
for _, elem := range s {
typedElem := elem.(map[string]interface{})
newElem, err := sortMergeListsByNameMap(typedElem, elemType)
if err != nil {
return nil, err
}
newS = append(newS, newElem)
}
// Sort the maps.
newS = sortMapsBasedOnField(newS, mergeKey)
return newS, nil
}
func sortMapsBasedOnField(m []interface{}, fieldName string) []interface{} {
mapM := []map[string]interface{}{}
for _, v := range m {
mapM = append(mapM, v.(map[string]interface{}))
}
ss := SortableSliceOfMaps{mapM, fieldName}
sort.Sort(ss)
newM := []interface{}{}
for _, v := range ss.s {
newM = append(newM, v)
}
return newM
}
type SortableSliceOfMaps struct {
s []map[string]interface{}
k string // key to sort on
}
func (ss SortableSliceOfMaps) Len() int {
return len(ss.s)
}
func (ss SortableSliceOfMaps) Less(i, j int) bool {
iStr := fmt.Sprintf("%v", ss.s[i][ss.k])
jStr := fmt.Sprintf("%v", ss.s[j][ss.k])
return sort.StringsAreSorted([]string{iStr, jStr})
}
func (ss SortableSliceOfMaps) Swap(i, j int) {
tmp := ss.s[i]
ss.s[i] = ss.s[j]
ss.s[j] = tmp
}
func uniqifyAndSortScalars(s []interface{}) []interface{} {
s = uniqifyScalars(s)
ss := SortableSliceOfScalars{s}
sort.Sort(ss)
return ss.s
}
func uniqifyScalars(s []interface{}) []interface{} {
// Clever algorithm to uniqify.
length := len(s) - 1
for i := 0; i < length; i++ {
for j := i + 1; j <= length; j++ {
if s[i] == s[j] {
s[j] = s[length]
s = s[0:length]
length--
j--
}
}
}
return s
}
type SortableSliceOfScalars struct {
s []interface{}
}
func (ss SortableSliceOfScalars) Len() int {
return len(ss.s)
}
func (ss SortableSliceOfScalars) Less(i, j int) bool {
iStr := fmt.Sprintf("%v", ss.s[i])
jStr := fmt.Sprintf("%v", ss.s[j])
return sort.StringsAreSorted([]string{iStr, jStr})
}
func (ss SortableSliceOfScalars) Swap(i, j int) {
tmp := ss.s[i]
ss.s[i] = ss.s[j]
ss.s[j] = tmp
}
// Returns the type of the elements of N slice(s). If the type is different,
// returns an error.
func sliceElementType(slices ...[]interface{}) (reflect.Type, error) {
var prevType reflect.Type
for _, s := range slices {
// Go through elements of all given slices and make sure they are all the same type.
for _, v := range s {
currentType := reflect.TypeOf(v)
if prevType == nil {
prevType = currentType
} else {
if prevType != currentType {
return nil, fmt.Errorf("at least two types found: %s and %s", prevType, currentType)
}
prevType = currentType
}
}
}
if prevType == nil {
return nil, fmt.Errorf("no elements in any given slices")
}
return prevType, nil
}