-
Notifications
You must be signed in to change notification settings - Fork 53
/
main.go
600 lines (578 loc) · 13 KB
/
main.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
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
package main
import (
"bufio"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
jd "github.com/josephburnett/jd/lib"
v2 "github.com/josephburnett/jd/v2"
"github.com/josephburnett/jd/web/serve"
)
const version = "HEAD"
var (
color = flag.Bool("color", false, "Print color diff")
format = flag.String("f", "", "Diff format (jd, patch, merge)")
gitDiffDriver = flag.Bool("git-diff-driver", false, "Use jd as a git diff driver.")
mset = flag.Bool("mset", false, "Arrays as multisets")
output = flag.String("o", "", "Output file")
patch = flag.Bool("p", false, "Patch mode")
port = flag.Int("port", 0, "Serve web UI on port")
precision = flag.Float64("precision", 0, "Maximum absolute difference for numbers to be equal")
set = flag.Bool("set", false, "Arrays as sets")
setkeys = flag.String("setkeys", "", "Keys to identify set objects")
translate = flag.String("t", "", "Translate mode")
ver = flag.Bool("version", false, "Print version and exit")
libv2 = flag.Bool("v2", false, "Use the jd v2 library")
yaml = flag.Bool("yaml", false, "Read and write YAML")
)
func main() {
flag.Parse()
if *ver {
fmt.Printf("jd version %v\n", version)
return
}
if *port != 0 {
if len(flag.Args()) > 0 {
errorAndExit("The web UI (-port) does not support arguments")
}
err := serveWeb(strconv.Itoa(*port))
if err != nil {
errorAndExit(err.Error())
}
return
}
var (
metadata []jd.Metadata
options []v2.Option
err error
)
if *libv2 {
options, err = parseMetadataV2()
} else {
metadata, err = parseMetadata()
}
if err != nil {
errorAndExit(err.Error())
}
if *gitDiffDriver {
if *libv2 {
errorAndExit("--git-diff-driver cannot be used with --v2 yet")
}
err := printGitDiffDriver(metadata)
if err != nil {
errorAndExit(err.Error())
}
os.Exit(0)
return
}
mode := diffMode
if *patch {
mode = patchMode
}
if *translate != "" {
mode = translateMode
}
if *patch && *translate != "" {
errorAndExit("Patch and translate modes cannot be used together.")
}
var a, b string
switch mode {
case diffMode, patchMode:
switch len(flag.Args()) {
case 1:
a = readFile(flag.Arg(0))
b = readStdin()
case 2:
a = readFile(flag.Arg(0))
b = readFile(flag.Arg(1))
default:
printUsageAndExit()
}
case translateMode:
switch len(flag.Args()) {
case 0:
a = readStdin()
case 1:
a = readFile(flag.Arg(0))
default:
printUsageAndExit()
}
}
switch mode {
case diffMode:
if *libv2 {
printDiffV2(a, b, options)
} else {
printDiff(a, b, metadata)
}
case patchMode:
if *libv2 {
printPatchV2(a, b, options)
} else {
printPatch(a, b, metadata)
}
case translateMode:
printTranslation(a)
}
}
type mode string
const (
diffMode mode = "diff"
patchMode mode = "patch"
translateMode mode = "trans"
)
func serveWeb(port string) error {
if serve.Handle == nil {
return fmt.Errorf("the web UI wasn't include in this build: use `make build` to include it")
}
http.HandleFunc("/", serve.Handle)
log.Printf("Listening on http://localhost:%v...", port)
return http.ListenAndServe(":"+port, nil)
}
func parseMetadata() ([]jd.Metadata, error) {
if *precision != 0.0 && (*set || *mset) {
return nil, fmt.Errorf("-precision cannot be used with -set or -mset because they use hashcodes")
}
metadata := make([]jd.Metadata, 0)
if *set {
metadata = append(metadata, jd.SET)
}
if *mset {
metadata = append(metadata, jd.MULTISET)
}
if *setkeys != "" {
keys := make([]string, 0)
ks := strings.Split(*setkeys, ",")
for _, k := range ks {
trimmed := strings.TrimSpace(k)
if trimmed == "" {
return nil, fmt.Errorf("invalid set key: %v", k)
}
keys = append(keys, trimmed)
}
metadata = append(metadata, jd.Setkeys(keys...))
}
if *format == "merge" {
metadata = append(metadata, jd.MERGE)
}
metadata = append(metadata, jd.SetPrecision(*precision))
return metadata, nil
}
func parseMetadataV2() ([]v2.Option, error) {
if *precision != 0.0 && (*set || *mset) {
return nil, fmt.Errorf("-precision cannot be used with -set or -mset because they use hashcodes")
}
options := make([]v2.Option, 0)
if *set {
options = append(options, v2.SET)
}
if *mset {
options = append(options, v2.MULTISET)
}
if *setkeys != "" {
keys := make([]string, 0)
ks := strings.Split(*setkeys, ",")
for _, k := range ks {
trimmed := strings.TrimSpace(k)
if trimmed == "" {
return nil, fmt.Errorf("invalid set key: %v", k)
}
keys = append(keys, trimmed)
}
options = append(options, v2.SetKeys(keys...))
}
if *format == "merge" {
options = append(options, v2.MERGE)
}
options = append(options, v2.Precision(*precision))
return options, nil
}
func printUsageAndExit() {
for _, line := range []string{
``,
`Usage: jd [OPTION]... FILE1 [FILE2]`,
`Diff and patch JSON files.`,
``,
`Prints the diff of FILE1 and FILE2 to STDOUT.`,
`When FILE2 is omitted the second input is read from STDIN.`,
`When patching (-p) FILE1 is a diff.`,
``,
`Options:`,
` -color Print color diff.`,
` -p Apply patch FILE1 to FILE2 or STDIN.`,
` -o=FILE3 Write to FILE3 instead of STDOUT.`,
` -set Treat arrays as sets.`,
` -mset Treat arrays as multisets (bags).`,
` -setkeys Keys to identify set objects`,
` -yaml Read and write YAML instead of JSON.`,
` -port=N Serve web UI on port N`,
` -precision=N Maximum absolute difference for numbers to be equal.`,
` Example: -precision=0.00001`,
` -f=FORMAT Read and write diff in FORMAT "jd" (default), "patch" (RFC 6902) or`,
` "merge" (RFC 7386)`,
` -t=FORMATS Translate FILE1 between FORMATS. Supported formats are "jd",`,
` "patch" (RFC 6902), "merge" (RFC 7386), "json" and "yaml".`,
` FORMATS are provided as a pair separated by "2". E.g.`,
` "yaml2json" or "jd2patch".`,
` -v2 Use the JD v2 library and format.`,
``,
`Examples:`,
` jd a.json b.json`,
` cat b.json | jd a.json`,
` jd -o patch a.json b.json; jd patch a.json`,
` jd -set a.json b.json`,
` jd -f patch a.json b.json`,
` jd -f merge a.json b.json`,
``,
`Version: ` + version,
``,
} {
fmt.Println(line)
}
os.Exit(2)
}
func printDiff(a, b string, metadata []jd.Metadata) {
str, haveDiff, err := diff(a, b, metadata)
if err != nil {
errorAndExit(err.Error())
}
if *output == "" {
fmt.Print(str)
} else {
ioutil.WriteFile(*output, []byte(str), 0644)
}
if haveDiff {
os.Exit(1)
}
os.Exit(0)
}
func printDiffV2(a, b string, options []v2.Option) {
str, haveDiff, err := diffV2(a, b, options)
if err != nil {
errorAndExit(err.Error())
}
if *output == "" {
fmt.Print(str)
} else {
ioutil.WriteFile(*output, []byte(str), 0644)
}
if haveDiff {
os.Exit(1)
}
os.Exit(0)
}
func printGitDiffDriver(metadata []jd.Metadata) error {
if len(flag.Args()) != 7 {
return fmt.Errorf("Git diff driver expects exactly 7 arguments.")
}
a := readFile(flag.Arg(1))
b := readFile(flag.Arg(4))
str, _, err := diff(a, b, metadata)
if err != nil {
return err
}
fmt.Print(str)
os.Exit(0)
return nil
}
func diff(a, b string, metadata []jd.Metadata) (string, bool, error) {
var aNode, bNode jd.JsonNode
var err error
if *yaml {
aNode, err = jd.ReadYamlString(a)
} else {
aNode, err = jd.ReadJsonString(a)
}
if err != nil {
return "", false, err
}
if *yaml {
bNode, err = jd.ReadYamlString(b)
} else {
bNode, err = jd.ReadJsonString(b)
}
if err != nil {
return "", false, err
}
diff := aNode.Diff(bNode, metadata...)
var renderOptions []jd.RenderOption
if *color {
renderOptions = append(renderOptions, jd.COLOR)
}
var (
str string
haveDiff bool
)
switch *format {
case "", "jd":
str = diff.Render(renderOptions...)
if str != "" {
haveDiff = true
}
case "patch":
str, err = diff.RenderPatch()
if err != nil {
return "", false, err
}
if str != "[]" {
haveDiff = true
}
case "merge":
str, err = diff.RenderMerge()
if err != nil {
return "", false, err
}
if str != "{}" {
haveDiff = true
}
default:
return "", false, fmt.Errorf("Invalid format: %q", *format)
}
return str, haveDiff, nil
}
func diffV2(a, b string, options []v2.Option) (string, bool, error) {
var aNode, bNode v2.JsonNode
var err error
if *yaml {
aNode, err = v2.ReadYamlString(a)
} else {
aNode, err = v2.ReadJsonString(a)
}
if err != nil {
return "", false, err
}
if *yaml {
bNode, err = v2.ReadYamlString(b)
} else {
bNode, err = v2.ReadJsonString(b)
}
if err != nil {
return "", false, err
}
diff := aNode.Diff(bNode, options...)
var renderOptions []v2.Option
if *color {
renderOptions = append(renderOptions, v2.COLOR)
}
var (
str string
haveDiff bool
)
switch *format {
case "", "jd":
str = diff.Render(renderOptions...)
if str != "" {
haveDiff = true
}
case "patch":
str, err = diff.RenderPatch()
if err != nil {
return "", false, err
}
if str != "[]" {
haveDiff = true
}
case "merge":
str, err = diff.RenderMerge()
if err != nil {
return "", false, err
}
if str != "{}" {
haveDiff = true
}
default:
return "", false, fmt.Errorf("Invalid format: %q", *format)
}
return str, haveDiff, nil
}
func printPatch(p, a string, metadata []jd.Metadata) {
var diff jd.Diff
var err error
switch *format {
case "", "jd":
diff, err = jd.ReadDiffString(p)
case "patch":
diff, err = jd.ReadPatchString(p)
case "merge":
diff, err = jd.ReadMergeString(p)
default:
errorAndExit(fmt.Sprintf("Invalid format: %q", *format))
}
if err != nil {
errorAndExit(err.Error())
}
var aNode jd.JsonNode
if *yaml {
aNode, err = jd.ReadYamlString(a)
} else {
aNode, err = jd.ReadJsonString(a)
}
if err != nil {
errorAndExit(err.Error())
}
bNode, err := aNode.Patch(diff)
if err != nil {
errorAndExit(err.Error())
}
var out string
if *yaml {
out = bNode.Yaml(metadata...)
} else {
out = bNode.Json(metadata...)
}
if *output == "" {
if out == "" {
os.Exit(0)
}
fmt.Print(out)
os.Exit(1)
} else {
if out == "" {
os.Exit(0)
}
ioutil.WriteFile(*output, []byte(out), 0644)
os.Exit(1)
}
}
func printPatchV2(p, a string, options []v2.Option) {
var diff v2.Diff
var err error
switch *format {
case "", "jd":
diff, err = v2.ReadDiffString(p)
case "patch":
diff, err = v2.ReadPatchString(p)
case "merge":
diff, err = v2.ReadMergeString(p)
default:
errorAndExit(fmt.Sprintf("Invalid format: %q", *format))
}
if err != nil {
errorAndExit(err.Error())
}
var aNode v2.JsonNode
if *yaml {
aNode, err = v2.ReadYamlString(a)
} else {
aNode, err = v2.ReadJsonString(a)
}
if err != nil {
errorAndExit(err.Error())
}
bNode, err := aNode.Patch(diff)
if err != nil {
errorAndExit(err.Error())
}
var out string
if *yaml {
out = bNode.Yaml(options...)
} else {
out = bNode.Json(options...)
}
if *output == "" {
if out == "" {
os.Exit(0)
}
fmt.Print(out)
os.Exit(1)
} else {
if out == "" {
os.Exit(0)
}
ioutil.WriteFile(*output, []byte(out), 0644)
os.Exit(1)
}
}
func printTranslation(a string) {
var out string
switch *translate {
case "jd2patch":
if *libv2 {
errorAndExit("jd2patch translation cannot be used with --v2 yet")
}
diff, err := jd.ReadDiffString(a)
if err != nil {
errorAndExit(err.Error())
}
out, err = diff.RenderPatch()
if err != nil {
errorAndExit(err.Error())
}
case "patch2jd":
if *libv2 {
errorAndExit("patch2jd translation cannot be used with --v2 yet")
}
patch, err := jd.ReadPatchString(a)
if err != nil {
errorAndExit(err.Error())
}
out = patch.Render()
case "jd2merge":
if *libv2 {
errorAndExit("jd2merge translation cannot be used with --v2 yet")
}
diff, err := jd.ReadDiffString(a)
if err != nil {
errorAndExit(err.Error())
}
out, err = diff.RenderMerge()
if err != nil {
errorAndExit(err.Error())
}
case "merge2jd":
if *libv2 {
errorAndExit("merge2jd translation cannot be used with --v2 yet")
}
patch, err := jd.ReadMergeString(a)
if err != nil {
errorAndExit(err.Error())
}
out = patch.Render()
case "json2yaml":
node, err := jd.ReadJsonString(a)
if err != nil {
errorAndExit(err.Error())
}
out = node.Yaml()
case "yaml2json":
node, err := jd.ReadYamlString(a)
if err != nil {
errorAndExit(err.Error())
}
out = node.Json()
default:
errorAndExit("unsupported translation: %q", *translate)
}
if *output == "" {
fmt.Print(out)
} else {
ioutil.WriteFile(*output, []byte(out), 0644)
}
os.Exit(0)
}
func errorAndExit(msg string, args ...interface{}) {
log.Printf(msg, args...)
os.Exit(2)
}
func readFile(filename string) string {
bytes, err := ioutil.ReadFile(filename)
if err != nil {
log.Print(err.Error())
os.Exit(2)
}
return string(bytes)
}
func readStdin() string {
r := bufio.NewReader(os.Stdin)
bytes, err := ioutil.ReadAll(r)
if err != nil {
log.Print(err.Error())
os.Exit(2)
}
return string(bytes)
}