/
parsetag.go
198 lines (183 loc) · 4.56 KB
/
parsetag.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
package reflectutils
import (
"reflect"
"regexp"
"strconv"
"strings"
"github.com/pkg/errors"
)
var aTagRE = regexp.MustCompile(`(\S+):"((?:[^"\\]|\\.)*)"(?:\s+|$)`)
// Tag represents a single element of a struct tag. For example for the
// field S in the struct below, there would be to Tags: one for json and
// one for xml. The value for the json one would be "s,omitempty".
//
// type Foo struct {
// S string `json:"s,omitempty" xml:"s_thing"`
// }
//
type Tag struct {
Tag string
Value string
}
type Tags []Tag
// TagSet is a simple transformation of an array of Tag into an
// indexted structure so that lookup is efficient.
type TagSet struct {
// Tags is a read-only value
Tags Tags
index map[string]int
}
// SplitTag breaks apart a reflect.StructTag into an array of annotated key/value pairs.
// Tags are expected to be in the conventional format. What does "contentional"
// mean? `name:"values,value=value" name2:"value"`. See https://flaviocopes.com/go-tags/
// a light introduction.
func SplitTag(tag reflect.StructTag) Tags {
found := make([]Tag, 0, 5)
s := string(tag)
for len(s) > 0 {
f := aTagRE.FindStringSubmatchIndex(s)
if len(f) != 6 {
break
}
tag := s[f[2]:f[3]]
value := s[f[4]:f[5]]
found = append(found, mkTag(tag, value))
s = s[f[1]:]
}
if len(found) == 0 {
return nil
}
return found
}
func mkTag(tag, value string) Tag {
return Tag{
Tag: tag,
Value: value,
}
}
func (s TagSet) Get(tag string) Tag {
t, _ := s.Lookup(tag)
return t
}
func (s TagSet) Lookup(tag string) (Tag, bool) {
if i, ok := s.index[tag]; ok {
return s.Tags[i], true
}
return mkTag("", ""), false
}
func (t Tags) Set() TagSet {
index := make(map[string]int)
for i, tag := range t {
index[tag.Tag] = i
}
return TagSet{
Tags: t,
index: index,
}
}
// Fill unpacks struct tags into a struct based on tags of the desitnation struct.
//
// type MyTags struct {
// Name string `pt:"0"`
// Flag bool `pt:"flag"`
// Int int `pt:"intValue"`
// }
//
// The above will fill the Name field by grabbing the first element of the tag.
// It will fill Flag by noticing if any of the following are present in the
// comma-separated list of tag elements: "flag", "!flag" (sets to false), "flag=true",
// "flag=false", "flag=0", "flag=1", "flag=t", "flag=f", "flag=T", "flag=F".
// It will set Int by looking for "intValue=280" (set to 280).
//
// When filling an array value, the default character to split upon is
// comma, but other values can be set with "split=X" to split on X.
// Special values of X are "quote", "space", and "none"
func (tag Tag) Fill(model interface{}, opts ...FillOptArg) error {
opt := fillOpt{
tag: "pt",
}
for _, f := range opts {
f(&opt)
}
v := reflect.ValueOf(model)
if !v.IsValid() || v.IsNil() || v.Type().Kind() != reflect.Ptr || v.Type().Elem().Kind() != reflect.Struct {
return errors.Errorf("Fill target must be a pointer to a struct, not %T", model)
}
kv := make(map[string]string)
elements := strings.Split(tag.Value, ",")
for _, element := range elements {
if eq := strings.IndexByte(element, '='); eq != -1 {
kv[element[0:eq]] = element[eq+1:]
} else {
if strings.HasPrefix(element, "!") {
kv[element[1:]] = "f"
} else {
kv[element] = "t"
}
}
}
var count int
var walkErr error
WalkStructElements(v.Type(), func(f reflect.StructField) bool {
tag := f.Tag.Get(opt.tag)
if tag == "-" {
return false
}
count++
parts := strings.Split(tag, ",")
var value string
if len(parts) > 0 && parts[0] != "" {
i, err := strconv.Atoi(parts[0])
if err == nil {
// positional!
if i >= len(elements) {
return true
}
value = elements[i]
} else {
value = kv[parts[0]]
}
} else {
value = kv[f.Name]
}
if value == "" {
return true
}
var sso []StringSetterArg
if len(parts) > 1 {
for _, part := range parts[1:] {
if strings.HasPrefix(part, "split=") {
splitOn := part[len("split="):]
switch splitOn {
case "quote":
splitOn = `"`
case "space":
splitOn = " "
}
sso = append(sso, WithSplitOn(splitOn))
}
}
}
set, err := MakeStringSetter(f.Type, sso...)
if err != nil {
walkErr = errors.Wrapf(err, "Cannot set %s", f.Type)
return true
}
err = set(v.Elem().FieldByIndex(f.Index), value)
if err != nil {
walkErr = errors.Wrap(err, f.Name)
}
return true
})
return walkErr
}
type FillOptArg func(*fillOpt)
type fillOpt struct {
tag string
}
// WithTag overrides the tag used by Tag.Fill. The default is "pt".
func WithTag(tag string) FillOptArg {
return func(o *fillOpt) {
o.tag = tag
}
}