-
Notifications
You must be signed in to change notification settings - Fork 465
/
template.go
599 lines (511 loc) · 19.1 KB
/
template.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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
package gendoc
import (
"encoding/json"
"fmt"
"sort"
"strings"
"github.com/golang/protobuf/protoc-gen-go/descriptor"
"github.com/pseudomuto/protoc-gen-doc/extensions"
"github.com/pseudomuto/protokit"
)
// Template is a type for encapsulating all the parsed files, messages, fields, enums, services, extensions, etc. into
// an object that will be supplied to a go template.
type Template struct {
// The files that were parsed
Files []*File `json:"files"`
// Details about the scalar values and their respective types in supported languages.
Scalars []*ScalarValue `json:"scalarValueTypes"`
}
// NewTemplate creates a Template object from a set of descriptors.
func NewTemplate(descs []*protokit.FileDescriptor) *Template {
files := make([]*File, 0, len(descs))
for _, f := range descs {
file := &File{
Name: f.GetName(),
Description: description(f.GetSyntaxComments().String()),
Package: f.GetPackage(),
HasEnums: len(f.Enums) > 0,
HasExtensions: len(f.Extensions) > 0,
HasMessages: len(f.Messages) > 0,
HasServices: len(f.Services) > 0,
Enums: make(orderedEnums, 0, len(f.Enums)),
Extensions: make(orderedExtensions, 0, len(f.Extensions)),
Messages: make(orderedMessages, 0, len(f.Messages)),
Services: make(orderedServices, 0, len(f.Services)),
Options: mergeOptions(extractOptions(f.GetOptions()), extensions.Transform(f.OptionExtensions)),
}
for _, e := range f.Enums {
file.Enums = append(file.Enums, parseEnum(e))
}
for _, e := range f.Extensions {
file.Extensions = append(file.Extensions, parseFileExtension(e))
}
// Recursively add nested types from messages
var addFromMessage func(*protokit.Descriptor)
addFromMessage = func(m *protokit.Descriptor) {
file.Messages = append(file.Messages, parseMessage(m))
for _, e := range m.Enums {
file.Enums = append(file.Enums, parseEnum(e))
}
for _, n := range m.Messages {
addFromMessage(n)
}
}
for _, m := range f.Messages {
addFromMessage(m)
}
for _, s := range f.Services {
file.Services = append(file.Services, parseService(s))
}
sort.Sort(file.Enums)
sort.Sort(file.Extensions)
sort.Sort(file.Messages)
sort.Sort(file.Services)
files = append(files, file)
}
return &Template{Files: files, Scalars: makeScalars()}
}
func makeScalars() []*ScalarValue {
var scalars []*ScalarValue
json.Unmarshal(scalarsJSON, &scalars)
return scalars
}
func mergeOptions(opts ...map[string]interface{}) map[string]interface{} {
out := make(map[string]interface{})
for _, opts := range opts {
for k, v := range opts {
if _, ok := out[k]; ok {
continue
}
out[k] = v
}
}
if len(out) == 0 {
return nil
}
return out
}
// CommonOptions are options common to all descriptor types.
type commonOptions interface {
GetDeprecated() bool
}
func extractOptions(opts commonOptions) map[string]interface{} {
out := make(map[string]interface{})
if opts.GetDeprecated() {
out["deprecated"] = true
}
switch opts := opts.(type) {
case *descriptor.MethodOptions:
if opts != nil && opts.IdempotencyLevel != nil {
out["idempotency_level"] = opts.IdempotencyLevel.String()
}
}
return out
}
// File wraps all the relevant parsed info about a proto file. File objects guarantee that their top-level enums,
// extensions, messages, and services are sorted alphabetically based on their "long name". Other values (enum values,
// fields, service methods) will be in the order that they're defined within their respective proto files.
//
// In the case of proto3 files, HasExtensions will always be false, and Extensions will be empty.
type File struct {
Name string `json:"name"`
Description string `json:"description"`
Package string `json:"package"`
HasEnums bool `json:"hasEnums"`
HasExtensions bool `json:"hasExtensions"`
HasMessages bool `json:"hasMessages"`
HasServices bool `json:"hasServices"`
Enums orderedEnums `json:"enums"`
Extensions orderedExtensions `json:"extensions"`
Messages orderedMessages `json:"messages"`
Services orderedServices `json:"services"`
Options map[string]interface{} `json:"options,omitempty"`
}
// Option returns the named option.
func (f File) Option(name string) interface{} { return f.Options[name] }
// FileExtension contains details about top-level extensions within a proto(2) file.
type FileExtension struct {
Name string `json:"name"`
LongName string `json:"longName"`
FullName string `json:"fullName"`
Description string `json:"description"`
Label string `json:"label"`
Type string `json:"type"`
LongType string `json:"longType"`
FullType string `json:"fullType"`
Number int `json:"number"`
DefaultValue string `json:"defaultValue"`
ContainingType string `json:"containingType"`
ContainingLongType string `json:"containingLongType"`
ContainingFullType string `json:"containingFullType"`
}
// Message contains details about a protobuf message.
//
// In the case of proto3 files, HasExtensions will always be false, and Extensions will be empty.
type Message struct {
Name string `json:"name"`
LongName string `json:"longName"`
FullName string `json:"fullName"`
Description string `json:"description"`
HasExtensions bool `json:"hasExtensions"`
HasFields bool `json:"hasFields"`
HasOneofs bool `json:"hasOneofs"`
Extensions []*MessageExtension `json:"extensions"`
Fields []*MessageField `json:"fields"`
Options map[string]interface{} `json:"options,omitempty"`
}
// Option returns the named option.
func (m Message) Option(name string) interface{} { return m.Options[name] }
// FieldOptions returns all options that are set on the fields in this message.
func (m Message) FieldOptions() []string {
optionSet := make(map[string]struct{})
for _, field := range m.Fields {
for option := range field.Options {
optionSet[option] = struct{}{}
}
}
if len(optionSet) == 0 {
return nil
}
options := make([]string, 0, len(optionSet))
for option := range optionSet {
options = append(options, option)
}
sort.Strings(options)
return options
}
// FieldsWithOption returns all fields that have the given option set.
// If no single value has the option set, this returns nil.
func (m Message) FieldsWithOption(optionName string) []*MessageField {
fields := make([]*MessageField, 0, len(m.Fields))
for _, field := range m.Fields {
if _, ok := field.Options[optionName]; ok {
fields = append(fields, field)
}
}
if len(fields) > 0 {
return fields
}
return nil
}
// MessageField contains details about an individual field within a message.
//
// In the case of proto3 files, DefaultValue will always be empty. Similarly, label will be empty unless the field is
// repeated (in which case it'll be "repeated").
type MessageField struct {
Name string `json:"name"`
Description string `json:"description"`
Label string `json:"label"`
Type string `json:"type"`
LongType string `json:"longType"`
FullType string `json:"fullType"`
IsMap bool `json:"ismap"`
IsOneof bool `json:"isoneof"`
OneofDecl string `json:"oneofdecl"`
DefaultValue string `json:"defaultValue"`
Options map[string]interface{} `json:"options,omitempty"`
}
// Option returns the named option.
func (f MessageField) Option(name string) interface{} { return f.Options[name] }
// MessageExtension contains details about message-scoped extensions in proto(2) files.
type MessageExtension struct {
FileExtension
ScopeType string `json:"scopeType"`
ScopeLongType string `json:"scopeLongType"`
ScopeFullType string `json:"scopeFullType"`
}
// Enum contains details about enumerations. These can be either top level enums, or nested (defined within a message).
type Enum struct {
Name string `json:"name"`
LongName string `json:"longName"`
FullName string `json:"fullName"`
Description string `json:"description"`
Values []*EnumValue `json:"values"`
Options map[string]interface{} `json:"options,omitempty"`
}
// Option returns the named option.
func (e Enum) Option(name string) interface{} { return e.Options[name] }
// ValueOptions returns all options that are set on the values in this enum.
func (e Enum) ValueOptions() []string {
optionSet := make(map[string]struct{})
for _, value := range e.Values {
for option := range value.Options {
optionSet[option] = struct{}{}
}
}
if len(optionSet) == 0 {
return nil
}
options := make([]string, 0, len(optionSet))
for option := range optionSet {
options = append(options, option)
}
sort.Strings(options)
return options
}
// ValuesWithOption returns all values that have the given option set.
// If no single value has the option set, this returns nil.
func (e Enum) ValuesWithOption(optionName string) []*EnumValue {
values := make([]*EnumValue, 0, len(e.Values))
for _, value := range e.Values {
if _, ok := value.Options[optionName]; ok {
values = append(values, value)
}
}
if len(values) > 0 {
return values
}
return nil
}
// EnumValue contains details about an individual value within an enumeration.
type EnumValue struct {
Name string `json:"name"`
Number string `json:"number"`
Description string `json:"description"`
Options map[string]interface{} `json:"options,omitempty"`
}
// Option returns the named option.
func (v EnumValue) Option(name string) interface{} { return v.Options[name] }
// Service contains details about a service definition within a proto file.
type Service struct {
Name string `json:"name"`
LongName string `json:"longName"`
FullName string `json:"fullName"`
Description string `json:"description"`
Methods []*ServiceMethod `json:"methods"`
Options map[string]interface{} `json:"options,omitempty"`
}
// Option returns the named option.
func (s Service) Option(name string) interface{} { return s.Options[name] }
// MethodOptions returns all options that are set on the methods in this service.
func (s Service) MethodOptions() []string {
optionSet := make(map[string]struct{})
for _, method := range s.Methods {
for option := range method.Options {
optionSet[option] = struct{}{}
}
}
if len(optionSet) == 0 {
return nil
}
options := make([]string, 0, len(optionSet))
for option := range optionSet {
options = append(options, option)
}
sort.Strings(options)
return options
}
// MethodsWithOption returns all methods that have the given option set.
// If no single method has the option set, this returns nil.
func (s Service) MethodsWithOption(optionName string) []*ServiceMethod {
methods := make([]*ServiceMethod, 0, len(s.Methods))
for _, method := range s.Methods {
if _, ok := method.Options[optionName]; ok {
methods = append(methods, method)
}
}
if len(methods) > 0 {
return methods
}
return nil
}
// ServiceMethod contains details about an individual method within a service.
type ServiceMethod struct {
Name string `json:"name"`
Description string `json:"description"`
RequestType string `json:"requestType"`
RequestLongType string `json:"requestLongType"`
RequestFullType string `json:"requestFullType"`
RequestStreaming bool `json:"requestStreaming"`
ResponseType string `json:"responseType"`
ResponseLongType string `json:"responseLongType"`
ResponseFullType string `json:"responseFullType"`
ResponseStreaming bool `json:"responseStreaming"`
Options map[string]interface{} `json:"options,omitempty"`
}
// Option returns the named option.
func (m ServiceMethod) Option(name string) interface{} { return m.Options[name] }
// ScalarValue contains information about scalar value types in protobuf. The common use case for this type is to know
// which language specific type maps to the protobuf type.
//
// For example, the protobuf type `int64` maps to `long` in C#, and `Bignum` in Ruby. For the full list, take a look at
// https://developers.google.com/protocol-buffers/docs/proto3#scalar
type ScalarValue struct {
ProtoType string `json:"protoType"`
Notes string `json:"notes"`
CppType string `json:"cppType"`
CSharp string `json:"csType"`
GoType string `json:"goType"`
JavaType string `json:"javaType"`
PhpType string `json:"phpType"`
PythonType string `json:"pythonType"`
RubyType string `json:"rubyType"`
}
func parseEnum(pe *protokit.EnumDescriptor) *Enum {
enum := &Enum{
Name: pe.GetName(),
LongName: pe.GetLongName(),
FullName: pe.GetFullName(),
Description: description(pe.GetComments().String()),
Options: mergeOptions(extractOptions(pe.GetOptions()), extensions.Transform(pe.OptionExtensions)),
}
for _, val := range pe.GetValues() {
enum.Values = append(enum.Values, &EnumValue{
Name: val.GetName(),
Number: fmt.Sprint(val.GetNumber()),
Description: description(val.GetComments().String()),
Options: mergeOptions(extractOptions(val.GetOptions()), extensions.Transform(val.OptionExtensions)),
})
}
return enum
}
func parseFileExtension(pe *protokit.ExtensionDescriptor) *FileExtension {
t, lt, ft := parseType(pe)
return &FileExtension{
Name: pe.GetName(),
LongName: pe.GetLongName(),
FullName: pe.GetFullName(),
Description: description(pe.GetComments().String()),
Label: labelName(pe.GetLabel(), pe.IsProto3(), pe.GetProto3Optional()),
Type: t,
LongType: lt,
FullType: ft,
Number: int(pe.GetNumber()),
DefaultValue: pe.GetDefaultValue(),
ContainingType: baseName(pe.GetExtendee()),
ContainingLongType: strings.TrimPrefix(pe.GetExtendee(), "."+pe.GetPackage()+"."),
ContainingFullType: strings.TrimPrefix(pe.GetExtendee(), "."),
}
}
func parseMessage(pm *protokit.Descriptor) *Message {
msg := &Message{
Name: pm.GetName(),
LongName: pm.GetLongName(),
FullName: pm.GetFullName(),
Description: description(pm.GetComments().String()),
HasExtensions: len(pm.GetExtensions()) > 0,
HasFields: len(pm.GetMessageFields()) > 0,
HasOneofs: len(pm.GetOneofDecl()) > 0,
Extensions: make([]*MessageExtension, 0, len(pm.Extensions)),
Fields: make([]*MessageField, 0, len(pm.Fields)),
Options: mergeOptions(extractOptions(pm.GetOptions()), extensions.Transform(pm.OptionExtensions)),
}
for _, ext := range pm.Extensions {
msg.Extensions = append(msg.Extensions, parseMessageExtension(ext))
}
for _, f := range pm.Fields {
msg.Fields = append(msg.Fields, parseMessageField(f, pm.GetOneofDecl()))
}
return msg
}
func parseMessageExtension(pe *protokit.ExtensionDescriptor) *MessageExtension {
return &MessageExtension{
FileExtension: *parseFileExtension(pe),
ScopeType: pe.GetParent().GetName(),
ScopeLongType: pe.GetParent().GetLongName(),
ScopeFullType: pe.GetParent().GetFullName(),
}
}
func parseMessageField(pf *protokit.FieldDescriptor, oneofDecls []*descriptor.OneofDescriptorProto) *MessageField {
t, lt, ft := parseType(pf)
m := &MessageField{
Name: pf.GetName(),
Description: description(pf.GetComments().String()),
Label: labelName(pf.GetLabel(), pf.IsProto3(), pf.GetProto3Optional()),
Type: t,
LongType: lt,
FullType: ft,
DefaultValue: pf.GetDefaultValue(),
Options: mergeOptions(extractOptions(pf.GetOptions()), extensions.Transform(pf.OptionExtensions)),
IsOneof: pf.OneofIndex != nil,
}
if m.IsOneof {
m.OneofDecl = oneofDecls[pf.GetOneofIndex()].GetName()
}
// Check if this is a map.
// See https://github.com/golang/protobuf/blob/master/protoc-gen-go/descriptor/descriptor.pb.go#L1556
// for more information
if m.Label == "repeated" &&
strings.Contains(m.LongType, ".") &&
strings.HasSuffix(m.Type, "Entry") &&
strings.HasSuffix(m.LongType, "Entry") &&
strings.HasSuffix(m.FullType, "Entry") {
m.IsMap = true
}
return m
}
func parseService(ps *protokit.ServiceDescriptor) *Service {
service := &Service{
Name: ps.GetName(),
LongName: ps.GetLongName(),
FullName: ps.GetFullName(),
Description: description(ps.GetComments().String()),
Options: mergeOptions(extractOptions(ps.GetOptions()), extensions.Transform(ps.OptionExtensions)),
}
for _, sm := range ps.Methods {
service.Methods = append(service.Methods, parseServiceMethod(sm))
}
return service
}
func parseServiceMethod(pm *protokit.MethodDescriptor) *ServiceMethod {
return &ServiceMethod{
Name: pm.GetName(),
Description: description(pm.GetComments().String()),
RequestType: baseName(pm.GetInputType()),
RequestLongType: strings.TrimPrefix(pm.GetInputType(), "."+pm.GetPackage()+"."),
RequestFullType: strings.TrimPrefix(pm.GetInputType(), "."),
RequestStreaming: pm.GetClientStreaming(),
ResponseType: baseName(pm.GetOutputType()),
ResponseLongType: strings.TrimPrefix(pm.GetOutputType(), "."+pm.GetPackage()+"."),
ResponseFullType: strings.TrimPrefix(pm.GetOutputType(), "."),
ResponseStreaming: pm.GetServerStreaming(),
Options: mergeOptions(extractOptions(pm.GetOptions()), extensions.Transform(pm.OptionExtensions)),
}
}
func baseName(name string) string {
parts := strings.Split(name, ".")
return parts[len(parts)-1]
}
func labelName(lbl descriptor.FieldDescriptorProto_Label, proto3 bool, proto3Opt bool) string {
if proto3 && !proto3Opt && lbl != descriptor.FieldDescriptorProto_LABEL_REPEATED {
return ""
}
return strings.ToLower(strings.TrimPrefix(lbl.String(), "LABEL_"))
}
type typeContainer interface {
GetType() descriptor.FieldDescriptorProto_Type
GetTypeName() string
GetPackage() string
}
func parseType(tc typeContainer) (string, string, string) {
name := tc.GetTypeName()
if strings.HasPrefix(name, ".") {
name = strings.TrimPrefix(name, ".")
return baseName(name), strings.TrimPrefix(name, tc.GetPackage()+"."), name
}
name = strings.ToLower(strings.TrimPrefix(tc.GetType().String(), "TYPE_"))
return name, name, name
}
func description(comment string) string {
val := strings.TrimLeft(comment, "*/\n ")
if strings.HasPrefix(val, "@exclude") {
return ""
}
return val
}
type orderedEnums []*Enum
func (oe orderedEnums) Len() int { return len(oe) }
func (oe orderedEnums) Swap(i, j int) { oe[i], oe[j] = oe[j], oe[i] }
func (oe orderedEnums) Less(i, j int) bool { return oe[i].LongName < oe[j].LongName }
type orderedExtensions []*FileExtension
func (oe orderedExtensions) Len() int { return len(oe) }
func (oe orderedExtensions) Swap(i, j int) { oe[i], oe[j] = oe[j], oe[i] }
func (oe orderedExtensions) Less(i, j int) bool { return oe[i].LongName < oe[j].LongName }
type orderedMessages []*Message
func (om orderedMessages) Len() int { return len(om) }
func (om orderedMessages) Swap(i, j int) { om[i], om[j] = om[j], om[i] }
func (om orderedMessages) Less(i, j int) bool { return om[i].LongName < om[j].LongName }
type orderedServices []*Service
func (os orderedServices) Len() int { return len(os) }
func (os orderedServices) Swap(i, j int) { os[i], os[j] = os[j], os[i] }
func (os orderedServices) Less(i, j int) bool { return os[i].LongName < os[j].LongName }