10 func merge(cur, patch *lazyNode, mergeMerge bool) *lazyNode {
11 curDoc, err := cur.intoDoc()
18 patchDoc, err := patch.intoDoc()
24 mergeDocs(curDoc, patchDoc, mergeMerge)
29 func mergeDocs(doc, patch *partialDoc, mergeMerge bool) {
30 for k, v := range *patch {
40 if !ok || cur == nil {
44 (*doc)[k] = merge(cur, v, mergeMerge)
50 func pruneNulls(n *lazyNode) {
51 sub, err := n.intoDoc()
56 ary, err := n.intoAry()
64 func pruneDocNulls(doc *partialDoc) *partialDoc {
65 for k, v := range *doc {
76 func pruneAryNulls(ary *partialArray) *partialArray {
77 newAry := []*lazyNode{}
79 for _, v := range *ary {
82 newAry = append(newAry, v)
91 var errBadJSONDoc = fmt.Errorf("Invalid JSON Document")
92 var errBadJSONPatch = fmt.Errorf("Invalid JSON Patch")
93 var errBadMergeTypes = fmt.Errorf("Mismatched JSON Documents")
95 // MergeMergePatches merges two merge patches together, such that
96 // applying this resulting merged merge patch to a document yields the same
97 // as merging each merge patch to the document in succession.
98 func MergeMergePatches(patch1Data, patch2Data []byte) ([]byte, error) {
99 return doMergePatch(patch1Data, patch2Data, true)
102 // MergePatch merges the patchData into the docData.
103 func MergePatch(docData, patchData []byte) ([]byte, error) {
104 return doMergePatch(docData, patchData, false)
107 func doMergePatch(docData, patchData []byte, mergeMerge bool) ([]byte, error) {
110 docErr := json.Unmarshal(docData, doc)
112 patch := &partialDoc{}
114 patchErr := json.Unmarshal(patchData, patch)
116 if _, ok := docErr.(*json.SyntaxError); ok {
117 return nil, errBadJSONDoc
120 if _, ok := patchErr.(*json.SyntaxError); ok {
121 return nil, errBadJSONPatch
124 if docErr == nil && *doc == nil {
125 return nil, errBadJSONDoc
128 if patchErr == nil && *patch == nil {
129 return nil, errBadJSONPatch
132 if docErr != nil || patchErr != nil {
133 // Not an error, just not a doc, so we turn straight into the patch
138 doc = pruneDocNulls(patch)
141 patchAry := &partialArray{}
142 patchErr = json.Unmarshal(patchData, patchAry)
145 return nil, errBadJSONPatch
148 pruneAryNulls(patchAry)
150 out, patchErr := json.Marshal(patchAry)
153 return nil, errBadJSONPatch
159 mergeDocs(doc, patch, mergeMerge)
162 return json.Marshal(doc)
165 // resemblesJSONArray indicates whether the byte-slice "appears" to be
166 // a JSON array or not.
167 // False-positives are possible, as this function does not check the internal
168 // structure of the array. It only checks that the outer syntax is present and
170 func resemblesJSONArray(input []byte) bool {
171 input = bytes.TrimSpace(input)
173 hasPrefix := bytes.HasPrefix(input, []byte("["))
174 hasSuffix := bytes.HasSuffix(input, []byte("]"))
176 return hasPrefix && hasSuffix
179 // CreateMergePatch will return a merge patch document capable of converting
180 // the original document(s) to the modified document(s).
181 // The parameters can be bytes of either two JSON Documents, or two arrays of
183 // The merge patch returned follows the specification defined at http://tools.ietf.org/html/draft-ietf-appsawg-json-merge-patch-07
184 func CreateMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
185 originalResemblesArray := resemblesJSONArray(originalJSON)
186 modifiedResemblesArray := resemblesJSONArray(modifiedJSON)
188 // Do both byte-slices seem like JSON arrays?
189 if originalResemblesArray && modifiedResemblesArray {
190 return createArrayMergePatch(originalJSON, modifiedJSON)
193 // Are both byte-slices are not arrays? Then they are likely JSON objects...
194 if !originalResemblesArray && !modifiedResemblesArray {
195 return createObjectMergePatch(originalJSON, modifiedJSON)
198 // None of the above? Then return an error because of mismatched types.
199 return nil, errBadMergeTypes
202 // createObjectMergePatch will return a merge-patch document capable of
203 // converting the original document to the modified document.
204 func createObjectMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
205 originalDoc := map[string]interface{}{}
206 modifiedDoc := map[string]interface{}{}
208 err := json.Unmarshal(originalJSON, &originalDoc)
210 return nil, errBadJSONDoc
213 err = json.Unmarshal(modifiedJSON, &modifiedDoc)
215 return nil, errBadJSONDoc
218 dest, err := getDiff(originalDoc, modifiedDoc)
223 return json.Marshal(dest)
226 // createArrayMergePatch will return an array of merge-patch documents capable
227 // of converting the original document to the modified document for each
228 // pair of JSON documents provided in the arrays.
229 // Arrays of mismatched sizes will result in an error.
230 func createArrayMergePatch(originalJSON, modifiedJSON []byte) ([]byte, error) {
231 originalDocs := []json.RawMessage{}
232 modifiedDocs := []json.RawMessage{}
234 err := json.Unmarshal(originalJSON, &originalDocs)
236 return nil, errBadJSONDoc
239 err = json.Unmarshal(modifiedJSON, &modifiedDocs)
241 return nil, errBadJSONDoc
244 total := len(originalDocs)
245 if len(modifiedDocs) != total {
246 return nil, errBadJSONDoc
249 result := []json.RawMessage{}
250 for i := 0; i < len(originalDocs); i++ {
251 original := originalDocs[i]
252 modified := modifiedDocs[i]
254 patch, err := createObjectMergePatch(original, modified)
259 result = append(result, json.RawMessage(patch))
262 return json.Marshal(result)
265 // Returns true if the array matches (must be json types).
266 // As is idiomatic for go, an empty array is not the same as a nil array.
267 func matchesArray(a, b []interface{}) bool {
268 if len(a) != len(b) {
271 if (a == nil && b != nil) || (a != nil && b == nil) {
275 if !matchesValue(a[i], b[i]) {
282 // Returns true if the values matches (must be json types)
283 // The types of the values must match, otherwise it will always return false
284 // If two map[string]interface{} are given, all elements must match.
285 func matchesValue(av, bv interface{}) bool {
286 if reflect.TypeOf(av) != reflect.TypeOf(bv) {
289 switch at := av.(type) {
308 case map[string]interface{}:
309 bt := bv.(map[string]interface{})
310 for key := range at {
311 if !matchesValue(at[key], bt[key]) {
315 for key := range bt {
316 if !matchesValue(at[key], bt[key]) {
322 bt := bv.([]interface{})
323 return matchesArray(at, bt)
328 // getDiff returns the (recursive) difference between a and b as a map[string]interface{}.
329 func getDiff(a, b map[string]interface{}) (map[string]interface{}, error) {
330 into := map[string]interface{}{}
331 for key, bv := range b {
338 // If types have changed, replace completely
339 if reflect.TypeOf(av) != reflect.TypeOf(bv) {
343 // Types are the same, compare values
344 switch at := av.(type) {
345 case map[string]interface{}:
346 bt := bv.(map[string]interface{})
347 dst := make(map[string]interface{}, len(bt))
348 dst, err := getDiff(at, bt)
355 case string, float64, bool:
356 if !matchesValue(av, bv) {
360 bt := bv.([]interface{})
361 if !matchesArray(at, bt) {
372 panic(fmt.Sprintf("Unknown type:%T in key %s", av, key))
375 // Now add all deleted values as nil