-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtag.go
105 lines (88 loc) · 2.03 KB
/
tag.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
package gofacto
import (
"reflect"
"strings"
"github.com/eyo-chen/gofacto/internal/utils"
)
// tag represents the metadata parsed from the custom tag
type tag struct {
fieldName string
structName string
tableName string
foreignField string
omit bool
}
// extractTag extracts the tag metadata from the struct type
func extractTag(dataType reflect.Type) ([]string, error) {
var ignoreFields []string
err := processStructFields(dataType, func(t tag, hasTag bool) error {
if !hasTag {
return nil
}
if t.omit {
ignoreFields = append(ignoreFields, t.fieldName)
}
return nil
})
if err != nil {
return nil, err
}
return ignoreFields, nil
}
// processStructFields applies a given function to each field of a struct type
func processStructFields(typ reflect.Type, fn func(tag tag, hasTag bool) error) error {
if typ.Kind() == reflect.Ptr {
typ = typ.Elem()
}
numField := typ.NumField()
for i := 0; i < numField; i++ {
field := typ.Field(i)
t, hasTag, err := parseTag(field)
if err != nil {
return err
}
if err := fn(t, hasTag); err != nil {
return err
}
}
return nil
}
// parseTag parses the tag string into a tag struct
func parseTag(field reflect.StructField) (tag, bool, error) {
tagStr := field.Tag.Get(packageName)
if tagStr == "" {
return tag{}, false, nil
}
parts := strings.Split(tagStr, ";")
if len(parts) == 0 {
return tag{}, false, errTagFormat
}
t := tag{fieldName: field.Name}
for _, part := range parts {
if part == "omit" {
t.omit = true
continue
}
subParts := strings.Split(part, ",")
if subParts[0] != "foreignKey" {
return tag{}, false, errTagFormat
}
for _, subPart := range subParts[1:] {
kv := strings.SplitN(subPart, ":", 2)
switch kv[0] {
case "struct":
t.structName = kv[1]
case "table":
t.tableName = kv[1]
case "field":
t.foreignField = kv[1]
default:
return tag{}, false, errTagFormat
}
}
}
if t.tableName == "" {
t.tableName = utils.CamelToSnake(t.structName) + "s"
}
return t, true, nil
}