podman
289 строк · 8.3 Кб
1// Copyright 2013-2022 Frank Schroeder. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package properties
6
7import (
8"fmt"
9"reflect"
10"strconv"
11"strings"
12"time"
13)
14
15// Decode assigns property values to exported fields of a struct.
16//
17// Decode traverses v recursively and returns an error if a value cannot be
18// converted to the field type or a required value is missing for a field.
19//
20// The following type dependent decodings are used:
21//
22// String, boolean, numeric fields have the value of the property key assigned.
23// The property key name is the name of the field. A different key and a default
24// value can be set in the field's tag. Fields without default value are
25// required. If the value cannot be converted to the field type an error is
26// returned.
27//
28// time.Duration fields have the result of time.ParseDuration() assigned.
29//
30// time.Time fields have the vaule of time.Parse() assigned. The default layout
31// is time.RFC3339 but can be set in the field's tag.
32//
33// Arrays and slices of string, boolean, numeric, time.Duration and time.Time
34// fields have the value interpreted as a comma separated list of values. The
35// individual values are trimmed of whitespace and empty values are ignored. A
36// default value can be provided as a semicolon separated list in the field's
37// tag.
38//
39// Struct fields are decoded recursively using the field name plus "." as
40// prefix. The prefix (without dot) can be overridden in the field's tag.
41// Default values are not supported in the field's tag. Specify them on the
42// fields of the inner struct instead.
43//
44// Map fields must have a key of type string and are decoded recursively by
45// using the field's name plus ".' as prefix and the next element of the key
46// name as map key. The prefix (without dot) can be overridden in the field's
47// tag. Default values are not supported.
48//
49// Examples:
50//
51// // Field is ignored.
52// Field int `properties:"-"`
53//
54// // Field is assigned value of 'Field'.
55// Field int
56//
57// // Field is assigned value of 'myName'.
58// Field int `properties:"myName"`
59//
60// // Field is assigned value of key 'myName' and has a default
61// // value 15 if the key does not exist.
62// Field int `properties:"myName,default=15"`
63//
64// // Field is assigned value of key 'Field' and has a default
65// // value 15 if the key does not exist.
66// Field int `properties:",default=15"`
67//
68// // Field is assigned value of key 'date' and the date
69// // is in format 2006-01-02
70// Field time.Time `properties:"date,layout=2006-01-02"`
71//
72// // Field is assigned the non-empty and whitespace trimmed
73// // values of key 'Field' split by commas.
74// Field []string
75//
76// // Field is assigned the non-empty and whitespace trimmed
77// // values of key 'Field' split by commas and has a default
78// // value ["a", "b", "c"] if the key does not exist.
79// Field []string `properties:",default=a;b;c"`
80//
81// // Field is decoded recursively with "Field." as key prefix.
82// Field SomeStruct
83//
84// // Field is decoded recursively with "myName." as key prefix.
85// Field SomeStruct `properties:"myName"`
86//
87// // Field is decoded recursively with "Field." as key prefix
88// // and the next dotted element of the key as map key.
89// Field map[string]string
90//
91// // Field is decoded recursively with "myName." as key prefix
92// // and the next dotted element of the key as map key.
93// Field map[string]string `properties:"myName"`
94func (p *Properties) Decode(x interface{}) error {
95t, v := reflect.TypeOf(x), reflect.ValueOf(x)
96if t.Kind() != reflect.Ptr || v.Elem().Type().Kind() != reflect.Struct {
97return fmt.Errorf("not a pointer to struct: %s", t)
98}
99if err := dec(p, "", nil, nil, v); err != nil {
100return err
101}
102return nil
103}
104
105func dec(p *Properties, key string, def *string, opts map[string]string, v reflect.Value) error {
106t := v.Type()
107
108// value returns the property value for key or the default if provided.
109value := func() (string, error) {
110if val, ok := p.Get(key); ok {
111return val, nil
112}
113if def != nil {
114return *def, nil
115}
116return "", fmt.Errorf("missing required key %s", key)
117}
118
119// conv converts a string to a value of the given type.
120conv := func(s string, t reflect.Type) (val reflect.Value, err error) {
121var v interface{}
122
123switch {
124case isDuration(t):
125v, err = time.ParseDuration(s)
126
127case isTime(t):
128layout := opts["layout"]
129if layout == "" {
130layout = time.RFC3339
131}
132v, err = time.Parse(layout, s)
133
134case isBool(t):
135v, err = boolVal(s), nil
136
137case isString(t):
138v, err = s, nil
139
140case isFloat(t):
141v, err = strconv.ParseFloat(s, 64)
142
143case isInt(t):
144v, err = strconv.ParseInt(s, 10, 64)
145
146case isUint(t):
147v, err = strconv.ParseUint(s, 10, 64)
148
149default:
150return reflect.Zero(t), fmt.Errorf("unsupported type %s", t)
151}
152if err != nil {
153return reflect.Zero(t), err
154}
155return reflect.ValueOf(v).Convert(t), nil
156}
157
158// keydef returns the property key and the default value based on the
159// name of the struct field and the options in the tag.
160keydef := func(f reflect.StructField) (string, *string, map[string]string) {
161_key, _opts := parseTag(f.Tag.Get("properties"))
162
163var _def *string
164if d, ok := _opts["default"]; ok {
165_def = &d
166}
167if _key != "" {
168return _key, _def, _opts
169}
170return f.Name, _def, _opts
171}
172
173switch {
174case isDuration(t) || isTime(t) || isBool(t) || isString(t) || isFloat(t) || isInt(t) || isUint(t):
175s, err := value()
176if err != nil {
177return err
178}
179val, err := conv(s, t)
180if err != nil {
181return err
182}
183v.Set(val)
184
185case isPtr(t):
186return dec(p, key, def, opts, v.Elem())
187
188case isStruct(t):
189for i := 0; i < v.NumField(); i++ {
190fv := v.Field(i)
191fk, def, opts := keydef(t.Field(i))
192if !fv.CanSet() {
193return fmt.Errorf("cannot set %s", t.Field(i).Name)
194}
195if fk == "-" {
196continue
197}
198if key != "" {
199fk = key + "." + fk
200}
201if err := dec(p, fk, def, opts, fv); err != nil {
202return err
203}
204}
205return nil
206
207case isArray(t):
208val, err := value()
209if err != nil {
210return err
211}
212vals := split(val, ";")
213a := reflect.MakeSlice(t, 0, len(vals))
214for _, s := range vals {
215val, err := conv(s, t.Elem())
216if err != nil {
217return err
218}
219a = reflect.Append(a, val)
220}
221v.Set(a)
222
223case isMap(t):
224valT := t.Elem()
225m := reflect.MakeMap(t)
226for postfix := range p.FilterStripPrefix(key + ".").m {
227pp := strings.SplitN(postfix, ".", 2)
228mk, mv := pp[0], reflect.New(valT)
229if err := dec(p, key+"."+mk, nil, nil, mv); err != nil {
230return err
231}
232m.SetMapIndex(reflect.ValueOf(mk), mv.Elem())
233}
234v.Set(m)
235
236default:
237return fmt.Errorf("unsupported type %s", t)
238}
239return nil
240}
241
242// split splits a string on sep, trims whitespace of elements
243// and omits empty elements
244func split(s string, sep string) []string {
245var a []string
246for _, v := range strings.Split(s, sep) {
247if v = strings.TrimSpace(v); v != "" {
248a = append(a, v)
249}
250}
251return a
252}
253
254// parseTag parses a "key,k=v,k=v,..."
255func parseTag(tag string) (key string, opts map[string]string) {
256opts = map[string]string{}
257for i, s := range strings.Split(tag, ",") {
258if i == 0 {
259key = s
260continue
261}
262
263pp := strings.SplitN(s, "=", 2)
264if len(pp) == 1 {
265opts[pp[0]] = ""
266} else {
267opts[pp[0]] = pp[1]
268}
269}
270return key, opts
271}
272
273func isArray(t reflect.Type) bool { return t.Kind() == reflect.Array || t.Kind() == reflect.Slice }
274func isBool(t reflect.Type) bool { return t.Kind() == reflect.Bool }
275func isDuration(t reflect.Type) bool { return t == reflect.TypeOf(time.Second) }
276func isMap(t reflect.Type) bool { return t.Kind() == reflect.Map }
277func isPtr(t reflect.Type) bool { return t.Kind() == reflect.Ptr }
278func isString(t reflect.Type) bool { return t.Kind() == reflect.String }
279func isStruct(t reflect.Type) bool { return t.Kind() == reflect.Struct }
280func isTime(t reflect.Type) bool { return t == reflect.TypeOf(time.Time{}) }
281func isFloat(t reflect.Type) bool {
282return t.Kind() == reflect.Float32 || t.Kind() == reflect.Float64
283}
284func isInt(t reflect.Type) bool {
285return t.Kind() == reflect.Int || t.Kind() == reflect.Int8 || t.Kind() == reflect.Int16 || t.Kind() == reflect.Int32 || t.Kind() == reflect.Int64
286}
287func isUint(t reflect.Type) bool {
288return t.Kind() == reflect.Uint || t.Kind() == reflect.Uint8 || t.Kind() == reflect.Uint16 || t.Kind() == reflect.Uint32 || t.Kind() == reflect.Uint64
289}
290