-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhandler.go
More file actions
318 lines (296 loc) · 7.62 KB
/
Copy pathhandler.go
File metadata and controls
318 lines (296 loc) · 7.62 KB
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
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
package enc
import (
"encoding/json"
"fmt"
"reflect"
"time"
"github.com/Aize-Public/forego/ctx"
"github.com/Aize-Public/forego/ctx/log"
)
// generic object that do the Unmarshal()/Conflate()
type Handler struct {
Factory map[reflect.Type]func(c ctx.C, n Node) (any, error)
// called if a field is present in the NodeTree but there is no mapping on the object it's unmarshaled into
UnhandledFields func(c ctx.C, path []any, n Node) error
Debugf func(c ctx.C, f string, args ...any)
path path
}
func (this Handler) Append(p any) Handler {
this.path = append(this.path, p)
return this
}
var ineff = map[string]bool{}
func MustUnmarshal(c ctx.C, n Node, into any) {
err := Handler{}.Unmarshal(c, n, into)
if err != nil {
panic(err)
}
}
func Unmarshal(c ctx.C, n Node, into any) error {
return Handler{}.Unmarshal(c, n, into)
}
func (this Handler) Unmarshal(c ctx.C, n Node, into any) error {
if n == nil {
n = Nil{}
}
v := reflect.ValueOf(into).Elem()
return this.Append(v.Type()).unmarshal(c, n, v)
}
func (this Handler) unmarshal(c ctx.C, from Node, v reflect.Value) error {
//c = ctx.WithTag(c, "path", this.path.String()) // NOTE(oha): this is a bit slow because the json part
//defer log.Debugf(c, "unmarshal( %T %+v => %v{%+v} )", from, from, v.Type(), v)
if this.Debugf != nil {
this.Debugf(c, "unmarshal( %v -> %v{%v} )", from, v.Type(), v)
}
if !v.CanSet() {
return ctx.NewErrorf(c, "can't assign %v", v)
}
if v.Kind() == reflect.Pointer {
switch from.(type) {
case Nil:
v.SetZero()
return nil
default:
vv := reflect.New(v.Type().Elem())
v.Set(vv)
if this.Debugf != nil {
this.Debugf(c, "pointer deref: %v -> %v", v.Type(), v.Elem().Type())
}
return this.unmarshal(c, from, v.Elem())
}
}
switch into := v.Addr().Interface().(type) {
case Unmarshaler:
if this.Debugf != nil {
this.Debugf(c, "is %T", into)
}
return into.UnmarshalNode(c, from)
case *json.RawMessage:
if this.Debugf != nil {
this.Debugf(c, "is %T", into)
}
*into = JSON{}.Encode(c, from)
warnIneff(c, "Warn: inefficient json.RawMessage, use enc.Node instead")
return nil
case *time.Time:
var t time.Time
err := json.Unmarshal(JSON{}.Encode(c, from), &t)
if err != nil {
return ctx.NewErrorf(c, "can't unmarshal %#v as time", from)
}
*into = t
return nil
case json.Unmarshaler:
if this.Debugf != nil {
this.Debugf(c, "is %T", into)
}
warnIneff(c, "Warn: inefficient %T.UnmarshalJSON(): implement enc.Unmarshaler instead", into)
j, _ := json.Marshal(from) // we must go back to the json
return into.UnmarshalJSON(j)
case *Node:
if this.Debugf != nil {
this.Debugf(c, "is %T", into)
}
// NOTE(oha) if a struct has a field of type enc.Node, we drop the data there (similarly to json.RawMessage)
*into = from
return nil
}
/*
vv := v.Elem()
switch from.(type) {
case nil, Nil:
vv.SetZero()
return nil
}
*/
if this.Factory != nil {
f := this.Factory[v.Type()]
if f != nil {
log.Debugf(c, "factory for type %v", v.Type())
obj, err := f(c, from)
if err != nil {
return ctx.NewErrorf(c, "factory error: %w", err)
}
s := reflect.ValueOf(obj)
if !s.CanConvert(v.Elem().Type()) {
return ctx.NewErrorf(c, "Factory %v returned %v which can't be converted to %v",
v.Type().Elem(), s.Type(), v.Elem().Type())
}
log.Debugf(c, "Factory %v returned %v which can be converted to %v",
v.Type().Elem(), s.Type(), v.Elem().Type())
v.Elem().Set(s) // we set the value, not the pointer... because go.reflect
return nil
}
}
//log.Debugf(c, "OHA %T => %v", from, v.Type())
if this.Debugf != nil {
this.Debugf(c, "normal type: %v, use generic %T.unmarshalInto()", v.Type(), from)
}
/*
if v.Kind() == reflect.Pointer {
// if we unmarshal into a pointer, we create the zero value and unmarshal into that instead
// this allow to unmarshal into *bool or *string
e := reflect.New(v.Type().Elem())
log.Debugf(c, "OHA4: %v", e.Type())
err := from.unmarshalInto(c, this, path, e.Elem())
if err != nil {
return err
}
v.Set(e)
return nil
}
*/
return from.unmarshalInto(c, this, v)
}
func warnIneff(c ctx.C, f string, args ...any) {
msg := fmt.Sprintf(f, args...)
if !ineff[msg] {
ineff[msg] = true
log.Warnf(c, f, args...)
}
}
// transform an object into a enc.Node
func Marshal(c ctx.C, in any) (Node, error) {
return Handler{}.Marshal(c, in)
}
func (this Handler) Marshal(c ctx.C, in any) (Node, error) {
//log.Warnf(c, "OHA: %T %v", in, in)
switch in := in.(type) {
case nil:
return Nil{}, nil
case Node:
return in, nil
case Marshaler:
//log.Warnf(c, "OHA: %T->MarshalNode", in)
return in.MarshalNode(c)
case time.Time:
return Time(in), nil
//return String(in.Format(time.RFC3339Nano)), nil
case ctx.Error:
return String(in.Error()), nil
case *ctx.Error:
return String(in.Error()), nil
case json.Marshaler:
j, err := in.MarshalJSON()
if err != nil {
return nil, err
}
return JSON{}.Decode(c, j)
}
v := reflect.ValueOf(in)
t := v.Type()
switch t.Kind() {
default:
log.Warnf(c, "possible wrong fallback for type %T", in)
return fromNative(in), nil
case reflect.Func:
return nil, ctx.NewErrorf(c, "can't marshal %T", in)
case reflect.Bool:
return Bool(v.Bool()), nil
case reflect.Float64, reflect.Float32:
return Float(v.Float()), nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
return Integer(v.Int()), nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return Integer(v.Uint()), nil
case reflect.String:
return String(v.String()), nil
case reflect.Pointer:
if v.IsNil() {
return Nil{}, nil
}
return this.Marshal(c, v.Elem().Interface())
case reflect.Slice:
if v.IsNil() {
return Nil{}, nil
}
fallthrough //Intentional, since the above check breaks when called on arrays
case reflect.Array:
list := List{}
for i := 0; i < v.Len(); i++ {
ev := v.Index(i)
e, err := this.Marshal(c, ev.Interface())
if err != nil {
return nil, err
}
list = append(list, e)
}
return list, nil
case reflect.Map:
if v.IsNil() {
return Nil{}, nil
}
m := Map{}
for _, kv := range v.MapKeys() {
vv := v.MapIndex(kv)
n, err := this.Marshal(c, vv.Interface())
if err != nil {
return nil, err
}
switch k := kv.Interface().(type) {
case string:
m[k] = n
default:
nk, err := this.Marshal(c, k)
if err != nil {
return nil, err
}
switch nk := nk.(type) {
case String:
m[string(nk)] = n
case Integer:
m[fmt.Sprint(nk)] = n
case Float:
m[fmt.Sprint(nk)] = n
case Digits:
m[fmt.Sprint(nk)] = n
default:
return nil, ctx.NewErrorf(c, "can't marshal %v as map key", kv.Type())
}
}
}
return m, nil
case reflect.Struct:
}
out := Pairs{}
for i := 0; i < v.NumField(); i++ {
ft := t.Field(i)
if !ft.IsExported() {
continue
}
tag := parseTag(ft)
if tag.Skip {
continue
}
fv := v.Field(i)
fn, err := this.Marshal(c, fv.Interface())
if err != nil {
return nil, err
}
switch fn := fn.(type) {
case Nil:
if !tag.OmitEmpty {
out = append(out, Pair{tag.Name, tag.JSON, fn})
}
case String:
if !tag.OmitEmpty || fn != "" {
out = append(out, Pair{tag.Name, tag.JSON, fn})
}
case Integer:
if !tag.OmitEmpty || fn != 0 {
out = append(out, Pair{tag.Name, tag.JSON, fn})
}
case Float:
if !tag.OmitEmpty || fn != 0.0 {
out = append(out, Pair{tag.Name, tag.JSON, fn})
}
case Digits:
if !tag.OmitEmpty || fn != "" {
out = append(out, Pair{tag.Name, tag.JSON, fn})
}
default:
out = append(out, Pair{tag.Name, tag.JSON, fn})
}
}
return out, nil
}