Debian Codegraph @

v5/merge.go

raw symbols SCIP
1 package jsonpatch
2
3 import (
4 "bytes"
5 "encoding/json"
6 "fmt"
7 "reflect"
8 )
9
10 func merge(cur, patch *lazyNode, mergeMerge bool) *lazyNode {
11 curDoc, err := cur.intoDoc()
12
13 if err != nil {
14 pruneNulls(patch)
15 return patch
16 }
17
18 patchDoc, err := patch.intoDoc()
19
20 if err != nil {
21 return patch
22 }
23
24 mergeDocs(curDoc, patchDoc, mergeMerge)
25
26 return cur
27 }
28
29 func mergeDocs(doc, patch *partialDoc, mergeMerge bool) {
30 for k, v := range patch.obj {
31 if v == nil {
32 if mergeMerge {
33 idx := -1
34 for i, key := range doc.keys {
35 if key == k {
36 idx = i
37 break
38 }
39 }
40 if idx == -1 {
41 doc.keys = append(doc.keys, k)
42 }
43 doc.obj[k] = nil
44 } else {
45 _ = doc.remove(k, &ApplyOptions{})
46 }
47 } else {
48 cur, ok := doc.obj[k]
49
50 if !ok || cur == nil {
51 if !mergeMerge {
52 pruneNulls(v)
53 }
54 _ = doc.set(k, v, &ApplyOptions{})
55 } else {
56 _ = doc.set(k, merge(cur, v, mergeMerge), &ApplyOptions{})
57 }
58 }
59 }
60 }
61
62 func pruneNulls(n *lazyNode) {
63 sub, err := n.intoDoc()
64
65 if err == nil {
66 pruneDocNulls(sub)
67 } else {
68 ary, err := n.intoAry()
69
70 if err == nil {
71 pruneAryNulls(ary)
72 }
73 }
74 }
75
76 func pruneDocNulls(doc *partialDoc) *partialDoc {
77 for k, v := range doc.obj {
78 if v == nil {
79 _ = doc.remove(k, &ApplyOptions{})
80 } else {
81 pruneNulls(v)
82 }
83 }
84
85 return doc
86 }
87
88 func pruneAryNulls(ary *partialArray) *partialArray {
89 newAry := []*lazyNode{}
90
91 for _, v := range *ary {
92 if v != nil {
93 pruneNulls(v)
94 }
95 newAry = append(newAry, v)
96 }
97
98 *ary = newAry
99
100 return ary
101 }
102
103 var errBadJSONDoc = fmt.Errorf("Invalid JSON Document")
104 var errBadJSONPatch = fmt.Errorf("Invalid JSON Patch")
105 var errBadMergeTypes = fmt.Errorf("Mismatched JSON Documents")
106
107 // MergeMergePatches merges two merge patches together, such that
108 // applying this resulting merged merge patch to a document yields the same
109 // as merging each merge patch to the document in succession.
110 func MergeMergePatches(patch1Data, patch2Data []byte) ([]byte, error) {
111 return doMergePatch(patch1Data, patch2Data, true)
112 }
113
114 // MergePatch merges the patchData into the docData.
115 func MergePatch(docData, patchData []byte) ([]byte, error) {
116 return doMergePatch(docData, patchData, false)
117 }
118
119 func doMergePatch(docData, patchData []byte, mergeMerge bool) ([]byte, error) {
120 doc := &partialDoc{}
121
122 docErr := json.Unmarshal(docData, doc)
123
124 patch := &partialDoc{}
125
126 patchErr := json.Unmarshal(patchData, patch)
127
128 if isSyntaxError(docErr) {
129 return nil, errBadJSONDoc
130 }
131
132 if isSyntaxError(patchErr) {
133 return nil, errBadJSONPatch
134 }
135
136 if docErr == nil && doc.obj == nil {
137 return nil, errBadJSONDoc
138 }
139
140 if patchErr == nil && patch.obj == nil {
141 return nil, errBadJSONPatch
142 }
143
144 if docErr != nil || patchErr != nil {
145 // Not an error, just not a doc, so we turn straight into the patch
146 if patchErr == nil {
147 if mergeMerge {
148 doc = patch
149 } else {
150 doc = pruneDocNulls(patch)
151 }
152 } else {
153 patchAry := &partialArray{}
154 patchErr = json.Unmarshal(patchData, patchAry)
155
156 if patchErr != nil {
157 return nil, errBadJSONPatch
158 }
159
160 pruneAryNulls(patchAry)
161
162 out, patchErr := json.Marshal(patchAry)
163
164 if patchErr != nil {
165 return nil, errBadJSONPatch
166 }
167
168 return out, nil
169 }
170 } else {
171 mergeDocs(doc, patch, mergeMerge)
172 }
173
174 return json.Marshal(doc)
175 }
176
177 func isSyntaxError(err error) bool {
178 if _, ok := err.(*json.SyntaxError); ok {
179 return true
180 }
181 if _, ok := err.(*syntaxError); ok {
182 return true
183 }
184 return false
185 }
186
187 // resemblesJSONArray indicates whether the byte-slice "appears" to be
188 // a JSON array or not.
189 // False-positives are possible, as this function does not check the internal
190 // structure of the array. It only checks that the outer syntax is present and
191 // correct.
192 func resemblesJSONArray(input []byte) bool {
193 input = bytes.TrimSpace(input)
194
195 hasPrefix := bytes.HasPrefix(input, []byte("["))
196 hasSuffix := bytes.HasSuffix(input, []byte("]"))
197
198 return hasPrefix && hasSuffix
199 }
200
201 // CreateMergePatch will return a merge patch document capable of converting
202 // the original document(s) to the modified document(s).
203 // The parameters can be bytes of either two JSON Documents, or two arrays of
204 // JSON documents.
205 // The merge patch returned follows the specification defined at http://tools.ietf.org/html/draft-ietf-appsawg-json-merge-patch-07
206 func CreateMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
207 originalResemblesArray := resemblesJSONArray(originalJSON)
208 modifiedResemblesArray := resemblesJSONArray(modifiedJSON)
209
210 // Do both byte-slices seem like JSON arrays?
211 if originalResemblesArray && modifiedResemblesArray {
212 return createArrayMergePatch(originalJSON, modifiedJSON)
213 }
214
215 // Are both byte-slices are not arrays? Then they are likely JSON objects...
216 if !originalResemblesArray && !modifiedResemblesArray {
217 return createObjectMergePatch(originalJSON, modifiedJSON)
218 }
219
220 // None of the above? Then return an error because of mismatched types.
221 return nil, errBadMergeTypes
222 }
223
224 // createObjectMergePatch will return a merge-patch document capable of
225 // converting the original document to the modified document.
226 func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
227 originalDoc := map[string]interface{}{}
228 modifiedDoc := map[string]interface{}{}
229
230 err := json.Unmarshal(originalJSON, &originalDoc)
231 if err != nil {
232 return nil, errBadJSONDoc
233 }
234
235 err = json.Unmarshal(modifiedJSON, &modifiedDoc)
236 if err != nil {
237 return nil, errBadJSONDoc
238 }
239
240 dest, err := getDiff(originalDoc, modifiedDoc)
241 if err != nil {
242 return nil, err
243 }
244
245 return json.Marshal(dest)
246 }
247
248 // createArrayMergePatch will return an array of merge-patch documents capable
249 // of converting the original document to the modified document for each
250 // pair of JSON documents provided in the arrays.
251 // Arrays of mismatched sizes will result in an error.
252 func createArrayMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
253 originalDocs := []json.RawMessage{}
254 modifiedDocs := []json.RawMessage{}
255
256 err := json.Unmarshal(originalJSON, &originalDocs)
257 if err != nil {
258 return nil, errBadJSONDoc
259 }
260
261 err = json.Unmarshal(modifiedJSON, &modifiedDocs)
262 if err != nil {
263 return nil, errBadJSONDoc
264 }
265
266 total := len(originalDocs)
267 if len(modifiedDocs) != total {
268 return nil, errBadJSONDoc
269 }
270
271 result := []json.RawMessage{}
272 for i := 0; i < len(originalDocs); i++ {
273 original := originalDocs[i]
274 modified := modifiedDocs[i]
275
276 patch, err := createObjectMergePatch(original, modified)
277 if err != nil {
278 return nil, err
279 }
280
281 result = append(result, json.RawMessage(patch))
282 }
283
284 return json.Marshal(result)
285 }
286
287 // Returns true if the array matches (must be json types).
288 // As is idiomatic for go, an empty array is not the same as a nil array.
289 func matchesArray(a, b []interface{}) bool {
290 if len(a) != len(b) {
291 return false
292 }
293 if (a == nil && b != nil) || (a != nil && b == nil) {
294 return false
295 }
296 for i := range a {
297 if !matchesValue(a[i], b[i]) {
298 return false
299 }
300 }
301 return true
302 }
303
304 // Returns true if the values matches (must be json types)
305 // The types of the values must match, otherwise it will always return false
306 // If two map[string]interface{} are given, all elements must match.
307 func matchesValue(av, bv interface{}) bool {
308 if reflect.TypeOf(av) != reflect.TypeOf(bv) {
309 return false
310 }
311 switch at := av.(type) {
312 case string:
313 bt := bv.(string)
314 if bt == at {
315 return true
316 }
317 case float64:
318 bt := bv.(float64)
319 if bt == at {
320 return true
321 }
322 case bool:
323 bt := bv.(bool)
324 if bt == at {
325 return true
326 }
327 case nil:
328 // Both nil, fine.
329 return true
330 case map[string]interface{}:
331 bt := bv.(map[string]interface{})
332 if len(bt) != len(at) {
333 return false
334 }
335 for key := range bt {
336 av, aOK := at[key]
337 bv, bOK := bt[key]
338 if aOK != bOK {
339 return false
340 }
341 if !matchesValue(av, bv) {
342 return false
343 }
344 }
345 return true
346 case []interface{}:
347 bt := bv.([]interface{})
348 return matchesArray(at, bt)
349 }
350 return false
351 }
352
353 // getDiff returns the (recursive) difference between a and b as a map[string]interface{}.
354 func getDiff(a, b map[string]interface{}) (map[string]interface{}, error) {
355 into := map[string]interface{}{}
356 for key, bv := range b {
357 av, ok := a[key]
358 // value was added
359 if !ok {
360 into[key] = bv
361 continue
362 }
363 // If types have changed, replace completely
364 if reflect.TypeOf(av) != reflect.TypeOf(bv) {
365 into[key] = bv
366 continue
367 }
368 // Types are the same, compare values
369 switch at := av.(type) {
370 case map[string]interface{}:
371 bt := bv.(map[string]interface{})
372 dst := make(map[string]interface{}, len(bt))
373 dst, err := getDiff(at, bt)
374 if err != nil {
375 return nil, err
376 }
377 if len(dst) > 0 {
378 into[key] = dst
379 }
380 case string, float64, bool:
381 if !matchesValue(av, bv) {
382 into[key] = bv
383 }
384 case []interface{}:
385 bt := bv.([]interface{})
386 if !matchesArray(at, bt) {
387 into[key] = bv
388 }
389 case nil:
390 switch bv.(type) {
391 case nil:
392 // Both nil, fine.
393 default:
394 into[key] = bv
395 }
396 default:
397 panic(fmt.Sprintf("Unknown type:%T in key %s", av, key))
398 }
399 }
400 // Now add all deleted values as nil
401 for key := range a {
402 _, found := b[key]
403 if !found {
404 into[key] = nil
405 }
406 }
407 return into, nil
408 }