forked from wI2L/jsondiff
-
Notifications
You must be signed in to change notification settings - Fork 0
/
operation.go
77 lines (67 loc) · 1.64 KB
/
operation.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
package jsondiff
import (
"encoding/json"
"strings"
)
// JSON Patch operation types.
// These are defined in RFC 6902 section 4.
const (
OperationAdd = "add"
OperationReplace = "replace"
OperationRemove = "remove"
OperationMove = "move"
OperationCopy = "copy"
OperationTest = "test"
)
// Operation represents a RFC6902 JSON Patch operation.
type Operation struct {
Type string `json:"op"`
From pointer `json:"from,omitempty"`
Path pointer `json:"path"`
OldValue interface{} `json:"-"`
Value interface{} `json:"value,omitempty"`
}
// String implements the fmt.Stringer interface.
func (o Operation) String() string {
b, err := json.Marshal(o)
if err != nil {
return "<invalid operation>"
}
return string(b)
}
// MarshalJSON implements the json.Marshaler interface.
func (o Operation) MarshalJSON() ([]byte, error) {
type op Operation
switch o.Type {
case OperationCopy, OperationMove:
o.Value = nil
case OperationAdd, OperationReplace, OperationTest:
o.From = emptyPtr
}
return json.Marshal(op(o))
}
// Patch represents a series of JSON Patch operations.
type Patch []Operation
// String implements the fmt.Stringer interface.
func (p Patch) String() string {
sb := strings.Builder{}
for i, op := range p {
if i != 0 {
sb.WriteByte('\n')
}
sb.WriteString(op.String())
}
return sb.String()
}
func (p *Patch) remove(idx int) Patch {
return (*p)[:idx+copy((*p)[idx:], (*p)[idx+1:])]
}
func (p *Patch) append(typ string, from, path pointer, src, tgt interface{}) Patch {
return append(*p, Operation{
Type: typ,
From: from,
Path: path,
OldValue: src,
Value: tgt,
})
}