Debian Codegraph @

deltas.go

raw
1 package gojsondiff
2
3 import (
4 "errors"
5 dmp "github.com/sergi/go-diff/diffmatchpatch"
6 "reflect"
7 "strconv"
8 )
9
10 // A Delta represents an atomic difference between two JSON objects.
11 type Delta interface {
12 // Similarity calculates the similarity of the Delta values.
13 // The return value is normalized from 0 to 1,
14 // 0 is completely different and 1 is they are same
15 Similarity() (similarity float64)
16 }
17
18 // To cache the calculated similarity,
19 // concrete Deltas can use similariter and similarityCache
20 type similariter interface {
21 similarity() (similarity float64)
22 }
23
24 type similarityCache struct {
25 similariter
26 value float64
27 }
28
29 func newSimilarityCache(sim similariter) similarityCache {
30 cache := similarityCache{similariter: sim, value: -1}
31 return cache
32 }
33
34 func (cache similarityCache) Similarity() (similarity float64) {
35 if cache.value < 0 {
36 cache.value = cache.similariter.similarity()
37 }
38 return cache.value
39 }
40
41 // A Position represents the position of a Delta in an object or an array.
42 type Position interface {
43 // String returns the position as a string
44 String() (name string)
45
46 // CompareTo returns a true if the Position is smaller than another Position.
47 // This function is used to sort Positions by the sort package.
48 CompareTo(another Position) bool
49 }
50
51 // A Name is a Postition with a string, which means the delta is in an object.
52 type Name string
53
54 func (n Name) String() (name string) {
55 return string(n)
56 }
57
58 func (n Name) CompareTo(another Position) bool {
59 return n < another.(Name)
60 }
61
62 // A Index is a Position with an int value, which means the Delta is in an Array.
63 type Index int
64
65 func (i Index) String() (name string) {
66 return strconv.Itoa(int(i))
67 }
68
69 func (i Index) CompareTo(another Position) bool {
70 return i < another.(Index)
71 }
72
73 // A PreDelta is a Delta that has a position of the left side JSON object.
74 // Deltas implements this interface should be applies before PostDeltas.
75 type PreDelta interface {
76 // PrePosition returns the Position.
77 PrePosition() Position
78
79 // PreApply applies the delta to object.
80 PreApply(object interface{}) interface{}
81 }
82
83 type preDelta struct{ Position }
84
85 func (i preDelta) PrePosition() Position {
86 return Position(i.Position)
87 }
88
89 type preDeltas []PreDelta
90
91 // for sorting
92 func (s preDeltas) Len() int {
93 return len(s)
94 }
95
96 // for sorting
97 func (s preDeltas) Swap(i, j int) {
98 s[i], s[j] = s[j], s[i]
99 }
100
101 // for sorting
102 func (s preDeltas) Less(i, j int) bool {
103 return !s[i].PrePosition().CompareTo(s[j].PrePosition())
104 }
105
106 // A PreDelta is a Delta that has a position of the right side JSON object.
107 // Deltas implements this interface should be applies after PreDeltas.
108 type PostDelta interface {
109 // PostPosition returns the Position.
110 PostPosition() Position
111
112 // PostApply applies the delta to object.
113 PostApply(object interface{}) interface{}
114 }
115
116 type postDelta struct{ Position }
117
118 func (i postDelta) PostPosition() Position {
119 return Position(i.Position)
120 }
121
122 type postDeltas []PostDelta
123
124 // for sorting
125 func (s postDeltas) Len() int {
126 return len(s)
127 }
128
129 // for sorting
130 func (s postDeltas) Swap(i, j int) {
131 s[i], s[j] = s[j], s[i]
132 }
133
134 // for sorting
135 func (s postDeltas) Less(i, j int) bool {
136 return s[i].PostPosition().CompareTo(s[j].PostPosition())
137 }
138
139 // An Object is a Delta that represents an object of JSON
140 type Object struct {
141 postDelta
142 similarityCache
143
144 // Deltas holds internal Deltas
145 Deltas []Delta
146 }
147
148 // NewObject returns an Object
149 func NewObject(position Position, deltas []Delta) *Object {
150 d := Object{postDelta: postDelta{position}, Deltas: deltas}
151 d.similarityCache = newSimilarityCache(&d)
152 return &d
153 }
154
155 func (d *Object) PostApply(object interface{}) interface{} {
156 switch object.(type) {
157 case map[string]interface{}:
158 o := object.(map[string]interface{})
159 n := string(d.PostPosition().(Name))
160 o[n] = applyDeltas(d.Deltas, o[n])
161 case []interface{}:
162 o := object.([]interface{})
163 n := int(d.PostPosition().(Index))
164 o[n] = applyDeltas(d.Deltas, o[n])
165 }
166 return object
167 }
168
169 func (d *Object) similarity() (similarity float64) {
170 similarity = deltasSimilarity(d.Deltas)
171 return
172 }
173
174 // An Array is a Delta that represents an array of JSON
175 type Array struct {
176 postDelta
177 similarityCache
178
179 // Deltas holds internal Deltas
180 Deltas []Delta
181 }
182
183 // NewArray returns an Array
184 func NewArray(position Position, deltas []Delta) *Array {
185 d := Array{postDelta: postDelta{position}, Deltas: deltas}
186 d.similarityCache = newSimilarityCache(&d)
187 return &d
188 }
189
190 func (d *Array) PostApply(object interface{}) interface{} {
191 switch object.(type) {
192 case map[string]interface{}:
193 o := object.(map[string]interface{})
194 n := string(d.PostPosition().(Name))
195 o[n] = applyDeltas(d.Deltas, o[n])
196 case []interface{}:
197 o := object.([]interface{})
198 n := int(d.PostPosition().(Index))
199 o[n] = applyDeltas(d.Deltas, o[n])
200 }
201 return object
202 }
203
204 func (d *Array) similarity() (similarity float64) {
205 similarity = deltasSimilarity(d.Deltas)
206 return
207 }
208
209 // An Added represents a new added field of an object or an array
210 type Added struct {
211 postDelta
212 similarityCache
213
214 // Values holds the added value
215 Value interface{}
216 }
217
218 // NewAdded returns a new Added
219 func NewAdded(position Position, value interface{}) *Added {
220 d := Added{postDelta: postDelta{position}, Value: value}
221 return &d
222 }
223
224 func (d *Added) PostApply(object interface{}) interface{} {
225 switch object.(type) {
226 case map[string]interface{}:
227 object.(map[string]interface{})[string(d.PostPosition().(Name))] = d.Value
228 case []interface{}:
229 i := int(d.PostPosition().(Index))
230 o := object.([]interface{})
231 if i < len(o) {
232 o = append(o, 0) //dummy
233 copy(o[i+1:], o[i:])
234 o[i] = d.Value
235 object = o
236 } else {
237 object = append(o, d.Value)
238 }
239 }
240
241 return object
242 }
243
244 func (d *Added) similarity() (similarity float64) {
245 return 0
246 }
247
248 // A Modified represents a field whose value is changed.
249 type Modified struct {
250 postDelta
251 similarityCache
252
253 // The value before modification
254 OldValue interface{}
255
256 // The value after modification
257 NewValue interface{}
258 }
259
260 // NewModified returns a Modified
261 func NewModified(position Position, oldValue, newValue interface{}) *Modified {
262 d := Modified{
263 postDelta: postDelta{position},
264 OldValue: oldValue,
265 NewValue: newValue,
266 }
267 d.similarityCache = newSimilarityCache(&d)
268 return &d
269
270 }
271
272 func (d *Modified) PostApply(object interface{}) interface{} {
273 switch object.(type) {
274 case map[string]interface{}:
275 // TODO check old value
276 object.(map[string]interface{})[string(d.PostPosition().(Name))] = d.NewValue
277 case []interface{}:
278 object.([]interface{})[int(d.PostPosition().(Index))] = d.NewValue
279 }
280 return object
281 }
282
283 func (d *Modified) similarity() (similarity float64) {
284 similarity += 0.3 // at least, they are at the same position
285 if reflect.TypeOf(d.OldValue) == reflect.TypeOf(d.NewValue) {
286 similarity += 0.3 // types are same
287
288 switch d.OldValue.(type) {
289 case string:
290 similarity += 0.4 * stringSimilarity(d.OldValue.(string), d.NewValue.(string))
291 case float64:
292 ratio := d.OldValue.(float64) / d.NewValue.(float64)
293 if ratio > 1 {
294 ratio = 1 / ratio
295 }
296 similarity += 0.4 * ratio
297 }
298 }
299 return
300 }
301
302 // A TextDiff represents a Modified with TextDiff between the old and the new values.
303 type TextDiff struct {
304 Modified
305
306 // Diff string
307 Diff []dmp.Patch
308 }
309
310 // NewTextDiff returns
311 func NewTextDiff(position Position, diff []dmp.Patch, oldValue, newValue interface{}) *TextDiff {
312 d := TextDiff{
313 Modified: *NewModified(position, oldValue, newValue),
314 Diff: diff,
315 }
316 return &d
317 }
318
319 func (d *TextDiff) PostApply(object interface{}) interface{} {
320 switch object.(type) {
321 case map[string]interface{}:
322 o := object.(map[string]interface{})
323 i := string(d.PostPosition().(Name))
324 // TODO error
325 d.OldValue = o[i]
326 // TODO error
327 d.patch()
328 o[i] = d.NewValue
329 case []interface{}:
330 o := object.([]interface{})
331 i := d.PostPosition().(Index)
332 d.OldValue = o[i]
333 // TODO error
334 d.patch()
335 o[i] = d.NewValue
336 }
337 return object
338 }
339
340 func (d *TextDiff) patch() error {
341 if d.OldValue == nil {
342 return errors.New("Old Value is not set")
343 }
344 patcher := dmp.New()
345 patched, successes := patcher.PatchApply(d.Diff, d.OldValue.(string))
346 for _, success := range successes {
347 if !success {
348 return errors.New("Failed to apply a patch")
349 }
350 }
351 d.NewValue = patched
352 return nil
353 }
354
355 func (d *TextDiff) DiffString() string {
356 dmp := dmp.New()
357 return dmp.PatchToText(d.Diff)
358 }
359
360 // A Delted represents deleted field or index of an Object or an Array.
361 type Deleted struct {
362 preDelta
363
364 // The value deleted
365 Value interface{}
366 }
367
368 // NewDeleted returns a Deleted
369 func NewDeleted(position Position, value interface{}) *Deleted {
370 d := Deleted{
371 preDelta: preDelta{position},
372 Value: value,
373 }
374 return &d
375
376 }
377
378 func (d *Deleted) PreApply(object interface{}) interface{} {
379 switch object.(type) {
380 case map[string]interface{}:
381 // TODO check old value
382 delete(object.(map[string]interface{}), string(d.PrePosition().(Name)))
383 case []interface{}:
384 i := int(d.PrePosition().(Index))
385 o := object.([]interface{})
386 object = append(o[:i], o[i+1:]...)
387 }
388 return object
389 }
390
391 func (d Deleted) Similarity() (similarity float64) {
392 return 0
393 }
394
395 // A Moved represents field that is moved, which means the index or name is
396 // changed. Note that, in this library, assigning a Moved and a Modified to
397 // a single position is not allowed. For the compatibility with jsondiffpatch,
398 // the Moved in this library can hold the old and new value in it.
399 type Moved struct {
400 preDelta
401 postDelta
402 similarityCache
403 // The value before moving
404 Value interface{}
405 // The delta applied after moving (for compatibility)
406 Delta interface{}
407 }
408
409 func NewMoved(oldPosition Position, newPosition Position, value interface{}, delta Delta) *Moved {
410 d := Moved{
411 preDelta: preDelta{oldPosition},
412 postDelta: postDelta{newPosition},
413 Value: value,
414 Delta: delta,
415 }
416 d.similarityCache = newSimilarityCache(&d)
417 return &d
418 }
419
420 func (d *Moved) PreApply(object interface{}) interface{} {
421 switch object.(type) {
422 case map[string]interface{}:
423 //not supported
424 case []interface{}:
425 i := int(d.PrePosition().(Index))
426 o := object.([]interface{})
427 d.Value = o[i]
428 object = append(o[:i], o[i+1:]...)
429 }
430 return object
431 }
432
433 func (d *Moved) PostApply(object interface{}) interface{} {
434 switch object.(type) {
435 case map[string]interface{}:
436 //not supported
437 case []interface{}:
438 i := int(d.PostPosition().(Index))
439 o := object.([]interface{})
440 o = append(o, 0) //dummy
441 copy(o[i+1:], o[i:])
442 o[i] = d.Value
443 object = o
444 }
445
446 if d.Delta != nil {
447 d.Delta.(PostDelta).PostApply(object)
448 }
449
450 return object
451 }
452
453 func (d *Moved) similarity() (similarity float64) {
454 similarity = 0.6 // as type and contents are same
455 ratio := float64(d.PrePosition().(Index)) / float64(d.PostPosition().(Index))
456 if ratio > 1 {
457 ratio = 1 / ratio
458 }
459 similarity += 0.4 * ratio
460 return
461 }