-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtype_walker.go
71 lines (59 loc) · 1.59 KB
/
type_walker.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
package proteus
import (
"reflect"
"strings"
"github.com/simplesurance/proteus/types"
)
// flatWalk visits all fields of a struct, including embedded values,
// collect information about found fields and returns it.
func flatWalk(setName, setPath string, val reflect.Value) (map[string]fieldAndValue, error) {
foundFields := map[string]fieldAndValue{}
if val.Type().Kind() != reflect.Struct {
return nil, types.ErrViolations([]types.Violation{
{
SetName: setName,
Message: "only structs can be paramsets",
},
})
}
var violations types.ErrViolations
// recursive function to walk on fields, including the ones on embedded
// structs
var walker func(reflect.Value, string)
walker = func(val reflect.Value, path string) {
for i := 0; i < val.NumField(); i++ {
field := val.Type().Field(i)
fieldValue := val.Field(i)
path := strings.TrimPrefix(path+"/"+field.Name, "/")
if field.Type.Kind() == reflect.Struct && field.Anonymous {
walker(fieldValue, path)
continue
}
// duplicated fields are invalid
normalizedName := strings.ToLower(field.Name)
if _, ok := foundFields[normalizedName]; ok {
violations = append(violations, types.Violation{
SetName: setName,
Path: path,
Message: "Duplicated field",
})
continue
}
foundFields[normalizedName] = fieldAndValue{
field: field,
value: fieldValue,
Path: path,
}
}
}
walker(val, setPath)
if len(violations) > 0 {
return nil, violations
}
return foundFields, nil
}
type fieldAndValue struct {
field reflect.StructField
value reflect.Value
Path string
}