-
Notifications
You must be signed in to change notification settings - Fork 1
/
common.go
54 lines (51 loc) · 1.17 KB
/
common.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
package gotaglint
import (
"bytes"
"go/ast"
"go/printer"
"go/token"
"golang.org/x/tools/go/analysis"
"reflect"
"strconv"
)
// render returns the pretty-print of the given node
func render(fset *token.FileSet, x interface{}) string {
var buf bytes.Buffer
if err := printer.Fprint(&buf, fset, x); err != nil {
panic(err)
}
return buf.String()
}
func runTagChecker(key string, fun func(analyzer *analysis.Pass, field *ast.Field, tag string)) func(pass *analysis.Pass) (interface{}, error) {
return func(pass *analysis.Pass) (interface{}, error) {
for _, file := range pass.Files {
ast.Inspect(file, func(node ast.Node) bool {
st, ok := node.(*ast.StructType)
if !ok {
return true
}
if st.Fields == nil {
return true
}
for _, f := range st.Fields.List {
if f.Tag == nil {
continue
}
tv, err := strconv.Unquote(f.Tag.Value)
if err != nil {
pass.Reportf(f.Tag.Pos(), "invalid tag:%q", render(pass.Fset, f.Tag))
continue
}
tags := reflect.StructTag(tv)
tag, ok := tags.Lookup(key)
if !ok {
continue
}
fun(pass, f, tag)
}
return true
})
}
return nil, nil
}
}