-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreate.go
More file actions
168 lines (148 loc) · 4.58 KB
/
create.go
File metadata and controls
168 lines (148 loc) · 4.58 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
package jsonpatch
import (
"encoding/json"
"fmt"
"slices"
"strconv"
)
// CreatePatch generates a JSON Patch document (RFC 6902) that transforms
// the original JSON document into the modified JSON document.
// Both arguments must be valid JSON encoded as []byte or string (or any type
// with one of those underlying types).
func CreatePatch[D Document](original, modified D) (Patch, error) {
var origDoc, modDoc interface{}
if err := json.Unmarshal(toBytes(original), &origDoc); err != nil {
return nil, fmt.Errorf("failed to decode original document: %w", err)
}
if err := json.Unmarshal(toBytes(modified), &modDoc); err != nil {
return nil, fmt.Errorf("failed to decode modified document: %w", err)
}
patch := Patch{}
diff(&patch, "", origDoc, modDoc)
return patch, nil
}
// CreatePatchFromValues generates a JSON Patch from two already-parsed JSON values.
func CreatePatchFromValues(original, modified interface{}) Patch {
patch := Patch{}
diff(&patch, "", normalizeJSON(original), normalizeJSON(modified))
return patch
}
// diff recursively computes the differences between two JSON values
// and appends the corresponding operations to the patch.
func diff(patch *Patch, path string, original, modified interface{}) {
// Fast path for primitives — avoids reflect.DeepEqual overhead.
switch o := original.(type) {
case nil:
if modified == nil {
return
}
case bool:
if m, ok := modified.(bool); ok && o == m {
return
}
case float64:
if m, ok := modified.(float64); ok && o == m {
return
}
case string:
if m, ok := modified.(string); ok && o == m {
return
}
default:
// Composite types — fall through to structural comparison
if jsonEqual(original, modified) {
return
}
}
origObj, origIsObj := original.(map[string]interface{})
modObj, modIsObj := modified.(map[string]interface{})
origArr, origIsArr := original.([]interface{})
modArr, modIsArr := modified.([]interface{})
switch {
case origIsObj && modIsObj:
diffObjects(patch, path, origObj, modObj)
case origIsArr && modIsArr:
diffArrays(patch, path, origArr, modArr)
default:
// Types differ or primitive values differ — replace
*patch = append(*patch, newReplaceOp(path, modified))
}
}
// diffObjects computes the diff between two JSON objects.
func diffObjects(patch *Patch, path string, original, modified map[string]interface{}) {
// Collect all keys from both objects for deterministic ordering
keys := make(map[string]bool)
for k := range original {
keys[k] = true
}
for k := range modified {
keys[k] = true
}
sortedKeys := make([]string, 0, len(keys))
for k := range keys {
sortedKeys = append(sortedKeys, k)
}
slices.Sort(sortedKeys)
for _, key := range sortedKeys {
childPath := path + "/" + escapePointerToken(key)
origVal, inOrig := original[key]
modVal, inMod := modified[key]
switch {
case inOrig && inMod:
// Key exists in both — recurse
diff(patch, childPath, origVal, modVal)
case inOrig && !inMod:
// Key removed
*patch = append(*patch, newRemoveOp(childPath))
case !inOrig && inMod:
// Key added
*patch = append(*patch, newAddOp(childPath, modVal))
}
}
}
// diffArrays computes the diff between two JSON arrays.
// Uses a simple approach: compare element by element, then handle length differences.
func diffArrays(patch *Patch, path string, original, modified []interface{}) {
commonLen := len(original)
if len(modified) < commonLen {
commonLen = len(modified)
}
// Compare common elements
for i := 0; i < commonLen; i++ {
childPath := path + "/" + strconv.Itoa(i)
diff(patch, childPath, original[i], modified[i])
}
// Handle extra elements in modified (additions)
if len(modified) > len(original) {
for i := len(original); i < len(modified); i++ {
childPath := path + "/-"
*patch = append(*patch, newAddOp(childPath, modified[i]))
}
}
// Handle extra elements in original (removals)
// Remove from the end to avoid index shifting issues
if len(original) > len(modified) {
for i := len(original) - 1; i >= len(modified); i-- {
childPath := path + "/" + strconv.Itoa(i)
*patch = append(*patch, newRemoveOp(childPath))
}
}
}
// newAddOp creates an "add" operation.
func newAddOp(path string, value interface{}) Operation {
op, _ := NewOperation(OpAdd, path, value)
return op
}
// newRemoveOp creates a "remove" operation.
func newRemoveOp(path string) Operation {
return Operation{
Op: OpRemove,
Path: path,
hasPath: true,
}
}
// newReplaceOp creates a "replace" operation.
func newReplaceOp(path string, value interface{}) Operation {
op, _ := NewOperation(OpReplace, path, value)
return op
}