-
Notifications
You must be signed in to change notification settings - Fork 151
/
marshal.go
287 lines (249 loc) · 7.87 KB
/
marshal.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
package args
// marshal.go helps with the conversion of
// CLI arguments represented as go data
// into CLI arguments represented as strings.
import (
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"time"
"github.com/dustin/go-humanize"
"github.com/scaleway/scaleway-sdk-go/scw"
"github.com/scaleway/scaleway-sdk-go/strcase"
)
type Marshaler interface {
MarshalArgs() (string, error)
}
type MarshalFunc func(src interface{}) (string, error)
var marshalFuncs = map[reflect.Type]MarshalFunc{
reflect.TypeOf((*scw.Size)(nil)).Elem(): func(src interface{}) (s string, e error) {
v := src.(*scw.Size)
value := humanize.Bytes(uint64(*v))
value = strings.Replace(value, " ", "", -1)
return value, nil
},
reflect.TypeOf((*time.Time)(nil)).Elem(): func(src interface{}) (string, error) {
v := src.(*time.Time)
return v.Format(time.RFC3339), nil
},
}
// MarshalStruct marshals a go struct using reflection to args like ["arg1=1", "arg2=2"].
// This function only marshal struct.
// If you wish to unmarshal a single value ( the part on the right of the `=` in arg notation )
// you should use MarshalValue instead.
func MarshalStruct(data interface{}) (args []string, err error) {
// First check if data is just a []string
if raw, ok := data.(*RawArgs); ok {
return *raw, nil
}
// Second make sure data is a pointer to a struct or a map.
src := reflect.ValueOf(data)
if !(src.Kind() == reflect.Ptr && (src.Elem().Kind() == reflect.Struct || src.Elem().Kind() == reflect.Map)) {
return nil, &DataMustBeAPointerError{}
}
return marshal(src, nil)
}
// MarshalValue marshals a single value. While MarshalStruct will convert a go struct to an argument list like ["arg1=1", "arg2=2"],
// MarshalValue will only marshal a single argument an return the arg value ( right part of the `=` )
func MarshalValue(data interface{}) (string, error) {
if isInterfaceNil(data) {
return "", nil
}
src := reflect.ValueOf(data)
if !src.CanAddr() {
// This happen when we call MarshalValue with a non addressable variable
// example MarshalValue(Region("fr-par"))
// A non addressable variable may break Marshal in case of custom Marshaler
tmp := reflect.New(src.Type())
tmp.Elem().Set(src)
src = tmp
}
m, err := marshal(src, nil)
if err != nil {
return "", err
}
// If we do not get a single key this is probably because we try to marshal a struct
if len(m) != 1 {
return "", &DataMustBeAMarshalableValueError{}
}
return m[0], nil
}
// RegisterMarshalFunc registers a MarshalFunc for a given interface.
// i must be a pointer.
func RegisterMarshalFunc(i interface{}, marshalFunc MarshalFunc) {
marshalFuncs[reflect.TypeOf(i).Elem()] = marshalFunc
}
// marshal is a recursive function that implements arg marshaling.
// It will take care of pointers resolution, nested structs, etc.
//
// If this function is called with:
// - a marshal-able value: [ "${keys.join(.)}=${marshaledValue}" ]
// - a go struct: [ "${keys.join(.)}.field1=${marshaledField1}", ... ]
// - a go map: [ "${keys.join(.)}.key1=${marshaledValue1}", ... ]
// - a go slice: [ "${keys.join(.)}.0=${marshaledValue0}", ... ]
//
// src: the value to marshal
// keys: the parent keys used by recursion (nil on first level)
//
// args: the CLI arguments as a slice of key-value pairs, each represented as a string
// err: an error if the function failed
func marshal(src reflect.Value, keys []string) (args []string, err error) {
if src.IsValid() && isMarshalableValue(src) {
value, err := marshalValue(src)
if err != nil {
return nil, err
}
isDefault, err := isDefaultValue(src)
if isDefault {
return nil, err
}
return []string{marshalKeyValue(keys, value)}, nil
}
switch src.Kind() {
case reflect.Ptr:
// If src is nil we do not marshal it
if src.IsNil() {
return nil, nil
}
// When:
// - dest is a pointer to a slice
// - The slice is empty
// we return slice=none
if src.Elem().Kind() == reflect.Slice && src.Elem().Len() == 0 {
return append(args, marshalKeyValue(keys, emptySliceValue)), nil
}
// If type is a pointer we Marshal pointer.Elem()
return marshal(src.Elem(), keys)
case reflect.Slice:
// If type is a slice:
// We loop through all items and marshal them with key = key.0, key.1, ....
args := []string(nil)
for i := 0; i < src.Len(); i++ {
subArgs, err := marshal(src.Index(i), append(keys, strconv.Itoa(i)))
if err != nil {
return nil, err
}
args = append(args, subArgs...)
}
return args, nil
case reflect.Map:
// If map is nil we do not marshal it
if src.IsNil() {
return nil, nil
}
// If type is a map:
// We loop through all items and marshal them with key = key.0, key.1, ....
args := []string(nil)
// Get all map keys and sort them. We assume keys are string
mapKeys := src.MapKeys()
sort.Slice(mapKeys, func(i, j int) bool {
return mapKeys[i].String() < mapKeys[j].String()
})
for _, mapKey := range mapKeys {
mapValue := src.MapIndex(mapKey)
newArgs, err := marshal(mapValue, append(keys, mapKey.String()))
if err != nil {
return nil, err
}
args = append(args, newArgs...)
}
return args, nil
case reflect.Struct:
// If type is a struct
// We loop through all struct field
args := []string(nil)
for i := 0; i < src.NumField(); i++ {
fieldValue := src.Field(i)
key := strcase.ToBashArg(src.Type().Field(i).Name)
newArgs, err := marshal(fieldValue, append(keys, key))
if err != nil {
return nil, err
}
args = append(args, newArgs...)
}
return args, nil
default:
// If value is default value for type (e.g. empty for a string or 0 for an int). We do not marshal it.
isDefault, err := isDefaultValue(src)
if err != nil {
return nil, err
}
if isDefault {
return nil, nil
}
return []string{marshalKeyValue(keys, src.Interface())}, nil
}
}
func marshalValue(src reflect.Value) (string, error) {
value := getInterfaceFromReflectValue(src)
// If src implements Marshaler we call MarshalArgs with the value
marshaler, isMarshaler := value.(Marshaler)
if isMarshaler && marshaler != nil {
value, err := marshaler.MarshalArgs()
if err != nil {
return "", err
}
return value, nil
}
// If src has a registered MarshalFunc(), use it.
if marshalFunc, exists := marshalFuncs[src.Type()]; exists {
value, err := marshalFunc(src.Addr().Interface())
if err != nil {
return "", err
}
return value, nil
}
stringer, isStringer := value.(fmt.Stringer)
if isStringer && stringer != nil {
return stringer.String(), nil
}
return "", &ValueIsNotMarshalableError{Interface: src.Interface()}
}
// marshalKeyValue transforms a list of nested keys and the corresponding value
// into a string representation of that key-value pair
// such as "key.sub_key=value"
func marshalKeyValue(keys []string, value interface{}) string {
key := strings.Join(keys, ".")
valueStr := fmt.Sprint(value)
if key != "" {
valueStr = key + "=" + valueStr
}
return valueStr
}
func isMarshalableValue(src reflect.Value) bool {
value := getInterfaceFromReflectValue(src)
_, isMarshaler := value.(Marshaler)
_, hasMarshalFunc := marshalFuncs[src.Type()]
_, isStringer := value.(fmt.Stringer)
return isMarshaler || hasMarshalFunc || isStringer
}
func isDefaultValue(value reflect.Value) (bool, error) {
switch value.Kind() {
case reflect.Int, reflect.Int16, reflect.Int32, reflect.Int64:
return value.Int() == 0, nil
case reflect.Uint, reflect.Uint16, reflect.Uint32, reflect.Uint64:
return value.Uint() == 0, nil
case reflect.Float32, reflect.Float64:
return value.Float() == 0, nil
case reflect.Bool:
return !value.Bool(), nil
case reflect.String:
return value.String() == "", nil
default:
return false, &NotMarshalableTypeError{Src: value.Interface()}
}
}
func isInterfaceNil(data interface{}) bool {
if data == nil {
return true
}
value := reflect.ValueOf(data)
switch value.Kind() {
case reflect.Ptr, reflect.Slice, reflect.Map:
return value.IsNil()
default:
return false
}
}