deltas.go 10.6 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 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
package gojsondiff

import (
	"errors"
	dmp "github.com/sergi/go-diff/diffmatchpatch"
	"reflect"
	"strconv"
)

// A Delta represents an atomic difference between two JSON objects.
type Delta interface {
	// Similarity calculates the similarity of the Delta values.
	// The return value is normalized from 0 to 1,
	// 0 is completely different and 1 is they are same
	Similarity() (similarity float64)
}

// To cache the calculated similarity,
// concrete Deltas can use similariter and similarityCache
type similariter interface {
	similarity() (similarity float64)
}

type similarityCache struct {
	similariter
	value float64
}

func newSimilarityCache(sim similariter) similarityCache {
	cache := similarityCache{similariter: sim, value: -1}
	return cache
}

func (cache similarityCache) Similarity() (similarity float64) {
	if cache.value < 0 {
		cache.value = cache.similariter.similarity()
	}
	return cache.value
}

// A Position represents the position of a Delta in an object or an array.
type Position interface {
	// String returns the position as a string
	String() (name string)

	// CompareTo returns a true if the Position is smaller than another Position.
	// This function is used to sort Positions by the sort package.
	CompareTo(another Position) bool
}

// A Name is a Postition with a string, which means the delta is in an object.
type Name string

func (n Name) String() (name string) {
	return string(n)
}

func (n Name) CompareTo(another Position) bool {
	return n < another.(Name)
}

// A Index is a Position with an int value, which means the Delta is in an Array.
type Index int

func (i Index) String() (name string) {
	return strconv.Itoa(int(i))
}

func (i Index) CompareTo(another Position) bool {
	return i < another.(Index)
}

// A PreDelta is a Delta that has a position of the left side JSON object.
// Deltas implements this interface should be applies before PostDeltas.
type PreDelta interface {
	// PrePosition returns the Position.
	PrePosition() Position

	// PreApply applies the delta to object.
	PreApply(object interface{}) interface{}
}

type preDelta struct{ Position }

func (i preDelta) PrePosition() Position {
	return Position(i.Position)
}

type preDeltas []PreDelta

// for sorting
func (s preDeltas) Len() int {
	return len(s)
}

// for sorting
func (s preDeltas) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

// for sorting
func (s preDeltas) Less(i, j int) bool {
	return !s[i].PrePosition().CompareTo(s[j].PrePosition())
}

// A PreDelta is a Delta that has a position of the right side JSON object.
// Deltas implements this interface should be applies after PreDeltas.
type PostDelta interface {
	// PostPosition returns the Position.
	PostPosition() Position

	// PostApply applies the delta to object.
	PostApply(object interface{}) interface{}
}

type postDelta struct{ Position }

func (i postDelta) PostPosition() Position {
	return Position(i.Position)
}

type postDeltas []PostDelta

// for sorting
func (s postDeltas) Len() int {
	return len(s)
}

// for sorting
func (s postDeltas) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

// for sorting
func (s postDeltas) Less(i, j int) bool {
	return s[i].PostPosition().CompareTo(s[j].PostPosition())
}

// An Object is a Delta that represents an object of JSON
type Object struct {
	postDelta
	similarityCache

	// Deltas holds internal Deltas
	Deltas []Delta
}

// NewObject returns an Object
func NewObject(position Position, deltas []Delta) *Object {
	d := Object{postDelta: postDelta{position}, Deltas: deltas}
	d.similarityCache = newSimilarityCache(&d)
	return &d
}

func (d *Object) PostApply(object interface{}) interface{} {
	switch object.(type) {
	case map[string]interface{}:
		o := object.(map[string]interface{})
		n := string(d.PostPosition().(Name))
		o[n] = applyDeltas(d.Deltas, o[n])
	case []interface{}:
		o := object.([]interface{})
		n := int(d.PostPosition().(Index))
		o[n] = applyDeltas(d.Deltas, o[n])
	}
	return object
}

func (d *Object) similarity() (similarity float64) {
	similarity = deltasSimilarity(d.Deltas)
	return
}

// An Array is a Delta that represents an array of JSON
type Array struct {
	postDelta
	similarityCache

	// Deltas holds internal Deltas
	Deltas []Delta
}

// NewArray returns an Array
func NewArray(position Position, deltas []Delta) *Array {
	d := Array{postDelta: postDelta{position}, Deltas: deltas}
	d.similarityCache = newSimilarityCache(&d)
	return &d
}

func (d *Array) PostApply(object interface{}) interface{} {
	switch object.(type) {
	case map[string]interface{}:
		o := object.(map[string]interface{})
		n := string(d.PostPosition().(Name))
		o[n] = applyDeltas(d.Deltas, o[n])
	case []interface{}:
		o := object.([]interface{})
		n := int(d.PostPosition().(Index))
		o[n] = applyDeltas(d.Deltas, o[n])
	}
	return object
}

func (d *Array) similarity() (similarity float64) {
	similarity = deltasSimilarity(d.Deltas)
	return
}

// An Added represents a new added field of an object or an array
type Added struct {
	postDelta
	similarityCache

	// Values holds the added value
	Value interface{}
}

// NewAdded returns a new Added
func NewAdded(position Position, value interface{}) *Added {
	d := Added{postDelta: postDelta{position}, Value: value}
	return &d
}

func (d *Added) PostApply(object interface{}) interface{} {
	switch object.(type) {
	case map[string]interface{}:
		object.(map[string]interface{})[string(d.PostPosition().(Name))] = d.Value
	case []interface{}:
		i := int(d.PostPosition().(Index))
		o := object.([]interface{})
		if i < len(o) {
			o = append(o, 0) //dummy
			copy(o[i+1:], o[i:])
			o[i] = d.Value
			object = o
		} else {
			object = append(o, d.Value)
		}
	}

	return object
}

