-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathregroup.go
265 lines (228 loc) · 7.08 KB
/
regroup.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
package regroup
import (
"fmt"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"golang.org/x/exp/slices"
)
const (
requiredOption = "required"
existsOption = "exists"
)
// ReGroup is the main ReGroup matcher struct
type ReGroup struct {
matcher *regexp.Regexp
}
func quote(s string) string {
if strconv.CanBackquote(s) {
return "`" + s + "`"
}
return strconv.Quote(s)
}
// Compile compiles given expression as regex and return new ReGroup with this expression as matching engine.
// If the expression can't be compiled as regex, a CompileError will be returned
func Compile(expr string) (*ReGroup, error) {
matcher, err := regexp.Compile(expr)
if err != nil {
return nil, &CompileError{err: err}
}
return &ReGroup{matcher: matcher}, nil
}
// MustCompile calls Compile and panics if it returns an error
func MustCompile(expr string) *ReGroup {
reGroup, err := Compile(expr)
if err != nil {
panic(`regroup: Compile(` + quote(expr) + `): ` + err.Error())
}
return reGroup
}
// matchGroupMap converts the match string array into a map of group keys to group values
func (r *ReGroup) matchGroupMap(match []string) map[string]string {
ret := make(map[string]string)
for i, name := range r.matcher.SubexpNames() {
if i != 0 && name != "" {
ret[name] = match[i]
}
}
return ret
}
// groupAndOption returns the requested regroup and its options split by ','
func (r *ReGroup) groupAndOption(fieldType reflect.StructField) (group string, option []string) {
regroupKey := fieldType.Tag.Get("regroup")
if regroupKey == "" {
return "", nil
}
split := strings.Split(regroupKey, ",")
if len(split) == 1 {
return strings.TrimSpace(split[0]), nil
}
var options []string
for _, opt := range split[1:] {
options = append(options, strings.TrimSpace(opt))
}
return strings.TrimSpace(split[0]), options
}
// setField getting a single struct field and matching groups map and set the field value to its matching group value tag
// after parsing it to match the field type
func (r *ReGroup) setField(fieldType reflect.StructField, fieldRef reflect.Value, matchGroup map[string]string) error {
fieldRefType := fieldType.Type
ptr := false
if fieldRefType.Kind() == reflect.Ptr {
ptr = true
fieldRefType = fieldType.Type.Elem()
}
if fieldRefType.Kind() == reflect.Struct {
if ptr {
if fieldRef.IsNil() {
return fmt.Errorf("can't set value to nil pointer in struct field: %s", fieldType.Name)
}
fieldRef = fieldRef.Elem()
}
if fieldRefType.Name() == "Time" && fieldRefType.PkgPath() == "time" {
return r.fillTimeTarget(fieldType, fieldRef, matchGroup)
}
return r.fillTarget(matchGroup, fieldRef)
}
regroupKey, regroupOptions := r.groupAndOption(fieldType)
if regroupKey == "" {
return nil
}
if ptr {
if fieldRef.IsNil() {
return fmt.Errorf("can't set value to nil pointer in field: %s", fieldType.Name)
}
fieldRef = fieldRef.Elem()
}
matchedVal, ok := matchGroup[regroupKey]
if !ok {
return &UnknownGroupError{group: regroupKey}
}
if slices.Contains(regroupOptions, existsOption) {
fieldRef.SetBool(matchedVal != "")
return nil
}
if matchedVal == "" {
if slices.Contains(regroupOptions, requiredOption) {
return &RequiredGroupIsEmpty{groupName: regroupKey, fieldName: fieldType.Name}
}
return nil
}
parsedFunc := getParsingFunc(fieldRefType)
if parsedFunc == nil {
return &TypeNotParsableError{fieldRefType}
}
parsed, err := parsedFunc(matchedVal, fieldRefType)
if err != nil {
return &ParseError{group: regroupKey, err: err}
}
fieldRef.Set(parsed)
return nil
}
func (r *ReGroup) fillTarget(matchGroup map[string]string, targetRef reflect.Value) error {
targetType := targetRef.Type()
for i := 0; i < targetType.NumField(); i++ {
fieldRef := targetRef.Field(i)
if !fieldRef.CanSet() {
continue
}
if err := r.setField(targetType.Field(i), fieldRef, matchGroup); err != nil {
return err
}
}
return nil
}
func (r *ReGroup) fillTimeTarget(fieldType reflect.StructField, fieldRef reflect.Value, matchGroup map[string]string) error {
regroupKey, regroupOptions := r.groupAndOption(fieldType)
if regroupKey == "" {
return nil
}
var pattern string
if len(regroupOptions) == 0 {
pattern = time.RFC3339
} else {
pattern = regroupOptions[0]
}
parsed, err := time.Parse(pattern, matchGroup[regroupKey])
if err != nil {
return err
}
fieldRef.Set(reflect.ValueOf(parsed))
return nil
}
// validateTarget checks that given interface is a pointer of struct
func (r *ReGroup) validateTarget(target interface{}) (reflect.Value, error) {
targetPtr := reflect.ValueOf(target)
if targetPtr.Kind() != reflect.Ptr {
return reflect.Value{}, &NotStructPtrError{}
}
return targetPtr.Elem(), nil
}
// Groups returns a map contains each group name as a key and the group's matched value as value
func (r *ReGroup) Groups(s string) (map[string]string, error) {
match := r.matcher.FindStringSubmatch(s)
if match == nil {
return nil, &NoMatchFoundError{}
}
return r.matchGroupMap(match), nil
}
// MatchToTarget matches a regex expression to string s and parse it into `target` argument.
// If no matches found, a &NoMatchFoundError error will be returned
func (r *ReGroup) MatchToTarget(s string, target interface{}) error {
match := r.matcher.FindStringSubmatch(s)
if match == nil {
return &NoMatchFoundError{}
}
targetRef, err := r.validateTarget(target)
if err != nil {
return err
}
return r.fillTarget(r.matchGroupMap(match), targetRef)
}
// Creating a new pointer to given target type
// Will recurse over all NOT NIL struct pointer and create them too
func (r *ReGroup) newTargetType(originalRef reflect.Value) reflect.Value {
originalType := originalRef.Type()
target := reflect.New(originalRef.Type()).Elem()
for i := 0; i < originalRef.NumField(); i++ {
origFieldRef := originalRef.Field(i)
if originalType.Field(i).Type.Kind() == reflect.Ptr {
if origFieldRef.IsNil() || !target.Field(i).CanSet() {
continue
}
origElem := origFieldRef.Elem()
if origElem.Type().Kind() == reflect.Struct {
// If the type is not nil struct pointer, recurse into it to create all necessary fields inside
target.Field(i).Set(r.newTargetType(origElem).Addr())
} else {
target.Field(i).Set(reflect.New(origElem.Type()))
}
}
}
return target
}
// MatchAllToTarget will find all the regex matches for given string 's',
// and parse them into objects of the same type as `targetType` argument.
// The return type is an array of interfaces, which every element is the same type as `targetType` argument.
// If no matches found, a &NoMatchFoundError error will be returned
func (r *ReGroup) MatchAllToTarget(s string, n int, targetType interface{}) ([]interface{}, error) {
targetRefType, err := r.validateTarget(targetType)
if err != nil {
return nil, err
}
matches := r.matcher.FindAllStringSubmatch(s, n)
if matches == nil {
return nil, &NoMatchFoundError{}
}
ret := make([]interface{}, len(matches))
for i, match := range matches {
target := r.newTargetType(targetRefType)
if err := r.fillTarget(r.matchGroupMap(match), target); err != nil {
return nil, err
}
ret[i] = target.Addr().Interface()
}
return ret, nil
}