forked from tmc/pqstream
-
Notifications
You must be signed in to change notification settings - Fork 0
/
patch.go
40 lines (36 loc) · 864 Bytes
/
patch.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
package pqstream
import (
"bytes"
jsonpatch "github.com/evanphx/json-patch"
"github.com/golang/protobuf/jsonpb"
ptypes_struct "github.com/golang/protobuf/ptypes/struct"
)
func generatePatch(a, b *ptypes_struct.Struct) (*ptypes_struct.Struct, error) {
abytes := &bytes.Buffer{}
bbytes := &bytes.Buffer{}
m := &jsonpb.Marshaler{}
if a != nil {
if err := m.Marshal(abytes, a); err != nil {
return nil, err
}
}
if b != nil {
if err := m.Marshal(bbytes, b); err != nil {
return nil, err
}
}
if abytes.Len() == 0 {
abytes.Write([]byte("{}"))
}
if bbytes.Len() == 0 {
bbytes.Write([]byte("{}"))
}
p, err := jsonpatch.CreateMergePatch(abytes.Bytes(), bbytes.Bytes())
if err != nil {
return nil, err
}
r := &ptypes_struct.Struct{}
rbytes := bytes.NewReader(p)
err = (&jsonpb.Unmarshaler{}).Unmarshal(rbytes, r)
return r, err
}