-
Notifications
You must be signed in to change notification settings - Fork 10
/
extract.go
191 lines (179 loc) · 4.81 KB
/
extract.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
// © 2023 Snyk Limited All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package interfacetricks
import (
"fmt"
"reflect"
"strings"
)
type ExtractError struct {
SrcPath []interface{}
SrcType reflect.Type
DstType reflect.Type
}
func (e ExtractError) Error() string {
pieces := []string{}
for _, piece := range e.SrcPath {
switch v := piece.(type) {
case int:
pieces = append(pieces, fmt.Sprintf("%d", v))
case string:
pieces = append(pieces, v)
default:
pieces = append(pieces, fmt.Sprintf("%v", v))
}
}
src := "nil"
if e.SrcType != nil {
src = e.SrcType.String()
}
dst := "nil"
if e.DstType != nil {
dst = e.DstType.String()
}
return fmt.Sprintf(
"extract type mismatch at %s: could not map source %s to destination %s",
strings.Join(pieces, "/"),
src,
dst,
)
}
// Extract "deserializes" an interface into a target destination, using the
// "encoding/json" conventions.
//
// No actual serialization happens, which means we can avoid a lot of string
// copies.
//
// The extraction will try to continue even when errors are encountered and
// return detailed error information for each problem.
func Extract(src interface{}, dst interface{}) []error {
return extract([]interface{}{}, src, reflect.ValueOf(dst))
}
// NOTE: This code is based on pkg/rego/bind.go, and updates may need to go
// there as well.
func extract(path []interface{}, src interface{}, dst reflect.Value) (errs []error) {
ty := dst.Type()
switch ty.Kind() {
case reflect.Pointer:
return extract(path, src, dst.Elem())
case reflect.Struct:
if srcObject, ok := src.(map[string]interface{}); ok {
for i := 0; i < ty.NumField(); i++ {
field := ty.Field(i)
goFieldVal := dst.Field(i)
goFieldVal.Set(reflect.Zero(field.Type)) // Set to zero/nil
if jsonFieldName, ok := getJsonFieldName(field); ok {
if srcFieldVal, ok := srcObject[jsonFieldName]; ok {
// Initialize if pointer
if field.Type.Kind() == reflect.Pointer {
goFieldVal.Set(reflect.New(field.Type.Elem()))
}
path = append(path, jsonFieldName)
errs = append(errs, extract(path, srcFieldVal, goFieldVal)...)
path = path[:len(path)-1]
}
} else {
}
}
return
}
case reflect.Slice:
if srcArray, ok := src.([]interface{}); ok && dst.CanSet() {
dst.Set(reflect.MakeSlice(ty, len(srcArray), len(srcArray)))
for i := 0; i < len(srcArray); i++ {
path = append(path, i)
errs = append(errs, extract(path, srcArray[i], dst.Index(i))...)
path = path[:len(path)-1]
}
return
}
case reflect.Map:
if srcObject, ok := src.(map[string]interface{}); ok && dst.CanSet() {
dst.Set(reflect.MakeMap(ty))
for k, v := range srcObject {
path = append(path, k)
key := reflect.New(ty.Key())
keyErrs := extract(path, k, key)
errs = append(errs, keyErrs...)
if len(keyErrs) == 0 {
val := reflect.New(ty.Elem())
errs = append(errs, extract(path, v, val)...)
dst.SetMapIndex(key.Elem(), val.Elem())
}
path = path[:len(path)-1]
}
return
}
case reflect.Interface:
if dst.CanSet() {
dst.Set(reflect.ValueOf(src))
return
}
case reflect.Bool:
if boolean, ok := src.(bool); ok && dst.CanSet() {
dst.SetBool(boolean)
return
}
case reflect.Int:
if number, ok := src.(int64); ok {
if dst.CanSet() {
dst.SetInt(number)
return
}
} else if number, ok := src.(int); ok {
if dst.CanSet() {
dst.SetInt(int64(number))
return
}
} else if number, ok := src.(float64); ok {
if dst.CanSet() {
dst.SetInt(int64(number))
return
}
}
case reflect.Float64:
if number, ok := src.(float64); ok {
if dst.CanSet() {
dst.SetFloat(number)
return
}
}
case reflect.String:
if str, ok := src.(string); ok && dst.CanSet() {
dst.SetString(str)
return
}
}
return []error{newExtractError(path, src, ty)}
}
func newExtractError(path []interface{}, src interface{}, dst reflect.Type) ExtractError {
pcopy := make([]interface{}, len(path))
copy(pcopy, path)
return ExtractError{
SrcPath: pcopy,
SrcType: reflect.TypeOf(src),
DstType: dst,
}
}
func getJsonFieldName(field reflect.StructField) (string, bool) {
tag, ok := field.Tag.Lookup("json")
if !ok {
return "", false
}
pieces := strings.SplitN(tag, ",", 2)
if len(pieces) >= 1 {
return pieces[0], true
}
return "", false
}