| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "fmt" |
| 5 | "io/ioutil" |
| 6 | "log" |
| 7 | "os" |
| 8 | |
| 9 | jsonpatch "github.com/evanphx/json-patch" |
| 10 | flags "github.com/jessevdk/go-flags" |
| 11 | ) |
| 12 | |
| 13 | type opts struct { |
| 14 | PatchFilePaths []FileFlag `long:"patch-file" short:"p" value-name:"PATH" description:"Path to file with one or more operations"` |
| 15 | } |
| 16 | |
| 17 | func main() { |
| 18 | var o opts |
| 19 | _, err := flags.Parse(&o) |
| 20 | if err != nil { |
| 21 | log.Fatalf("error: %s\n", err) |
| 22 | } |
| 23 | |
| 24 | patches := make([]jsonpatch.Patch, len(o.PatchFilePaths)) |
| 25 | |
| 26 | for i, patchFilePath := range o.PatchFilePaths { |
| 27 | var bs []byte |
| 28 | bs, err = ioutil.ReadFile(patchFilePath.Path()) |
| 29 | if err != nil { |
| 30 | log.Fatalf("error reading patch file: %s", err) |
| 31 | } |
| 32 | |
| 33 | var patch jsonpatch.Patch |
| 34 | patch, err = jsonpatch.DecodePatch(bs) |
| 35 | if err != nil { |
| 36 | log.Fatalf("error decoding patch file: %s", err) |
| 37 | } |
| 38 | |
| 39 | patches[i] = patch |
| 40 | } |
| 41 | |
| 42 | doc, err := ioutil.ReadAll(os.Stdin) |
| 43 | if err != nil { |
| 44 | log.Fatalf("error reading from stdin: %s", err) |
| 45 | } |
| 46 | |
| 47 | mdoc := doc |
| 48 | for _, patch := range patches { |
| 49 | mdoc, err = patch.Apply(mdoc) |
| 50 | if err != nil { |
| 51 | log.Fatalf("error applying patch: %s", err) |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | fmt.Printf("%s", mdoc) |
| 56 | } |