func (d *Added) similarity() (similarity float64) {
	return 0
}

// A Modified represents a field whose value is changed.
type Modified struct {
	postDelta
	similarityCache

	// The value before modification
	OldValue interface{}

	// The value after modification
	NewValue interface{}
}

// NewModified returns a Modified
func NewModified(position Position, oldValue, newValue interface{}) *Modified {
	d := Modified{
		postDelta: postDelta{position},
		OldValue:  oldValue,
		NewValue:  newValue,
	}
	d.similarityCache = newSimilarityCache(&d)
	return &d

}

func (d *Modified) PostApply(object interface{}) interface{} {
	switch object.(type) {
	case map[string]interface{}:
		// TODO check old value
		object.(map[string]interface{})[string(d.PostPosition().(Name))] = d.NewValue
	case []interface{}:
		object.([]interface{})[int(d.PostPosition().(Index))] = d.NewValue
	}
	return object
}

func (d *Modified) similarity() (similarity float64) {
	similarity += 0.3 // at least, they are at the same position
	if reflect.TypeOf(d.OldValue) == reflect.TypeOf(d.NewValue) {
		similarity += 0.3 // types are same

		switch d.OldValue.(type) {
		case string:
			similarity += 0.4 * stringSimilarity(d.OldValue.(string), d.NewValue.(string))
		case float64:
			ratio := d.OldValue.(float64) / d.NewValue.(float64)
			if ratio > 1 {
				ratio = 1 / ratio
			}
			similarity += 0.4 * ratio
		}
	}
	return
}

// A TextDiff represents a Modified with TextDiff between the old and the new values.
type TextDiff struct {
	Modified

	// Diff string
	Diff []dmp.Patch
}

// NewTextDiff returns
func NewTextDiff(position Position, diff []dmp.Patch, oldValue, newValue interface{}) *TextDiff {
	d := TextDiff{
		Modified: *NewModified(position, oldValue, newValue),
		Diff:     diff,
	}
	return &d
}

func (d *TextDiff) PostApply(object interface{}) interface{} {
	switch object.(type) {
	case map[string]interface{}:
		o := object.(map[string]interface{})
		i := string(d.PostPosition().(Name))
		// TODO error
		d.OldValue = o[i]
		// TODO error
		d.patch()
		o[i] = d.NewValue
	case []interface{}:
		o := object.([]interface{})
		i := d.PostPosition().(Index)
		d.OldValue = o[i]
		// TODO error
		d.patch()
		o[i] = d.NewValue
	}
	return object
}

func (d *TextDiff) patch() error {
	if d.OldValue == nil {
		return errors.New("Old Value is not set")
	}
	patcher := dmp.New()
	patched, successes := patcher.PatchApply(d.Diff, d.OldValue.(string))
	for _, success := range successes {
		if !success {
			return errors.New("Failed to apply a patch")
		}
	}
	d.NewValue = patched
	return nil
}

func (d *TextDiff) DiffString() string {
	dmp := dmp.New()
	return dmp.PatchToText(d.Diff)
}

// A Delted represents deleted field or index of an Object or an Array.
type Deleted struct {
	preDelta

	// The value deleted
	Value interface{}
}

// NewDeleted returns a Deleted
func NewDeleted(position Position, value interface{}) *Deleted {
	d := Deleted{
		preDelta: preDelta{position},
		Value:    value,
	}
	return &d

}

func (d *Deleted) PreApply(object interface{}) interface{} {
	switch object.(type) {
	case map[string]interface{}:
		// TODO check old value
		delete(object.(map[string]interface{}), string(d.PrePosition().(Name)))
	case []interface{}:
		i := int(d.PrePosition().(Index))
		o := object.([]interface{})
		object = append(o[:i], o[i+1:]...)
	}
	return object
}

func (d Deleted) Similarity() (similarity float64) {
	return 0
}

// A Moved represents field that is moved, which means the index or name is
// changed. Note that, in this library, assigning a Moved and a Modified to
// a single position is not allowed. For the compatibility with jsondiffpatch,
// the Moved in this library can hold the old and new value in it.
type Moved struct {
	preDelta
	postDelta
	similarityCache
	// The value before moving
	Value interface{}
	// The delta applied after moving (for compatibility)
	Delta interface{}
}

func NewMoved(oldPosition Position, newPosition Position, value interface{}, delta Delta) *Moved {
	d := Moved{
		preDelta:  preDelta{oldPosition},
		postDelta: postDelta{newPosition},
		Value:     value,
		Delta:     delta,
	}
	d.similarityCache = newSimilarityCache(&d)
	return &d
}

func (d *Moved) PreApply(object interface{}) interface{} {
	switch object.(type) {
	case map[string]interface{}:
		//not supported
	case []interface{}:
		i := int(d.PrePosition().(Index))
		o := object.([]interface{})
		d.Value = o[i]
		object = append(o[:i], o[i+1:]...)
	}
	return object
}

func (d *Moved) PostApply(object interface{}) interface{} {
	switch object.(type) {
	case map[string]interface{}:
		//not supported
	case []interface{}:
		i := int(d.PostPosition().(Index))
		o := object.([]interface{})
		o = append(o, 0) //dummy
		copy(o[i+1:], o[i:])
		o[i] = d.Value
		object = o
	}

	if d.Delta != nil {
		d.Delta.(PostDelta).PostApply(object)
	}

	return object
}

func (d *Moved) similarity() (similarity float64) {
	similarity = 0.6 // as type and contens are same
	ratio := float64(d.PrePosition().(Index)) / float64(d.PostPosition().(Index))
	if ratio > 1 {
		ratio = 1 / ratio
	}
	similarity += 0.4 * ratio
	return
}