-
Notifications
You must be signed in to change notification settings - Fork 151
/
unmarshal.go
480 lines (417 loc) · 13.8 KB
/
unmarshal.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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
package args
// unmarshal.go helps with the conversion of
// CLI arguments represented as strings
// into CLI arguments represented as Go data.
import (
"fmt"
"io"
"net"
"reflect"
"strconv"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/karrick/tparse/v2"
"github.com/scaleway/scaleway-sdk-go/scw"
"github.com/scaleway/scaleway-sdk-go/strcase"
)
type Unmarshaler interface {
UnmarshalArgs(value string) error
}
type UnmarshalFunc func(value string, dest interface{}) error
var TestForceNow *time.Time
var unmarshalFuncs = map[reflect.Type]UnmarshalFunc{
reflect.TypeOf((*scw.Size)(nil)).Elem(): func(value string, dest interface{}) error {
// Only support G, GB for now (case insensitive).
value = strings.ToLower(value)
if !strings.HasSuffix(value, "g") && !strings.HasSuffix(value, "gb") {
return fmt.Errorf("size must be defined using the G or GB unit")
}
bytes, err := humanize.ParseBytes(value)
if err != nil {
return err
}
*(dest.(*scw.Size)) = scw.Size(bytes)
return nil
},
reflect.TypeOf((*scw.IPNet)(nil)).Elem(): func(value string, dest interface{}) error {
return dest.(*scw.IPNet).UnmarshalJSON([]byte(`"` + value + `"`))
},
reflect.TypeOf((*net.IP)(nil)).Elem(): func(value string, dest interface{}) error {
ip := net.ParseIP(value)
if ip == nil {
return fmt.Errorf("%s is not a valid IP", value)
}
*(dest.(*net.IP)) = ip
return nil
},
reflect.TypeOf((*io.Reader)(nil)).Elem(): func(value string, dest interface{}) error {
*(dest.(*io.Reader)) = strings.NewReader(value)
return nil
},
reflect.TypeOf((*time.Time)(nil)).Elem(): func(value string, dest interface{}) error {
// Handle absolute time
absoluteTimeParsed, absoluteErr := time.Parse(time.RFC3339, value)
if absoluteErr == nil {
*(dest.(*time.Time)) = absoluteTimeParsed
return nil
}
if len(value) == 0 {
return fmt.Errorf("empty time given")
}
// Handle relative time
if value[0] != '+' && value[0] != '-' {
value = "+" + value
}
m := map[string]time.Time{
"t": time.Now(),
}
if TestForceNow != nil {
m["t"] = *TestForceNow
}
relativeTimeParsed, relativeErr := tparse.ParseWithMap(time.RFC3339, "t"+value, m)
if relativeErr == nil {
*(dest.(*time.Time)) = relativeTimeParsed
return nil
}
return &CannotParseDateError{
ArgValue: value,
AbsoluteTimeParseError: absoluteErr,
RelativeTimeParseError: relativeErr,
}
},
reflect.TypeOf((*time.Duration)(nil)).Elem(): func(value string, dest interface{}) error {
duration, err := time.ParseDuration(value)
if err != nil {
return fmt.Errorf("failed to parse duration: %w", err)
}
*(dest.(*time.Duration)) = duration
return nil
},
reflect.TypeOf((*scw.JSONObject)(nil)).Elem(): func(value string, dest interface{}) error {
jsonObject, err := scw.DecodeJSONObject(value, scw.NoEscape)
if err != nil {
return fmt.Errorf("failed to parse json object: %w", err)
}
*(dest.(*scw.JSONObject)) = jsonObject
return nil
},
reflect.TypeOf((*[]byte)(nil)).Elem(): func(value string, dest interface{}) error {
*(dest.(*[]byte)) = []byte(value)
return nil
},
reflect.TypeOf((*scw.Duration)(nil)).Elem(): func(value string, dest interface{}) error {
duration, err := time.ParseDuration(value)
if err != nil {
return fmt.Errorf("failed to parse duration: %w", err)
}
*(dest.(*scw.Duration)) = *scw.NewDurationFromTimeDuration(duration)
return nil
},
}
// UnmarshalStruct parses args like ["arg1=1", "arg2=2"] to a Go structure using reflection.
//
// args: slice of args passed through the command line
// data: Go structure to fill
func UnmarshalStruct(args []string, data interface{}) error {
// First check if we want to retrieve a simple []string
if raw, ok := data.(*RawArgs); ok {
*raw = args
return nil
}
// Second make sure data is a pointer to a struct or a map.
dest := reflect.ValueOf(data)
if !(dest.Kind() == reflect.Ptr && (dest.Elem().Kind() == reflect.Struct || dest.Elem().Kind() == reflect.Map)) {
return &DataMustBeAPointerError{}
}
dest = dest.Elem()
// Map arg names to their values.
// ["arg1=1", "arg2=2", "arg3"] => [ ["arg1","1"], ["arg2","2"], ["arg3",""] ]
argsSlice := SplitRaw(args)
processedArgNames := make(map[string]bool)
// Loop through all arguments
for _, kv := range argsSlice {
argName, argValue := kv[0], kv[1]
argNameWords := strings.Split(argName, ".")
if processedArgNames[argName] {
return &UnmarshalArgError{
ArgName: argName,
ArgValue: argValue,
Err: &DuplicateArgError{},
}
}
// We check that we did not already handle an argument value set on a child or a parent
// Example `cluster=premium cluster.volume.size=12` cannot be valid as both args are in conflict.
// Example `cluster.volume.size=12 cluster=premium` should also be invalid.
for processedArgName := range processedArgNames {
// We put the longest argName in long and the shortest in short.
short, long := argName, processedArgName
if len(long) < len(short) {
short, long = long, short
}
// We check if the longest starts with short+"."
// If it does this mean we have a conflict.
if strings.HasPrefix(long, short+".") {
return &ConflictArgError{
ArgName1: processedArgName,
ArgName2: argName,
}
}
}
processedArgNames[argName] = true
// Set will recursively find the correct field to set.
err := set(dest, argNameWords, argValue)
if err != nil {
return &UnmarshalArgError{
ArgName: argName,
ArgValue: argValue,
Err: err,
}
}
}
return nil
}
// IsUmarshalableValue returns true if data type could be unmarshalled with args.UnmarshalValue
func IsUmarshalableValue(data interface{}) bool {
dest := reflect.ValueOf(data)
if !dest.IsValid() {
return false
}
for dest.Kind() == reflect.Ptr {
dest = dest.Elem()
}
return isUnmarshalableValue(dest)
}
// RegisterUnmarshalFunc registers an UnmarshalFunc for a given interface.
// i must be a pointer.
func RegisterUnmarshalFunc(i interface{}, unmarshalFunc UnmarshalFunc) {
unmarshalFuncs[reflect.TypeOf(i).Elem()] = unmarshalFunc
}
// set sets a (sub)value of a data structure.
// It uses reflection to go as deep as necessary into the data struct, following the arg name passed.
//
// dest: the structure to be completed
// argNameWords: the name of the argument to set
// value: the value to be set, represented as a string
//
// Example: argNameWords ["contacts", "0", "address", "city"] will set value "city" for your first contact in your phone book.
func set(dest reflect.Value, argNameWords []string, value string) error {
// If dest has a custom unmarshaler, we use it.
// dest can either implement Unmarshaler
// or have an UnmarshalFunc() registered.
if isUnmarshalableValue(dest) {
if len(argNameWords) != 0 {
// Trying to unmarshal a nested field inside an unmarshalable type
return &CannotSetNestedFieldError{
Dest: dest.Interface(),
}
}
for dest.Kind() == reflect.Ptr {
dest.Set(reflect.New(dest.Type().Elem()))
dest = dest.Elem()
}
return unmarshalValue(value, dest)
}
switch dest.Kind() {
case reflect.Ptr:
// If type is a nil pointer we create a new Value. NB: maps and slices are pointers.
if dest.IsNil() {
dest.Set(reflect.New(dest.Type().Elem()))
}
// When:
// - dest is a pointer to a slice
// - there is no more argNameWords left
// - value == none
// slice ptr was allocated
// we allocate the empty slice and return
if dest.Elem().Kind() == reflect.Slice && len(argNameWords) == 0 && value == emptySliceValue {
sliceDest := dest.Elem()
sliceDest.Set(reflect.MakeSlice(sliceDest.Type(), 0, 0))
return nil
}
// Call set with the pointer.Elem()
return set(dest.Elem(), argNameWords, value)
case reflect.Slice:
// If type is a slice:
// We cannot handle slice without an index notation.
if len(argNameWords) == 0 {
return &MissingIndexOnArrayError{}
}
// We check if argNameWords[0] is a positive integer to handle cases like keys.0.value=12
index, err := strconv.ParseUint(argNameWords[0], 10, 32) // a slice index is 32 bit
if err != nil {
return &InvalidIndexError{Index: argNameWords[0]}
}
// Make sure array is big enough to access the correct index.
diff := int(index) - dest.Len()
switch {
case diff > 0:
return &MissingIndicesInArrayError{IndexToInsert: int(index), CurrentLength: dest.Len()}
case diff == 0:
// Append one element to our slice.
dest.Set(reflect.AppendSlice(dest, reflect.MakeSlice(dest.Type(), 1, 1)))
case diff < 0:
// Element already exist at current index.
}
// Recursively call set without the index word
return set(dest.Index(int(index)), argNameWords[1:], value)
case reflect.Map:
// If map is nil we create it.
if dest.IsNil() {
dest.Set(reflect.MakeMap(dest.Type()))
}
if len(argNameWords) == 0 {
return &MissingMapKeyError{}
}
// Create a new value if it does not exist, then call set and add result in the map
mapKey := reflect.ValueOf(argNameWords[0])
mapValue := dest.MapIndex(mapKey)
if !mapValue.IsValid() {
mapValue = reflect.New(dest.Type().Elem()).Elem()
}
err := set(mapValue, argNameWords[1:], value)
dest.SetMapIndex(mapKey, mapValue)
return err
case reflect.Struct:
if len(argNameWords) == 0 {
return &MissingStructFieldError{Dest: dest.Interface()}
}
// We cannot rely on dest.GetFieldByName() as reflect library is doing deep traversing when using anonymous field.
// Because of that we should rely on our own logic
//
// - First we try to find a field with the correct name in the current struct
// - If it does not exist we try to find it in all nested anonymous fields
// Anonymous fields are traversed from last to first as the last one in the struct declaration should take precedence
// We construct two caches:
anonymousFieldIndexes := []int(nil)
fieldIndexByName := map[string]int{}
for i := 0; i < dest.Type().NumField(); i++ {
field := dest.Type().Field(i)
if field.Anonymous {
anonymousFieldIndexes = append(anonymousFieldIndexes, i)
} else {
fieldIndexByName[field.Name] = i
}
}
// Make sure argument name is correct.
// We enforce this check to avoid not well formatted argument name to work by "accident"
// as we use ToPublicGoName on the argument name later on.
if !validArgNameRegex.MatchString(argNameWords[0]) {
return error(&InvalidArgNameError{})
}
// Try to find the correct field in the current struct.
fieldName := strcase.ToPublicGoName(argNameWords[0])
if fieldIndex, exist := fieldIndexByName[fieldName]; exist {
return set(dest.Field(fieldIndex), argNameWords[1:], value)
}
// If it does not exist we try to find it in nested anonymous field
for i := len(anonymousFieldIndexes) - 1; i >= 0; i-- {
err := set(dest.Field(anonymousFieldIndexes[i]), argNameWords, value)
switch err.(type) {
case nil:
// If we got no error the field was correctly set we return nil.
return nil
case *UnknownArgError:
// If err is an UnknownArgError this could mean the field is in another anonymous field
// We continue to the previous anonymous field.
continue
default:
// If we get any other error this mean something went wrong we return an error.
return err
}
}
// We look in all struct fields + all anonymous fields without success.
return &UnknownArgError{}
}
return &UnmarshalableTypeError{Dest: dest.Interface()}
}
// unmarshalScalar handles unmarshaling from a string to a scalar type .
// It handles transformation like Atoi if dest is an Integer.
func unmarshalScalar(value string, dest reflect.Value) error {
bitSize := map[reflect.Kind]int{
reflect.Int: 0,
reflect.Int8: 8,
reflect.Int16: 16,
reflect.Int32: 32,
reflect.Int64: 64,
reflect.Uint: 0,
reflect.Uint8: 8,
reflect.Uint16: 16,
reflect.Uint32: 32,
reflect.Uint64: 64,
reflect.Float32: 32,
reflect.Float64: 64,
}
switch dest.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
i, err := strconv.ParseInt(value, 0, bitSize[dest.Kind()])
dest.SetInt(i)
return err
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
i, err := strconv.ParseUint(value, 0, bitSize[dest.Kind()])
dest.SetUint(i)
return err
case reflect.Float32, reflect.Float64:
f, err := strconv.ParseFloat(value, bitSize[dest.Kind()])
dest.SetFloat(f)
return err
case reflect.Bool:
switch value {
case "true":
dest.SetBool(true)
case "false":
dest.SetBool(false)
default:
return &CannotParseBoolError{Value: value}
}
return nil
case reflect.String:
dest.SetString(value)
return nil
default:
return &UnmarshalableTypeError{Dest: dest.Interface()}
}
}
// A type is unmarshalable if:
// - it implement Unmarshaler
// - it has an unmarshalFunc
// - it is a scalar type
func isUnmarshalableValue(dest reflect.Value) bool {
value := getInterfaceFromReflectValue(dest)
_, isUnmarshaler := value.(Unmarshaler)
_, hasUnmarshalFunc := unmarshalFuncs[dest.Type()]
_, isScalar := scalarKinds[dest.Kind()]
return isUnmarshaler || hasUnmarshalFunc || isScalar
}
func unmarshalValue(value string, dest reflect.Value) error {
iValue := getInterfaceFromReflectValue(dest)
// If src implements Marshaler we call MarshalArgs with the value
unmarshaler, isUnmarshaler := iValue.(Unmarshaler)
if isUnmarshaler && unmarshaler != nil {
return unmarshaler.UnmarshalArgs(value)
}
// If src has a registered MarshalFunc(), use it.
if unmarshalFunc, exists := unmarshalFuncs[dest.Type()]; exists {
err := unmarshalFunc(value, dest.Addr().Interface())
if err != nil {
return &CannotUnmarshalError{
Dest: dest.Addr().Interface(),
Err: err,
}
}
return nil
}
if scalarKinds[dest.Kind()] {
err := unmarshalScalar(value, dest)
if err != nil {
return &CannotUnmarshalError{
Dest: dest.Addr().Interface(),
Err: err,
}
}
return nil
}
return &CannotUnmarshalError{
Dest: dest.Interface(),
}
}