| 1 |
// Package gojsondiff implements "Diff" that compares two JSON objects and |
| 2 |
// generates Deltas that describes differences between them. The package also |
| 3 |
// provides "Patch" that apply Deltas to a JSON object. |
| 4 |
package gojsondiff |
| 5 |
|
| 6 |
import ( |
| 7 |
"container/list" |
| 8 |
"encoding/json" |
| 9 |
"reflect" |
| 10 |
"sort" |
| 11 |
|
| 12 |
dmp "github.com/sergi/go-diff/diffmatchpatch" |
| 13 |
"github.com/yudai/golcs" |
| 14 |
) |
| 15 |
|
| 16 |
// A Diff holds deltas generated by a Differ |
| 17 |
type Diff interface { |
| 18 |
// Deltas returns Deltas that describe differences between two JSON objects |
| 19 |
Deltas() []Delta |
| 20 |
// Modified returnes true if Diff has at least one Delta. |
| 21 |
Modified() bool |
| 22 |
} |
| 23 |
|
| 24 |
type diff struct { |
| 25 |
deltas []Delta |
| 26 |
} |
| 27 |
|
| 28 |
func (diff *diff) Deltas() []Delta { |
| 29 |
return diff.deltas |
| 30 |
} |
| 31 |
|
| 32 |
func (diff *diff) Modified() bool { |
| 33 |
return len(diff.deltas) > 0 |
| 34 |
} |
| 35 |
|
| 36 |
// A Differ conmapres JSON objects and apply patches |
| 37 |
type Differ struct { |
| 38 |
textDiffMinimumLength int |
| 39 |
} |
| 40 |
|
| 41 |
// New returns new Differ with default configuration |
| 42 |
func New() *Differ { |
| 43 |
return &Differ{ |
| 44 |
textDiffMinimumLength: 30, |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
// Compare compares two JSON strings as []bytes and return a Diff object. |
| 49 |
func (differ *Differ) Compare( |
| 50 |
left []byte, |
| 51 |
right []byte, |
| 52 |
) (Diff, error) { |
| 53 |
var leftMap, rightMap map[string]interface{} |
| 54 |
err := json.Unmarshal(left, &leftMap) |
| 55 |
if err != nil { |
| 56 |
return nil, err |
| 57 |
} |
| 58 |
|
| 59 |
err = json.Unmarshal(right, &rightMap) |
| 60 |
if err != nil { |
| 61 |
return nil, err |
| 62 |
} |
| 63 |
return differ.CompareObjects(leftMap, rightMap), nil |
| 64 |
} |
| 65 |
|
| 66 |
// CompareObjects compares two JSON object as map[string]interface{} |
| 67 |
// and return a Diff object. |
| 68 |
func (differ *Differ) CompareObjects( |
| 69 |
left map[string]interface{}, |
| 70 |
right map[string]interface{}, |
| 71 |
) Diff { |
| 72 |
deltas := differ.compareMaps(left, right) |
| 73 |
return &diff{deltas: deltas} |
| 74 |
} |
| 75 |
|
| 76 |
// CompareArrays compares two JSON arrays as []interface{} |
| 77 |
// and return a Diff object. |
| 78 |
func (differ *Differ) CompareArrays( |
| 79 |
left []interface{}, |
| 80 |
right []interface{}, |
| 81 |
) Diff { |
| 82 |
deltas := differ.compareArrays(left, right) |
| 83 |
return &diff{deltas: deltas} |
| 84 |
} |
| 85 |
|
| 86 |
func (differ *Differ) compareMaps( |
| 87 |
left map[string]interface{}, |
| 88 |
right map[string]interface{}, |
| 89 |
) (deltas []Delta) { |
| 90 |
deltas = make([]Delta, 0) |
| 91 |
|
| 92 |
names := sortedKeys(left) // stabilize delta order |
| 93 |
for _, name := range names { |
| 94 |
if rightValue, ok := right[name]; ok { |
| 95 |
same, delta := differ.compareValues(Name(name), left[name], rightValue) |
| 96 |
if !same { |
| 97 |
deltas = append(deltas, delta) |
| 98 |
} |
| 99 |
} else { |
| 100 |
deltas = append(deltas, NewDeleted(Name(name), left[name])) |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
names = sortedKeys(right) // stabilize delta order |
| 105 |
for _, name := range names { |
| 106 |
if _, ok := left[name]; !ok { |
| 107 |
deltas = append(deltas, NewAdded(Name(name), right[name])) |
| 108 |
} |
| 109 |
} |
| 110 |
|
| 111 |
return deltas |
| 112 |
} |
| 113 |
|
| 114 |
// ApplyPatch applies a Diff to an JSON object. This method is destructive. |
| 115 |
func (differ *Differ) ApplyPatch(json map[string]interface{}, patch Diff) { |
| 116 |
applyDeltas(patch.Deltas(), json) |
| 117 |
} |
| 118 |
|
| 119 |
type maybe struct { |
| 120 |
index int |
| 121 |
lcsIndex int |
| 122 |
item interface{} |
| 123 |
} |
| 124 |
|
| 125 |
func (differ *Differ) compareArrays( |
| 126 |
left []interface{}, |
| 127 |
right []interface{}, |
| 128 |
) (deltas []Delta) { |
| 129 |
deltas = make([]Delta, 0) |
| 130 |
// LCS index pairs |
| 131 |
lcsPairs := lcs.New(left, right).IndexPairs() |
| 132 |
|
| 133 |
// list up items not in LCS, they are maybe deleted |
| 134 |
maybeDeleted := list.New() // but maybe moved or modified |
| 135 |
lcsI := 0 |
| 136 |
for i, leftValue := range left { |
| 137 |
if lcsI < len(lcsPairs) && lcsPairs[lcsI].Left == i { |
| 138 |
lcsI++ |
| 139 |
} else { |
| 140 |
maybeDeleted.PushBack(maybe{index: i, lcsIndex: lcsI, item: leftValue}) |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
// list up items not in LCS, they are maybe Added |
| 145 |
maybeAdded := list.New() // but maybe moved or modified |
| 146 |
lcsI = 0 |
| 147 |
for i, rightValue := range right { |
| 148 |
if lcsI < len(lcsPairs) && lcsPairs[lcsI].Right == i { |
| 149 |
lcsI++ |
| 150 |
} else { |
| 151 |
maybeAdded.PushBack(maybe{index: i, lcsIndex: lcsI, item: rightValue}) |
| 152 |
} |
| 153 |
} |
| 154 |
|
| 155 |
// find moved items |
| 156 |
var delNext *list.Element // for prefetch to remove item in iteration |
| 157 |
for delCandidate := maybeDeleted.Front(); delCandidate != nil; delCandidate = delNext { |
| 158 |
delCan := delCandidate.Value.(maybe) |
| 159 |
delNext = delCandidate.Next() |
| 160 |
|
| 161 |
for addCandidate := maybeAdded.Front(); addCandidate != nil; addCandidate = addCandidate.Next() { |
| 162 |
addCan := addCandidate.Value.(maybe) |
| 163 |
if reflect.DeepEqual(delCan.item, addCan.item) { |
| 164 |
deltas = append(deltas, NewMoved(Index(delCan.index), Index(addCan.index), delCan.item, nil)) |
| 165 |
maybeAdded.Remove(addCandidate) |
| 166 |
maybeDeleted.Remove(delCandidate) |
| 167 |
break |
| 168 |
} |
| 169 |
} |
| 170 |
} |
| 171 |
|
| 172 |
// find modified or add+del |
| 173 |
prevIndexDel := 0 |
| 174 |
prevIndexAdd := 0 |
| 175 |
delElement := maybeDeleted.Front() |
| 176 |
addElement := maybeAdded.Front() |
| 177 |
for i := 0; i <= len(lcsPairs); i++ { // not "< len(lcsPairs)" |
| 178 |
var lcsPair lcs.IndexPair |
| 179 |
var delSize, addSize int |
| 180 |
if i < len(lcsPairs) { |
| 181 |
lcsPair = lcsPairs[i] |
| 182 |
delSize = lcsPair.Left - prevIndexDel - 1 |
| 183 |
addSize = lcsPair.Right - prevIndexAdd - 1 |
| 184 |
prevIndexDel = lcsPair.Left |
| 185 |
prevIndexAdd = lcsPair.Right |
| 186 |
} |
| 187 |
|
| 188 |
var delSlice []maybe |
| 189 |
if delSize > 0 { |
| 190 |
delSlice = make([]maybe, 0, delSize) |
| 191 |
} else { |
| 192 |
delSlice = make([]maybe, 0, maybeDeleted.Len()) |
| 193 |
} |
| 194 |
for ; delElement != nil; delElement = delElement.Next() { |
| 195 |
d := delElement.Value.(maybe) |
| 196 |
if d.lcsIndex != i { |
| 197 |
break |
| 198 |
} |
| 199 |
delSlice = append(delSlice, d) |
| 200 |
} |
| 201 |
|
| 202 |
var addSlice []maybe |
| 203 |
if addSize > 0 { |
| 204 |
addSlice = make([]maybe, 0, addSize) |
| 205 |
} else { |
| 206 |
addSlice = make([]maybe, 0, maybeAdded.Len()) |
| 207 |
} |
| 208 |
for ; addElement != nil; addElement = addElement.Next() { |
| 209 |
a := addElement.Value.(maybe) |
| 210 |
if a.lcsIndex != i { |
| 211 |
break |
| 212 |
} |
| 213 |
addSlice = append(addSlice, a) |
| 214 |
} |
| 215 |
|
| 216 |
if len(delSlice) > 0 && len(addSlice) > 0 { |
| 217 |
var bestDeltas []Delta |
| 218 |
bestDeltas, delSlice, addSlice = differ.maximizeSimilarities(delSlice, addSlice) |
| 219 |
for _, delta := range bestDeltas { |
| 220 |
deltas = append(deltas, delta) |
| 221 |
} |
| 222 |
} |
| 223 |
|
| 224 |
for _, del := range delSlice { |
| 225 |
deltas = append(deltas, NewDeleted(Index(del.index), del.item)) |
| 226 |
} |
| 227 |
for _, add := range addSlice { |
| 228 |
deltas = append(deltas, NewAdded(Index(add.index), add.item)) |
| 229 |
} |
| 230 |
} |
| 231 |
|
| 232 |
return deltas |
| 233 |
} |
| 234 |
|
| 235 |
func (differ *Differ) compareValues( |
| 236 |
position Position, |
| 237 |
left interface{}, |
| 238 |
right interface{}, |
| 239 |
) (same bool, delta Delta) { |
| 240 |
if reflect.TypeOf(left) != reflect.TypeOf(right) { |
| 241 |
return false, NewModified(position, left, right) |
| 242 |
} |
| 243 |
|
| 244 |
switch left.(type) { |
| 245 |
|
| 246 |
case map[string]interface{}: |
| 247 |
l := left.(map[string]interface{}) |
| 248 |
childDeltas := differ.compareMaps(l, right.(map[string]interface{})) |
| 249 |
if len(childDeltas) > 0 { |
| 250 |
return false, NewObject(position, childDeltas) |
| 251 |
} |
| 252 |
|
| 253 |
case []interface{}: |
| 254 |
l := left.([]interface{}) |
| 255 |
childDeltas := differ.compareArrays(l, right.([]interface{})) |
| 256 |
|
| 257 |
if len(childDeltas) > 0 { |
| 258 |
return false, NewArray(position, childDeltas) |
| 259 |
} |
| 260 |
|
| 261 |
default: |
| 262 |
if !reflect.DeepEqual(left, right) { |
| 263 |
|
| 264 |
if reflect.ValueOf(left).Kind() == reflect.String && |
| 265 |
reflect.ValueOf(right).Kind() == reflect.String && |
| 266 |
differ.textDiffMinimumLength <= len(left.(string)) { |
| 267 |
|
| 268 |
textDiff := dmp.New() |
| 269 |
patchs := textDiff.PatchMake(left.(string), right.(string)) |
| 270 |
return false, NewTextDiff(position, patchs, left, right) |
| 271 |
|
| 272 |
} else { |
| 273 |
return false, NewModified(position, left, right) |
| 274 |
} |
| 275 |
} |
| 276 |
} |
| 277 |
|
| 278 |
return true, nil |
| 279 |
} |
| 280 |
|
| 281 |
func applyDeltas(deltas []Delta, object interface{}) interface{} { |
| 282 |
preDeltas := make(preDeltas, 0) |
| 283 |
for _, delta := range deltas { |
| 284 |
switch delta.(type) { |
| 285 |
case PreDelta: |
| 286 |
preDeltas = append(preDeltas, delta.(PreDelta)) |
| 287 |
} |
| 288 |
} |
| 289 |
sort.Sort(preDeltas) |
| 290 |
for _, delta := range preDeltas { |
| 291 |
object = delta.PreApply(object) |
| 292 |
} |
| 293 |
|
| 294 |
postDeltas := make(postDeltas, 0, len(deltas)-len(preDeltas)) |
| 295 |
for _, delta := range deltas { |
| 296 |
switch delta.(type) { |
| 297 |
case PostDelta: |
| 298 |
postDeltas = append(postDeltas, delta.(PostDelta)) |
| 299 |
} |
| 300 |
} |
| 301 |
sort.Sort(postDeltas) |
| 302 |
|
| 303 |
for _, delta := range postDeltas { |
| 304 |
object = delta.PostApply(object) |
| 305 |
} |
| 306 |
|
| 307 |
return object |
| 308 |
} |
| 309 |
|
| 310 |
func (differ *Differ) maximizeSimilarities(left []maybe, right []maybe) (resultDeltas []Delta, freeLeft, freeRight []maybe) { |
| 311 |
deltaTable := make([][]Delta, len(left)) |
| 312 |
for i := 0; i < len(left); i++ { |
| 313 |
deltaTable[i] = make([]Delta, len(right)) |
| 314 |
} |
| 315 |
for i, leftValue := range left { |
| 316 |
for j, rightValue := range right { |
| 317 |
_, delta := differ.compareValues(Index(rightValue.index), leftValue.item, rightValue.item) |
| 318 |
deltaTable[i][j] = delta |
| 319 |
} |
| 320 |
} |
| 321 |
|
| 322 |
sizeX := len(left) + 1 // margins for both sides |
| 323 |
sizeY := len(right) + 1 |
| 324 |
|
| 325 |
// fill out with similarities |
| 326 |
dpTable := make([][]float64, sizeX) |
| 327 |
for i := 0; i < sizeX; i++ { |
| 328 |
dpTable[i] = make([]float64, sizeY) |
| 329 |
} |
| 330 |
for x := sizeX - 2; x >= 0; x-- { |
| 331 |
for y := sizeY - 2; y >= 0; y-- { |
| 332 |
prevX := dpTable[x+1][y] |
| 333 |
prevY := dpTable[x][y+1] |
| 334 |
score := deltaTable[x][y].Similarity() + dpTable[x+1][y+1] |
| 335 |
|
| 336 |
dpTable[x][y] = max(prevX, prevY, score) |
| 337 |
} |
| 338 |
} |
| 339 |
|
| 340 |
minLength := len(left) |
| 341 |
if minLength > len(right) { |
| 342 |
minLength = len(right) |
| 343 |
} |
| 344 |
maxInvalidLength := minLength - 1 |
| 345 |
|
| 346 |
freeLeft = make([]maybe, 0, len(left)-minLength) |
| 347 |
freeRight = make([]maybe, 0, len(right)-minLength) |
| 348 |
|
| 349 |
resultDeltas = make([]Delta, 0, minLength) |
| 350 |
var x, y int |
| 351 |
for x, y = 0, 0; x <= sizeX-2 && y <= sizeY-2; { |
| 352 |
current := dpTable[x][y] |
| 353 |
nextX := dpTable[x+1][y] |
| 354 |
nextY := dpTable[x][y+1] |
| 355 |
|
| 356 |
xValidLength := len(left) - maxInvalidLength + y |
| 357 |
yValidLength := len(right) - maxInvalidLength + x |
| 358 |
|
| 359 |
if x+1 < xValidLength && current == nextX { |
| 360 |
freeLeft = append(freeLeft, left[x]) |
| 361 |
x++ |
| 362 |
} else if y+1 < yValidLength && current == nextY { |
| 363 |
freeRight = append(freeRight, right[y]) |
| 364 |
y++ |
| 365 |
} else { |
| 366 |
resultDeltas = append(resultDeltas, deltaTable[x][y]) |
| 367 |
x++ |
| 368 |
y++ |
| 369 |
} |
| 370 |
} |
| 371 |
for ; x < sizeX-1; x++ { |
| 372 |
freeLeft = append(freeLeft, left[x-1]) |
| 373 |
} |
| 374 |
for ; y < sizeY-1; y++ { |
| 375 |
freeRight = append(freeRight, right[y-1]) |
| 376 |
} |
| 377 |
|
| 378 |
return resultDeltas, freeLeft, freeRight |
| 379 |
} |
| 380 |
|
| 381 |
func deltasSimilarity(deltas []Delta) (similarity float64) { |
| 382 |
for _, delta := range deltas { |
| 383 |
similarity += delta.Similarity() |
| 384 |
} |
| 385 |
similarity = similarity / float64(len(deltas)) |
| 386 |
return |
| 387 |
} |
| 388 |
|
| 389 |
func stringSimilarity(left, right string) (similarity float64) { |
| 390 |
matchingLength := float64( |
| 391 |
lcs.New( |
| 392 |
stringToInterfaceSlice(left), |
| 393 |
stringToInterfaceSlice(right), |
| 394 |
).Length(), |
| 395 |
) |
| 396 |
similarity = |
| 397 |
(matchingLength / float64(len(left))) * (matchingLength / float64(len(right))) |
| 398 |
return |
| 399 |
} |
| 400 |
|
| 401 |
func stringToInterfaceSlice(str string) []interface{} { |
| 402 |
s := make([]interface{}, len(str)) |
| 403 |
for i, v := range str { |
| 404 |
s[i] = v |
| 405 |
} |
| 406 |
return s |
| 407 |
} |
| 408 |
|
| 409 |
func sortedKeys(m map[string]interface{}) (keys []string) { |
| 410 |
keys = make([]string, 0, len(m)) |
| 411 |
for key, _ := range m { |
| 412 |
keys = append(keys, key) |
| 413 |
} |
| 414 |
sort.Strings(keys) |
| 415 |
return |
| 416 |
} |
| 417 |
|
| 418 |
func max(first float64, rest ...float64) (max float64) { |
| 419 |
max = first |
| 420 |
for _, value := range rest { |
| 421 |
if max < value { |
| 422 |
max = value |
| 423 |
} |
| 424 |
} |
| 425 |
return max |
| 426 |
} |