Debian Codegraph @

jp/main.go

raw
1 package main
2
3 import (
4 "encoding/json"
5 "fmt"
6 "io/ioutil"
7 "os"
8
9 "github.com/urfave/cli"
10
11 diff "github.com/yudai/gojsondiff"
12 )
13
14 func main() {
15 app := cli.NewApp()
16 app.Name = "jd"
17 app.Usage = "JSON Diff"
18 app.Version = "0.0.2"
19
20 app.Flags = []cli.Flag{}
21
22 app.Action = func(c *cli.Context) {
23 if len(c.Args()) < 2 {
24 fmt.Println("Not enough arguments.\n")
25 fmt.Printf("Usage: %s diff json_file\n", app.Name)
26 os.Exit(1)
27 }
28
29 diffFilePath := c.Args()[0]
30 jsonFilePath := c.Args()[1]
31
32 // Diff file
33 diffFile, err := ioutil.ReadFile(diffFilePath)
34 if err != nil {
35 fmt.Printf("Failed to open file '%s': %s\n", diffFilePath, err.Error())
36 os.Exit(2)
37 }
38
39 // Load Diff file
40 um := diff.NewUnmarshaller()
41 diffObject, err := um.UnmarshalBytes(diffFile)
42 if err != nil {
43 fmt.Printf("Failed to load diff file '%s': %s\n", diffFilePath, err.Error())
44 os.Exit(2)
45 }
46
47 // JSON file
48 jsonFile, err := ioutil.ReadFile(jsonFilePath)
49 if err != nil {
50 fmt.Printf("Failed to open file '%s': %s\n", jsonFilePath, err.Error())
51 os.Exit(2)
52 }
53
54 // Load JSON
55 var jsonObject map[string]interface{}
56 json.Unmarshal(jsonFile, &jsonObject)
57
58 // Apply
59 differ := diff.New()
60 differ.ApplyPatch(jsonObject, diffObject)
61
62 pachedJson, _ := json.MarshalIndent(jsonObject, "", " ")
63 fmt.Println(string(pachedJson))
64 }
65
66 app.Run(os.Args)
67 }