-
Notifications
You must be signed in to change notification settings - Fork 158
/
Copy pathgenerator.go
339 lines (287 loc) · 7.48 KB
/
generator.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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"strings"
"text/template"
"google.golang.org/protobuf/types/pluginpb"
"github.com/golang/protobuf/proto"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/markbates/pkger"
"golang.org/x/tools/imports"
"google.golang.org/protobuf/compiler/protogen"
)
func main() {
// Tip of the hat to Tim Coulson
// https://medium.com/@tim.r.coulson/writing-a-protoc-plugin-with-google-golang-org-protobuf-cd5aa75f5777
// Protoc passes pluginpb.CodeGeneratorRequest in via stdin
// marshalled with Protobuf
input, _ := ioutil.ReadAll(os.Stdin)
var request pluginpb.CodeGeneratorRequest
if err := proto.Unmarshal(input, &request); err != nil {
log.Fatalf("error unmarshalling [%s]: %v", string(input), err)
}
// Initialise our plugin with default options
opts := protogen.Options{}
plugin, err := opts.New(&request)
if err != nil {
log.Fatalf("error initializing plugin: %v", err)
}
plugin.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)
protos := make([]*descriptor.FileDescriptorProto, len(plugin.Files))
for index, file := range plugin.Files {
protos[index] = file.Proto
}
params := make(map[string]string)
for _, param := range strings.Split(request.GetParameter(), ",") {
split := strings.Split(param, "=")
params[split[0]] = split[1]
}
buf := new(bytes.Buffer)
err = generateServer(protos, &Options{
writer: buf,
adminPort: params["admin-port"],
grpcAddr: fmt.Sprintf("%s:%s", params["grpc-address"], params["grpc-port"]),
})
if err != nil {
log.Fatalf("Failed to generate server %v", err)
}
file := plugin.NewGeneratedFile("server.go", ".")
file.Write(buf.Bytes())
// Generate a response from our plugin and marshall as protobuf
out, err := proto.Marshal(plugin.Response())
if err != nil {
log.Fatalf("error marshalling plugin response: %v", err)
}
// Write the response to stdout, to be picked up by protoc
os.Stdout.Write(out)
}
type generatorParam struct {
Services []Service
Dependencies map[string]string
GrpcAddr string
AdminPort string
PbPath string
}
type Service struct {
Name string
Package string
Methods []methodTemplate
}
type methodTemplate struct {
SvcPackage string
Name string
ServiceName string
MethodType string
Input string
Output string
}
const (
methodTypeStandard = "standard"
// server to client stream
methodTypeServerStream = "server-stream"
// client to server stream
methodTypeClientStream = "client-stream"
methodTypeBidirectional = "bidirectional"
)
type Options struct {
writer io.Writer
grpcAddr string
adminPort string
pbPath string
format bool
}
var SERVER_TEMPLATE string
func init() {
f, err := pkger.Open("/server.tmpl")
if err != nil {
log.Fatalf("error opening server.tmpl: %s", err)
}
bytes, err := ioutil.ReadAll(f)
if err != nil {
log.Fatalf("error reading server.tmpl: %s", err)
}
SERVER_TEMPLATE = string(bytes)
}
func generateServer(protos []*descriptor.FileDescriptorProto, opt *Options) error {
services := extractServices(protos)
deps := resolveDependencies(protos)
param := generatorParam{
Services: services,
Dependencies: deps,
GrpcAddr: opt.grpcAddr,
AdminPort: opt.adminPort,
PbPath: opt.pbPath,
}
if opt == nil {
opt = &Options{}
}
if opt.writer == nil {
opt.writer = os.Stdout
}
tmpl := template.New("server.tmpl")
tmpl, err := tmpl.Parse(SERVER_TEMPLATE)
if err != nil {
return fmt.Errorf("template parse %v", err)
}
buf := new(bytes.Buffer)
err = tmpl.Execute(buf, param)
if err != nil {
return fmt.Errorf("template execute %v", err)
}
byt := buf.Bytes()
bytProcessed, err := imports.Process("", byt, nil)
if err != nil {
return fmt.Errorf("formatting: %v \n%s", err, string(byt))
}
_, err = opt.writer.Write(bytProcessed)
return err
}
func resolveDependencies(protos []*descriptor.FileDescriptorProto) map[string]string {
deps := map[string]string{}
for _, proto := range protos {
alias, pkg := getGoPackage(proto)
// fatal if go_package is not present
if pkg == "" {
log.Fatalf("option go_package is required. but %s doesn't have any", proto.GetName())
}
if _, ok := deps[pkg]; ok {
continue
}
deps[pkg] = alias
}
return deps
}
var aliases = map[string]bool{}
var aliasNum = 1
var packages = map[string]string{}
func getGoPackage(proto *descriptor.FileDescriptorProto) (alias string, goPackage string) {
goPackage = proto.GetOptions().GetGoPackage()
if goPackage == "" {
return
}
// support go_package alias declaration
// https://github.com/golang/protobuf/issues/139
if splits := strings.Split(goPackage, ";"); len(splits) > 1 {
goPackage = splits[0]
alias = splits[1]
} else {
// get the alias based on the latest folder
splitSlash := strings.Split(goPackage, "/")
// replace - with _
alias = strings.ReplaceAll(splitSlash[len(splitSlash)-1], "-", "_")
}
// if package already discovered just return
if al, ok := packages[goPackage]; ok {
alias = al
return
}
// Aliases can't be keywords
if isKeyword(alias) {
alias = fmt.Sprintf("%s_pb", alias)
}
// in case of found same alias
// add numbers on it
if ok := aliases[alias]; ok {
alias = fmt.Sprintf("%s%d", alias, aliasNum)
aliasNum++
}
packages[goPackage] = alias
aliases[alias] = true
return
}
// change the structure also translate method type
func extractServices(protos []*descriptor.FileDescriptorProto) []Service {
svcTmp := []Service{}
for _, proto := range protos {
for _, svc := range proto.GetService() {
var s Service
s.Name = svc.GetName()
alias, _ := getGoPackage(proto)
if alias != "" {
s.Package = alias + "."
}
methods := make([]methodTemplate, len(svc.Method))
for j, method := range svc.Method {
tipe := methodTypeStandard
if method.GetServerStreaming() && !method.GetClientStreaming() {
tipe = methodTypeServerStream
} else if !method.GetServerStreaming() && method.GetClientStreaming() {
tipe = methodTypeClientStream
} else if method.GetServerStreaming() && method.GetClientStreaming() {
tipe = methodTypeBidirectional
}
methods[j] = methodTemplate{
Name: strings.Title(*method.Name),
SvcPackage: s.Package,
ServiceName: svc.GetName(),
Input: getMessageType(protos, method.GetInputType()),
Output: getMessageType(protos, method.GetOutputType()),
MethodType: tipe,
}
}
s.Methods = methods
svcTmp = append(svcTmp, s)
}
}
return svcTmp
}
func getMessageType(protos []*descriptor.FileDescriptorProto, tipe string) string {
split := strings.Split(tipe, ".")[1:]
targetPackage := strings.Join(split[:len(split)-1], ".")
targetType := split[len(split)-1]
for _, proto := range protos {
if proto.GetPackage() != targetPackage {
continue
}
for _, msg := range proto.GetMessageType() {
if msg.GetName() == targetType {
alias, _ := getGoPackage(proto)
if alias != "" {
alias += "."
}
return fmt.Sprintf("%s%s", alias, msg.GetName())
}
}
}
return targetType
}
func isKeyword(word string) bool {
keywords := [...]string{
"break",
"case",
"chan",
"const",
"continue",
"default",
"defer",
"else",
"fallthrough",
"for",
"func",
"go",
"goto",
"if",
"import",
"interface",
"map",
"package",
"range",
"return",
"select",
"struct",
"switch",
"type",
"var",
}
for _, keyword := range keywords {
if strings.ToLower(word) == keyword {
return true
}
}
return false
}