forked from nsf/jsondiff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jsondiff.go
441 lines (417 loc) · 9.88 KB
/
jsondiff.go
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
package jsondiff
import (
"bytes"
"encoding/json"
"reflect"
"regexp"
"sort"
"strconv"
)
type Difference int
const (
FullMatch Difference = iota
SupersetMatch
NoMatch
FirstArgIsInvalidJson
SecondArgIsInvalidJson
BothArgsAreInvalidJson
)
func (d Difference) String() string {
switch d {
case FullMatch:
return "FullMatch"
case SupersetMatch:
return "SupersetMatch"
case NoMatch:
return "NoMatch"
case FirstArgIsInvalidJson:
return "FirstArgIsInvalidJson"
case SecondArgIsInvalidJson:
return "SecondArgIsInvalidJson"
case BothArgsAreInvalidJson:
return "BothArgsAreInvalidJson"
}
return "Invalid"
}
type Tag struct {
Begin string
End string
}
type Options struct {
Normal Tag
Added Tag
Removed Tag
Changed Tag
Prefix string
Indent string
PrintTypes bool
ChangedSeparator string
}
// Provides a set of options in JSON format that are fully parseable.
func DefaultJSONOptions() Options {
return Options{
Added: Tag{Begin: "\"prop-added\":{", End: "}"},
Removed: Tag{Begin: "\"prop-removed\":{", End: "}"},
Changed: Tag{Begin: "{\"changed\":[", End: "]}"},
ChangedSeparator: ", ",
Indent: " ",
}
}
// Provides a set of options that are well suited for console output. Options
// use ANSI foreground color escape sequences to highlight changes.
func DefaultConsoleOptions() Options {
return Options{
Added: Tag{Begin: "\033[0;32m", End: "\033[0m"},
Removed: Tag{Begin: "\033[0;31m", End: "\033[0m"},
Changed: Tag{Begin: "\033[0;33m", End: "\033[0m"},
ChangedSeparator: " => ",
Indent: " ",
}
}
// Provides a set of options that are well suited for HTML output. Works best
// inside <pre> tag.
func DefaultHTMLOptions() Options {
return Options{
Added: Tag{Begin: `<span style="background-color: #8bff7f">`, End: `</span>`},
Removed: Tag{Begin: `<span style="background-color: #fd7f7f">`, End: `</span>`},
Changed: Tag{Begin: `<span style="background-color: #fcff7f">`, End: `</span>`},
ChangedSeparator: " => ",
Indent: " ",
}
}
type context struct {
opts *Options
buf bytes.Buffer
level int
lastTag *Tag
diff Difference
}
func (ctx *context) newline(s string) {
ctx.buf.WriteString(s)
if ctx.lastTag != nil {
ctx.buf.WriteString(ctx.lastTag.End)
}
ctx.buf.WriteString("\n")
ctx.buf.WriteString(ctx.opts.Prefix)
for i := 0; i < ctx.level; i++ {
ctx.buf.WriteString(ctx.opts.Indent)
}
if ctx.lastTag != nil {
ctx.buf.WriteString(ctx.lastTag.Begin)
}
}
func (ctx *context) key(k string) {
ctx.buf.WriteString(strconv.Quote(k))
ctx.buf.WriteString(": ")
}
func (ctx *context) writeValue(v interface{}, full bool) {
switch vv := v.(type) {
case bool:
ctx.buf.WriteString(strconv.FormatBool(vv))
case json.Number:
ctx.buf.WriteString(string(vv))
case string:
ctx.buf.WriteString(strconv.Quote(vv))
case []interface{}:
if full {
if len(vv) == 0 {
ctx.buf.WriteString("[")
} else {
ctx.level++
ctx.newline("[")
}
for i, v := range vv {
ctx.writeValue(v, true)
if i != len(vv)-1 {
ctx.newline(",")
} else {
ctx.level--
ctx.newline("")
}
}
ctx.buf.WriteString("]")
} else {
ctx.buf.WriteString("[]")
}
case map[string]interface{}:
if full {
if len(vv) == 0 {
ctx.buf.WriteString("{")
} else {
ctx.level++
ctx.newline("{")
}
i := 0
for k, v := range vv {
ctx.key(k)
ctx.writeValue(v, true)
if i != len(vv)-1 {
ctx.newline(",")
} else {
ctx.level--
ctx.newline("")
}
i++
}
ctx.buf.WriteString("}")
} else {
ctx.buf.WriteString("{}")
}
default:
ctx.buf.WriteString("null")
}
ctx.writeTypeMaybe(v)
}
func (ctx *context) writeTypeMaybe(v interface{}) {
if ctx.opts.PrintTypes {
ctx.buf.WriteString(" ")
ctx.writeType(v)
}
}
func (ctx *context) writeType(v interface{}) {
switch v.(type) {
case bool:
ctx.buf.WriteString("(boolean)")
case json.Number:
ctx.buf.WriteString("(number)")
case string:
ctx.buf.WriteString("(string)")
case []interface{}:
ctx.buf.WriteString("(array)")
case map[string]interface{}:
ctx.buf.WriteString("(object)")
default:
ctx.buf.WriteString("(null)")
}
}
func (ctx *context) writeMismatch(a, b interface{}) {
ctx.writeValue(a, false)
ctx.buf.WriteString(ctx.opts.ChangedSeparator)
ctx.writeValue(b, false)
}
func (ctx *context) tag(tag *Tag) {
if ctx.lastTag == tag {
return
} else if ctx.lastTag != nil {
ctx.buf.WriteString(ctx.lastTag.End)
}
ctx.buf.WriteString(tag.Begin)
ctx.lastTag = tag
}
func (ctx *context) result(d Difference) {
if d == NoMatch {
ctx.diff = NoMatch
} else if d == SupersetMatch && ctx.diff != NoMatch {
ctx.diff = SupersetMatch
} else if ctx.diff != NoMatch && ctx.diff != SupersetMatch {
ctx.diff = FullMatch
}
}
func (ctx *context) printMismatch(a, b interface{}) {
ctx.tag(&ctx.opts.Changed)
ctx.writeMismatch(a, b)
}
func (ctx *context) printDiff(a, b interface{}) {
if a == nil || b == nil {
if a == nil && b == nil {
ctx.tag(&ctx.opts.Normal)
ctx.writeValue(a, false)
ctx.result(FullMatch)
} else {
ctx.printMismatch(a, b)
ctx.result(NoMatch)
}
return
}
ka := reflect.TypeOf(a).Kind()
kb := reflect.TypeOf(b).Kind()
if ka != kb {
ctx.printMismatch(a, b)
ctx.result(NoMatch)
return
}
switch ka {
case reflect.Bool:
if a.(bool) != b.(bool) {
ctx.printMismatch(a, b)
ctx.result(NoMatch)
return
}
case reflect.String:
switch aa := a.(type) {
case json.Number:
bb, ok := b.(json.Number)
if !ok || aa != bb {
ctx.printMismatch(a, b)
ctx.result(NoMatch)
return
}
case string:
bb, ok := b.(string)
// if !ok || aa != bb {
// matched, _ := regexp.MatchString(aa, bb)
matched, _ := regexp.MatchString(bb, aa)
if !ok || !matched {
ctx.printMismatch(a, b)
ctx.result(NoMatch)
return
}
}
case reflect.Slice:
sa, sb := a.([]interface{}), b.([]interface{})
salen, sblen := len(sa), len(sb)
max := salen
if sblen > max {
max = sblen
}
ctx.tag(&ctx.opts.Normal)
if max == 0 {
ctx.buf.WriteString("[")
} else {
ctx.level++
ctx.newline("[")
}
for i := 0; i < max; i++ {
if i < salen && i < sblen {
ctx.printDiff(sa[i], sb[i])
} else if i < salen {
ctx.tag(&ctx.opts.Removed)
ctx.writeValue(sa[i], true)
ctx.result(SupersetMatch)
} else if i < sblen {
ctx.tag(&ctx.opts.Added)
ctx.writeValue(sb[i], true)
ctx.result(NoMatch)
}
ctx.tag(&ctx.opts.Normal)
if i != max-1 {
ctx.newline(",")
} else {
ctx.level--
ctx.newline("")
}
}
ctx.buf.WriteString("]")
ctx.writeTypeMaybe(a)
return
case reflect.Map:
ma, mb := a.(map[string]interface{}), b.(map[string]interface{})
keysMap := make(map[string]bool)
for k := range ma {
keysMap[k] = true
}
for k := range mb {
keysMap[k] = true
}
keys := make([]string, 0, len(keysMap))
for k := range keysMap {
keys = append(keys, k)
}
sort.Strings(keys)
ctx.tag(&ctx.opts.Normal)
if len(keys) == 0 {
ctx.buf.WriteString("{")
} else {
ctx.level++
ctx.newline("{")
}
for i, k := range keys {
va, aok := ma[k]
vb, bok := mb[k]
if aok && bok {
ctx.key(k)
ctx.printDiff(va, vb)
} else if aok {
ctx.tag(&ctx.opts.Removed)
ctx.key(k)
ctx.writeValue(va, true)
ctx.result(SupersetMatch)
} else if bok {
// check if the b key partially macthes any other a key
var submatch = false
for ik, _ := range ma {
if reflect.TypeOf(k).Kind() != reflect.String { // ignore non string keys
continue
}
// if matched, _ := regexp.MatchString(k, ik); matched {
if matched, _ := regexp.MatchString(ik, k); matched {
submatch = true
ctx.key(ik)
break // no need to check any other keys
}
}
if submatch {
ctx.writeValue(vb, true)
ctx.result(SupersetMatch)
} else {
ctx.tag(&ctx.opts.Added)
ctx.key(k)
ctx.writeValue(vb, true)
ctx.result(NoMatch)
}
}
ctx.tag(&ctx.opts.Normal)
if i != len(keys)-1 {
ctx.newline(",")
} else {
ctx.level--
ctx.newline("")
}
}
ctx.buf.WriteString("}")
ctx.writeTypeMaybe(a)
return
}
ctx.tag(&ctx.opts.Normal)
ctx.writeValue(a, true)
ctx.result(FullMatch)
}
// Compares two JSON documents using given options. Returns difference type and
// a string describing differences.
//
// FullMatch means provided arguments are deeply equal.
//
// SupersetMatch means first argument is a superset of a second argument. In
// this context being a superset means that for each object or array in the
// hierarchy which don't match exactly, it must be a superset of another one.
// For example:
//
// {"a": 123, "b": 456, "c": [7, 8, 9]}
//
// Is a superset of:
//
// {"a": 123, "c": [7, 8]}
//
// NoMatch means there is no match.
//
// The rest of the difference types mean that one of or both JSON documents are
// invalid JSON.
//
// Returned string uses a format similar to pretty printed JSON to show the
// human-readable difference between provided JSON documents. It is important
// to understand that returned format is not a valid JSON and is not meant
// to be machine readable.
func Compare(a, b []byte, opts *Options) (Difference, string) {
var av, bv interface{}
da := json.NewDecoder(bytes.NewReader(a))
da.UseNumber()
db := json.NewDecoder(bytes.NewReader(b))
db.UseNumber()
errA := da.Decode(&av)
errB := db.Decode(&bv)
if errA != nil && errB != nil {
return BothArgsAreInvalidJson, "both arguments are invalid json"
}
if errA != nil {
return FirstArgIsInvalidJson, "first argument is invalid json"
}
if errB != nil {
return SecondArgIsInvalidJson, "second argument is invalid json"
}
ctx := context{opts: opts}
ctx.printDiff(av, bv)
if ctx.lastTag != nil {
ctx.buf.WriteString(ctx.lastTag.End)
}
return ctx.diff, ctx.buf.String()
}