-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugin.go
114 lines (96 loc) · 2.66 KB
/
plugin.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
package main
import (
"fmt"
"strings"
"github.com/ryanreadbooks/protoc-gen-verifier/verifier"
"github.com/sirupsen/logrus"
"google.golang.org/protobuf/compiler/protogen"
)
const (
GeneratedFileExt = ".pb.verify.go"
)
func makeStatement(anno string, gf *protogen.GeneratedFile, field *protogen.Field) {
lines := strings.Split(strings.TrimSpace(anno), "\n")
// 从下往上找找到合适 只要有一行合适的就结束
for i := len(lines) - 1; i >= 0; i-- {
fieldName := fmt.Sprintf("x.Get%s()", field.GoName)
tag := verifier.NewTag(lines[i])
if field.Message != nil {
logrus.Debugf("field = %v, %T", field.Message.Desc, field.Message.Desc)
}
defalutVal := DefaultValueOfKind(field)
if defalutVal == nil {
if continueParsing() {
continue
}
panic("unsupported kind in proto file")
}
if _, ok := defalutVal.(verifier.Skipper); ok {
continue
}
err := tag.Parse(fieldName, defalutVal, func(statement string, deps []string) {
logrus.Debugf("statement=%s", statement)
gf.P(statement)
gf.P()
addFileImports(gf, deps)
})
// 解析当前tag出错
if err != nil {
if continueParsing() {
continue
} else {
panic(err)
}
}
break
}
}
func generateVerifyMethod(gf *protogen.GeneratedFile, msg *protogen.Message) {
// 生成验证方法
gf.P("func (x *", msg.GoIdent, ") Verify() error {")
gf.P()
// 处理每一个字段的注释 生成对应的校验代码
for _, field := range msg.Fields {
// 只有LeadingComment才会被识别
anno := field.Comments.Leading.String()
if anno != "" {
makeStatement(anno, gf, field)
}
}
gf.P("return nil")
gf.P("}")
gf.P()
}
// handleMessage处理每个message定义
func handleMessage(gf *protogen.GeneratedFile, msg *protogen.Message) {
// 生成Verify方法
generateVerifyMethod(gf, msg)
// message中嵌套定义的同样处理
for _, nested := range msg.Messages {
if !nested.Desc.IsMapEntry() {
handleMessage(gf, nested)
}
}
}
func addFileImports(f *protogen.GeneratedFile, deps []string) {
for _, pkg := range deps {
f.QualifiedGoIdent(protogen.GoIdent{
GoImportPath: protogen.GoImportPath(pkg),
})
}
}
// handleFile处理每个proto文件
func handleFile(p *protogen.Plugin, file *protogen.File) {
// 每个proto文件都生成一个输出
filename := file.GeneratedFilenamePrefix + GeneratedFileExt
f := p.NewGeneratedFile(filename, file.GoImportPath)
f.P("// Code generated by protoc-gen-verifier. DO NOT EDIT.")
f.P(fmt.Sprintf("// source: %s", *file.Proto.Name))
f.P()
f.P("package ", file.GoPackageName)
f.P()
// 处理文件中的每一个message定义
for _, message := range file.Messages {
handleMessage(f, message)
}
}