-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathfields.go
120 lines (98 loc) · 2.2 KB
/
fields.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
package kmip
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import (
"reflect"
"strings"
"github.com/pkg/errors"
)
type field struct {
name string
idx []int
tag Tag
typ Type
required bool
sliceof bool
skip bool
dynamic bool
}
type structDesc struct {
tag Tag
fields []field
}
func parseTag(tag string) (name, opt string) {
parts := strings.SplitN(tag, ",", 2)
name = parts[0]
if len(parts) > 1 {
opt = parts[1]
}
return
}
func guessType(ft reflect.Type, f *field) error {
switch ft {
case typeOfInt32:
f.typ = INTEGER
case typeOfInt64:
f.typ = LONG_INTEGER
case typeOfEnum:
f.typ = ENUMERATION
case typeOfBool:
f.typ = BOOLEAN
case typeOfBytes:
f.typ = BYTE_STRING
case typeOfString:
f.typ = TEXT_STRING
case typeOfTime:
f.typ = DATE_TIME
case typeOfDuration:
f.typ = INTERVAL
default:
if ft.Kind() == reflect.Struct {
f.typ = STRUCTURE
} else if ft.Kind() == reflect.Interface {
f.typ = STRUCTURE
f.dynamic = true
} else {
return errors.Errorf("unsupported type %s", ft.String())
}
}
return nil
}
func getStructDesc(tt reflect.Type) (*structDesc, error) {
res := &structDesc{}
for i := 0; i < tt.NumField(); i++ {
ff := tt.Field(i)
name, opt := parseTag(ff.Tag.Get("kmip"))
if ff.Type == typeOfTag {
var ok bool
if res.tag, ok = tagMap[name]; !ok {
return nil, errors.Errorf("unknown tag %v for struct tag", name)
}
continue
}
if name == "" || ff.PkgPath != "" {
continue
}
f := field{
name: ff.Name,
idx: ff.Index,
}
var ok bool
if f.tag, ok = tagMap[name]; !ok {
return nil, errors.Errorf("unknown tag %v for field %v", name, ff.Name)
}
f.required = strings.Contains(opt, "required")
f.skip = strings.Contains(opt, "skip")
ft := ff.Type
if ft.Kind() == reflect.Slice && ft != typeOfBytes {
f.sliceof = true
ft = ft.Elem()
}
if err := guessType(ft, &f); err != nil {
return nil, errors.WithMessagef(err, "error processing field %v", ff.Name)
}
res.fields = append(res.fields, f)
}
return res, nil
}