forked from magiconair/properties
-
Notifications
You must be signed in to change notification settings - Fork 0
/
decode.go
289 lines (263 loc) · 8.28 KB
/
decode.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
// Copyright 2013-2022 Frank Schroeder. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package properties
import (
"fmt"
"reflect"
"strconv"
"strings"
"time"
)
// Decode assigns property values to exported fields of a struct.
//
// Decode traverses v recursively and returns an error if a value cannot be
// converted to the field type or a required value is missing for a field.
//
// The following type dependent decodings are used:
//
// String, boolean, numeric fields have the value of the property key assigned.
// The property key name is the name of the field. A different key and a default
// value can be set in the field's tag. Fields without default value are
// required. If the value cannot be converted to the field type an error is
// returned.
//
// time.Duration fields have the result of time.ParseDuration() assigned.
//
// time.Time fields have the vaule of time.Parse() assigned. The default layout
// is time.RFC3339 but can be set in the field's tag.
//
// Arrays and slices of string, boolean, numeric, time.Duration and time.Time
// fields have the value interpreted as a comma separated list of values. The
// individual values are trimmed of whitespace and empty values are ignored. A
// default value can be provided as a semicolon separated list in the field's
// tag.
//
// Struct fields are decoded recursively using the field name plus "." as
// prefix. The prefix (without dot) can be overridden in the field's tag.
// Default values are not supported in the field's tag. Specify them on the
// fields of the inner struct instead.
//
// Map fields must have a key of type string and are decoded recursively by
// using the field's name plus ".' as prefix and the next element of the key
// name as map key. The prefix (without dot) can be overridden in the field's
// tag. Default values are not supported.
//
// Examples:
//
// // Field is ignored.
// Field int `properties:"-"`
//
// // Field is assigned value of 'Field'.
// Field int
//
// // Field is assigned value of 'myName'.
// Field int `properties:"myName"`
//
// // Field is assigned value of key 'myName' and has a default
// // value 15 if the key does not exist.
// Field int `properties:"myName,default=15"`
//
// // Field is assigned value of key 'Field' and has a default
// // value 15 if the key does not exist.
// Field int `properties:",default=15"`
//
// // Field is assigned value of key 'date' and the date
// // is in format 2006-01-02
// Field time.Time `properties:"date,layout=2006-01-02"`
//
// // Field is assigned the non-empty and whitespace trimmed
// // values of key 'Field' split by commas.
// Field []string
//
// // Field is assigned the non-empty and whitespace trimmed
// // values of key 'Field' split by commas and has a default
// // value ["a", "b", "c"] if the key does not exist.
// Field []string `properties:",default=a;b;c"`
//
// // Field is decoded recursively with "Field." as key prefix.
// Field SomeStruct
//
// // Field is decoded recursively with "myName." as key prefix.
// Field SomeStruct `properties:"myName"`
//
// // Field is decoded recursively with "Field." as key prefix
// // and the next dotted element of the key as map key.
// Field map[string]string
//
// // Field is decoded recursively with "myName." as key prefix
// // and the next dotted element of the key as map key.
// Field map[string]string `properties:"myName"`
func (p *Properties) Decode(x interface{}) error {
t, v := reflect.TypeOf(x), reflect.ValueOf(x)
if t.Kind() != reflect.Ptr || v.Elem().Type().Kind() != reflect.Struct {
return fmt.Errorf("not a pointer to struct: %s", t)
}
if err := dec(p, "", nil, nil, v); err != nil {
return err
}
return nil
}
func dec(p *Properties, key string, def *string, opts map[string]string, v reflect.Value) error {
t := v.Type()
// value returns the property value for key or the default if provided.
value := func() (string, error) {
if val, ok := p.Get(key); ok {
return val, nil
}
if def != nil {
return *def, nil
}
return "", fmt.Errorf("missing required key %s", key)
}
// conv converts a string to a value of the given type.
conv := func(s string, t reflect.Type) (val reflect.Value, err error) {
var v interface{}
switch {
case isDuration(t):
v, err = time.ParseDuration(s)
case isTime(t):
layout := opts["layout"]
if layout == "" {
layout = time.RFC3339
}
v, err = time.Parse(layout, s)
case isBool(t):
v, err = boolVal(s), nil
case isString(t):
v, err = s, nil
case isFloat(t):
v, err = strconv.ParseFloat(s, 64)
case isInt(t):
v, err = strconv.ParseInt(s, 10, 64)
case isUint(t):
v, err = strconv.ParseUint(s, 10, 64)
default:
return reflect.Zero(t), fmt.Errorf("unsupported type %s", t)
}
if err != nil {
return reflect.Zero(t), err
}
return reflect.ValueOf(v).Convert(t), nil
}
// keydef returns the property key and the default value based on the
// name of the struct field and the options in the tag.
keydef := func(f reflect.StructField) (string, *string, map[string]string) {
_key, _opts := parseTag(f.Tag.Get("properties"))
var _def *string
if d, ok := _opts["default"]; ok {
_def = &d
}
if _key != "" {
return _key, _def, _opts
}
return f.Name, _def, _opts
}
switch {
case isDuration(t) || isTime(t) || isBool(t) || isString(t) || isFloat(t) || isInt(t) || isUint(t):
s, err := value()
if err != nil {
return err
}
val, err := conv(s, t)
if err != nil {
return err
}
v.Set(val)
case isPtr(t):
return dec(p, key, def, opts, v.Elem())
case isStruct(t):
for i := 0; i < v.NumField(); i++ {
fv := v.Field(i)
fk, def, opts := keydef(t.Field(i))
if !fv.CanSet() {
return fmt.Errorf("cannot set %s", t.Field(i).Name)
}
if fk == "-" {
continue
}
if key != "" {
fk = key + "." + fk
}
if err := dec(p, fk, def, opts, fv); err != nil {
return err
}
}
return nil
case isArray(t):
val, err := value()
if err != nil {
return err
}
vals := split(val, ";")
a := reflect.MakeSlice(t, 0, len(vals))
for _, s := range vals {
val, err := conv(s, t.Elem())
if err != nil {
return err
}
a = reflect.Append(a, val)
}
v.Set(a)
case isMap(t):
valT := t.Elem()
m := reflect.MakeMap(t)
for postfix := range p.FilterStripPrefix(key + ".").m {
pp := strings.SplitN(postfix, ".", 2)
mk, mv := pp[0], reflect.New(valT)
if err := dec(p, key+"."+mk, nil, nil, mv); err != nil {
return err
}
m.SetMapIndex(reflect.ValueOf(mk), mv.Elem())
}
v.Set(m)
default:
return fmt.Errorf("unsupported type %s", t)
}
return nil
}
// split splits a string on sep, trims whitespace of elements
// and omits empty elements
func split(s string, sep string) []string {
var a []string
for _, v := range strings.Split(s, sep) {
if v = strings.TrimSpace(v); v != "" {
a = append(a, v)
}
}
return a
}
// parseTag parses a "key,k=v,k=v,..."
func parseTag(tag string) (key string, opts map[string]string) {
opts = map[string]string{}
for i, s := range strings.Split(tag, ",") {
if i == 0 {
key = s
continue
}
pp := strings.SplitN(s, "=", 2)
if len(pp) == 1 {
opts[pp[0]] = ""
} else {
opts[pp[0]] = pp[1]
}
}
return key, opts
}
func isArray(t reflect.Type) bool { return t.Kind() == reflect.Array || t.Kind() == reflect.Slice }
func isBool(t reflect.Type) bool { return t.Kind() == reflect.Bool }
func isDuration(t reflect.Type) bool { return t == reflect.TypeOf(time.Second) }
func isMap(t reflect.Type) bool { return t.Kind() == reflect.Map }
func isPtr(t reflect.Type) bool { return t.Kind() == reflect.Ptr }
func isString(t reflect.Type) bool { return t.Kind() == reflect.String }
func isStruct(t reflect.Type) bool { return t.Kind() == reflect.Struct }
func isTime(t reflect.Type) bool { return t == reflect.TypeOf(time.Time{}) }
func isFloat(t reflect.Type) bool {
return t.Kind() == reflect.Float32 || t.Kind() == reflect.Float64
}
func isInt(t reflect.Type) bool {
return t.Kind() == reflect.Int || t.Kind() == reflect.Int8 || t.Kind() == reflect.Int16 || t.Kind() == reflect.Int32 || t.Kind() == reflect.Int64
}
func isUint(t reflect.Type) bool {
return t.Kind() == reflect.Uint || t.Kind() == reflect.Uint8 || t.Kind() == reflect.Uint16 || t.Kind() == reflect.Uint32 || t.Kind() == reflect.Uint64
}