-
Notifications
You must be signed in to change notification settings - Fork 0
/
tagparser.go
99 lines (81 loc) · 1.88 KB
/
tagparser.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
package tagparser
import (
"context"
"errors"
"go/ast"
"go/token"
"reflect"
"strings"
"edholm.dev/go-logging"
)
type AvailableConfig struct {
Name string
Package string
Options []ConfigOption
}
func Analyze(ctx context.Context, files []*ast.File) []AvailableConfig {
availConfigs := make([]AvailableConfig, 0, len(files))
for _, file := range files {
ast.Inspect(file, func(node ast.Node) bool {
if gendecl, ok := node.(*ast.GenDecl); ok {
if gendecl.Tok != token.TYPE {
return true
}
// TODO: check for multiple
if len(gendecl.Specs) != 1 {
return true
}
typespec, ok := gendecl.Specs[0].(*ast.TypeSpec)
if !ok {
return true
}
strukt, ok := typespec.Type.(*ast.StructType)
if !ok {
return true
}
if !hasTags(strukt) {
return true
}
options := extractConfigOptions(ctx, strukt)
if len(options) > 0 {
availConfigs = append(availConfigs, AvailableConfig{
Name: typespec.Name.Name,
Package: file.Name.Name,
Options: options,
})
}
}
return true
})
}
return availConfigs
}
func hasTags(strukt *ast.StructType) bool {
for _, field := range strukt.Fields.List {
if field.Tag != nil {
return true
}
}
return false
}
func extractConfigOptions(ctx context.Context, strukt *ast.StructType) []ConfigOption {
logger := logging.FromContext(ctx)
options := make([]ConfigOption, 0, len(strukt.Fields.List))
for _, field := range strukt.Fields.List {
if field.Tag == nil {
continue
}
rawTag := strings.ReplaceAll(field.Tag.Value, "`", "")
tag := reflect.StructTag(rawTag)
option, err := parseConfigOption(tag)
if err != nil && errors.Is(err, errKeyNotFound) {
continue
}
if err != nil {
logger.Warnw("failed to parse struct tag into ConfigOption", "err", err)
continue
}
options = append(options, option)
}
return options
}