-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpatch.go
173 lines (145 loc) · 3.46 KB
/
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
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
package gopatch
import (
"encoding/json"
"errors"
"fmt"
"io"
"reflect"
"strings"
)
// Todo list
// float to in conversion
// support pointer fields
// support test op
// support nested structs
// comments and documentation
// allow user to provide operation logic
const (
Test = "test"
Replace = "replace"
Add = "add"
Remove = "remove"
FieldTag = "patch_field"
)
var (
ErrNotImplemented = errors.New("not implemented yet")
ErrInvalidPath = errors.New("invalid path")
ErrUnsupportedOp = errors.New("unsupported operation")
ErrApplyOp = errors.New("cannot apply patch operation")
)
type Operation interface {
Op() string
Path() []string
Value() interface{}
ApplyTo(object interface{}) error
}
type Patch []Operation
type operationData struct {
Path []string
Value interface{}
}
type JsonOperation struct {
Op string
Path string
Value interface{}
}
func NewPatch(reader io.Reader) (Patch, error) {
var newPatch []JsonOperation
err := json.NewDecoder(reader).Decode(&newPatch)
if err != nil {
return nil, err
}
ops := make([]Operation, len(newPatch))
for i, jsonOp := range newPatch {
operation, err := toOperation(jsonOp)
if err != nil {
return nil, err
}
ops[i] = operation
}
return ops, nil
}
func ApplyPatch(patch Patch, object interface{}) error {
for _, op := range patch {
err := op.ApplyTo(object)
if err != nil {
return err
}
}
return nil
}
func toOperation(jsonOp JsonOperation) (Operation, error) {
path := strings.Split(jsonOp.Path, "/")
fields := make([]string, 0)
for _, f := range path {
if f != "" {
fields = append(fields, f)
}
}
if len(fields) == 0 {
return nil, fmt.Errorf("%w: %s", ErrInvalidPath, jsonOp.Path)
}
// temporary check until nested structs are implemented
if len(fields) > 1 {
return nil, fmt.Errorf("%w: %s", ErrNotImplemented, jsonOp.Path)
}
opData := operationData{
Path: fields,
Value: jsonOp.Value,
}
switch jsonOp.Op {
case Replace:
return &ReplaceOperation{opData}, nil
}
return nil, fmt.Errorf("%w: %s", ErrUnsupportedOp, jsonOp.Op)
}
type ReplaceOperation struct {
operationData
}
func (r ReplaceOperation) Op() string {
return Replace
}
func (r ReplaceOperation) Path() []string {
return r.operationData.Path
}
func (r ReplaceOperation) Value() interface{} {
return r.operationData.Value
}
func (r ReplaceOperation) String() string {
return fmt.Sprintf("Op: %s, Path: %q, Value: %v", Replace, r.Path(), r.Value())
}
func (r ReplaceOperation) ApplyTo(object interface{}) error {
target := reflect.ValueOf(object)
if target.Kind() == reflect.Ptr && target.Elem().Kind() == reflect.Struct {
target = findField(target.Elem(), r.Path()[0])
if target.IsValid() && target.CanSet() {
source := reflect.ValueOf(r.Value())
if target.Kind() == source.Kind() {
target.Set(source)
return nil
}
if !source.IsValid() {
zeroValue := reflect.Zero(target.Type())
target.Set(zeroValue)
return nil
}
}
}
return fmt.Errorf("%w {%s} to %v", ErrApplyOp, r, object)
}
func findField(structValue reflect.Value, fieldName string) reflect.Value {
field := structValue.FieldByNameFunc(func(structFieldName string) bool {
return strings.EqualFold(structFieldName, fieldName)
})
if field.IsValid() {
return field
}
structType := structValue.Type()
for i := 0; i < structValue.NumField(); i++ {
tag := structType.Field(i).Tag.Get(FieldTag)
if tag == fieldName {
return structValue.Field(i)
}
}
return reflect.Value{}
}