-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
96 lines (78 loc) · 1.96 KB
/
main.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
package main
import (
"bytes"
_ "embed"
"flag"
"fmt"
"html/template"
"strings"
"google.golang.org/protobuf/compiler/protogen"
)
//go:embed handler.kafka.tmpl
var handlerKafkaTmpl string
type gen struct {
ModelNamePrivate string
ModelName string
PackageName string
PathFile string
Version string
}
const (
defaultSuffix = "Export"
version = "v1.1.3"
)
func main() {
versionFlag := flag.Bool("version", false, "print version and exit")
flag.Parse()
if *versionFlag {
fmt.Println(version)
return
}
var flags flag.FlagSet
suffix := flags.String("suffix", defaultSuffix, "")
protoc := protogen.Options{
ParamFunc: flags.Set,
}
protoc.Run(func(plugin *protogen.Plugin) error {
if *suffix == "" {
*suffix = defaultSuffix
}
for _, file := range plugin.Files {
for _, message := range file.Proto.GetMessageType() {
if strings.HasSuffix(message.GetName(), *suffix) {
tmpl, err := parseTemplates(&gen{
ModelNamePrivate: fmt.Sprintf("%s%s", strings.ToLower(message.GetName()[:1]), message.GetName()[1:]),
ModelName: message.GetName(),
PackageName: string(file.GoPackageName),
PathFile: file.Desc.Path(),
Version: version,
})
if err != nil {
plugin.Error(err)
continue
}
msgName := strings.ToLower(strings.Replace(message.GetName(), *suffix, "", 2))
filename := fmt.Sprintf("%s_%s.kafka.go", file.GeneratedFilenamePrefix, msgName)
genFile := plugin.NewGeneratedFile(filename, file.GoImportPath)
if _, err = genFile.Write([]byte(tmpl)); err != nil {
plugin.Error(err)
continue
}
}
}
}
return nil
})
}
func parseTemplates(tmplData interface{}) (str string, err error) {
tmpl, err := template.New("").Parse(handlerKafkaTmpl)
if err != nil {
return
}
var content bytes.Buffer
err = tmpl.Execute(&content, tmplData)
if err != nil {
return
}
return content.String(), nil
}