-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocs.go
More file actions
838 lines (791 loc) · 31.3 KB
/
Copy pathdocs.go
File metadata and controls
838 lines (791 loc) · 31.3 KB
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
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
package main
import (
"fmt"
"slices"
"strings"
"unicode"
"charm.land/bubbles/v2/list"
"charm.land/lipgloss/v2"
"google.golang.org/protobuf/encoding/prototext"
"google.golang.org/protobuf/encoding/protowire"
"google.golang.org/protobuf/reflect/protodesc"
"google.golang.org/protobuf/reflect/protoreflect"
"google.golang.org/protobuf/reflect/protoregistry"
"google.golang.org/protobuf/types/descriptorpb"
"google.golang.org/protobuf/types/dynamicpb"
)
// docsPackage is a list.Item representing all top-level proto entities in a
// single package. The list on the left shows one entry per package; selecting
// it renders the full entity docs in the viewport on the right.
type docsPackage struct {
name string
syntax string
edition string
features string
services []protoreflect.ServiceDescriptor
messages []protoreflect.MessageDescriptor
enums []protoreflect.EnumDescriptor
extensions []protoreflect.ExtensionDescriptor
// resolver resolves message types (including third-party types with no
// generated Go package) that appear inside custom option values, so a
// google.protobuf.Any option value can be expanded to its compact
// "[type.url]{...}" form instead of falling back to raw type_url/value
// bytes. Shared across every docsPackage built from the same registry.
resolver *dynamicpb.Types
}
func (p *docsPackage) FilterValue() string { return p.name }
func (p *docsPackage) Title() string { return p.name }
func (p *docsPackage) Description() string {
var parts []string
if n := len(p.services); n > 0 {
parts = append(parts, fmt.Sprintf("%d service%s", n, plural(n)))
}
if n := len(p.messages); n > 0 {
parts = append(parts, fmt.Sprintf("%d message%s", n, plural(n)))
}
if n := len(p.enums); n > 0 {
parts = append(parts, fmt.Sprintf("%d enum%s", n, plural(n)))
}
if n := len(p.extensions); n > 0 {
parts = append(parts, fmt.Sprintf("%d extension%s", n, plural(n)))
}
return strings.Join(parts, " · ")
}
// editionString returns the edition label as it appears in proto source
// (e.g. "2023" for EDITION_2023).
func editionString(e descriptorpb.Edition) string {
return strings.TrimPrefix(e.String(), "EDITION_")
}
// derivedJSONName computes the default JSON name for a proto field name
// (snake_case -> camelCase), matching the protobuf compiler's algorithm.
// Compilers always populate FieldDescriptorProto.json_name, whether or not
// the .proto source contained an explicit override, so comparing against
// this derivation is the only reliable way to detect a genuine override.
func derivedJSONName(name string) string {
var b strings.Builder
capNext := false
for _, r := range name {
switch {
case r == '_':
capNext = true
case capNext:
b.WriteRune(unicode.ToUpper(r))
capNext = false
default:
b.WriteRune(r)
}
}
return b.String()
}
func plural(n int) string {
if n == 1 {
return ""
}
return "s"
}
// packagesFromDocs groups top-level entities from the own-module files by
// package, sorts packages alphabetically, and sorts entities within each
// package by FQN.
func packagesFromDocs(files *protoregistry.Files, ownPaths map[string]bool) []list.Item {
byPkg := make(map[string]*docsPackage)
resolver := dynamicpb.NewTypes(files)
files.RangeFiles(func(fd protoreflect.FileDescriptor) bool {
if !ownPaths[fd.Path()] {
return true
}
pkg := string(fd.Package())
if _, ok := byPkg[pkg]; !ok {
p := &docsPackage{name: pkg, resolver: resolver}
if fd.Syntax() == protoreflect.Editions {
p.edition = editionString(protodesc.ToFileDescriptorProto(fd).GetEdition())
p.features = fileFeatureOverrides(fd)
} else {
p.syntax = fd.Syntax().String()
}
byPkg[pkg] = p
}
p := byPkg[pkg]
for i := range fd.Services().Len() {
p.services = append(p.services, fd.Services().Get(i))
}
for i := range fd.Messages().Len() {
p.messages = append(p.messages, fd.Messages().Get(i))
}
for i := range fd.Enums().Len() {
p.enums = append(p.enums, fd.Enums().Get(i))
}
for i := range fd.Extensions().Len() {
p.extensions = append(p.extensions, fd.Extensions().Get(i))
}
return true
})
byFQN := func(a, b protoreflect.Descriptor) int {
return strings.Compare(string(a.FullName()), string(b.FullName()))
}
byFQNSvc := func(a, b protoreflect.ServiceDescriptor) int { return byFQN(a, b) }
byFQNMsg := func(a, b protoreflect.MessageDescriptor) int { return byFQN(a, b) }
byFQNEnum := func(a, b protoreflect.EnumDescriptor) int { return byFQN(a, b) }
byFQNExt := func(a, b protoreflect.ExtensionDescriptor) int { return byFQN(a, b) }
pkgs := make([]list.Item, 0, len(byPkg))
for _, p := range byPkg {
slices.SortStableFunc(p.services, byFQNSvc)
slices.SortStableFunc(p.messages, byFQNMsg)
slices.SortStableFunc(p.enums, byFQNEnum)
slices.SortStableFunc(p.extensions, byFQNExt)
pkgs = append(pkgs, p)
}
slices.SortStableFunc(pkgs, func(a, b list.Item) int {
return strings.Compare(a.(*docsPackage).name, b.(*docsPackage).name)
})
return pkgs
}
// renderPackage renders a full documentation page for a package — all its
// services, messages, enums, and extensions — suitable for the viewport.
func renderPackage(p *docsPackage, isDark bool) string {
resolver := p.resolver
lightDark := lipgloss.LightDark(isDark)
nameStyle := lipgloss.NewStyle().Foreground(colorForeground).Bold(true)
ruleStyle := lipgloss.NewStyle().Foreground(lightDark(lipgloss.Color("#cccccc"), lipgloss.Color("#444444")))
dimStyle := lipgloss.NewStyle().Foreground(lightDark(lipgloss.Color("#555555"), lipgloss.Color("#aaaaaa")))
typeStyle := lipgloss.NewStyle().Foreground(lightDark(lipgloss.Color("#0060aa"), lipgloss.Color("#88ccff")))
commentStyle := lipgloss.NewStyle().Foreground(lightDark(lipgloss.Color("#448844"), lipgloss.Color("#88bb88"))).Italic(true)
deprecatedStyle := lipgloss.NewStyle().Foreground(lightDark(lipgloss.Color("#aa4400"), lipgloss.Color("#ff8866")))
var b strings.Builder
rule := func(name string) {
// name may already contain ANSI escapes from an annotate() call, so
// the underline must match its rendered (visible) width, not its
// raw byte length.
b.WriteString("\n" + nameStyle.Render(name) + "\n")
b.WriteString(ruleStyle.Render(strings.Repeat("─", lipgloss.Width(name))) + "\n")
}
writeComment := func(d protoreflect.Descriptor) {
if c := leadingComment(d); c != "" {
for line := range strings.SplitSeq(c, "\n") {
b.WriteString(commentStyle.Render(line) + "\n")
}
}
}
annotate := func(d protoreflect.Descriptor) string {
var s string
if isDeprecated(d) {
s += " " + deprecatedStyle.Render("[deprecated]")
}
if enum, ok := d.(protoreflect.EnumDescriptor); ok && enum.IsClosed() {
s += " " + dimStyle.Render("[closed]")
}
if vis := symbolVisibility(d); vis != "" {
s += " " + dimStyle.Render("["+vis+"]")
}
if feat := descriptorFeatureOverrides(d); feat != "" {
s += " " + dimStyle.Render(feat)
}
if custom := customOptionsAnnotation(d.Options(), resolver); custom != "" {
s += " " + dimStyle.Render(custom)
}
return s
}
switch {
case p.edition != "":
text := fmt.Sprintf("edition = %q;", p.edition)
if p.features != "" {
text += " " + p.features
}
b.WriteString(dimStyle.Render(text) + "\n")
case p.syntax != "":
b.WriteString(dimStyle.Render(fmt.Sprintf("syntax = %q;", p.syntax)) + "\n")
}
for _, svc := range p.services {
rule(string(svc.Name()) + annotate(svc))
writeComment(svc)
b.WriteString("\n")
for i := range svc.Methods().Len() {
m := svc.Methods().Get(i)
b.WriteString(renderMethod(m, resolver, typeStyle, dimStyle, commentStyle))
b.WriteString("\n")
}
}
for _, msg := range p.messages {
rule(string(msg.Name()) + annotate(msg))
writeComment(msg)
b.WriteString("\n")
renderMessageFields(&b, msg, resolver, typeStyle, dimStyle, commentStyle)
b.WriteString("\n")
// Nested enum types, shown as subsections with dotted path.
renderNestedEnums(&b, msg, string(msg.Name()), resolver, dimStyle, commentStyle, nameStyle, ruleStyle, annotate, writeComment)
// Nested extend blocks, declared directly inside this message.
renderNestedExtensions(&b, msg, resolver, typeStyle, dimStyle, commentStyle)
// Nested message types, shown as subsections with dotted path.
renderNestedMessages(&b, msg, string(msg.Name()), resolver, typeStyle, dimStyle, commentStyle, nameStyle, ruleStyle, annotate, writeComment)
}
for _, enum := range p.enums {
rule(string(enum.Name()) + annotate(enum))
writeComment(enum)
b.WriteString("\n")
for i := range enum.Values().Len() {
v := enum.Values().Get(i)
b.WriteString(renderEnumValue(v, enumValueAliasOf(enum, v), resolver, dimStyle, commentStyle))
}
renderEnumReserved(&b, enum, dimStyle)
b.WriteString("\n")
}
for _, ext := range p.extensions {
// No annotate(ext) here: unlike other top-level entities, an
// extension's own body line (rendered by renderField below) already
// carries its full annotation set (deprecated, custom options, ...)
// for this exact same descriptor, so adding it to the header too
// would just duplicate it.
rule(string(ext.Name()))
writeComment(ext)
b.WriteString("\n")
b.WriteString(dimStyle.Render(fmt.Sprintf("extend %s {", ext.ContainingMessage().FullName())) + "\n")
b.WriteString(" " + renderField(ext, resolver, typeStyle, dimStyle, commentStyle))
b.WriteString(dimStyle.Render("}") + "\n\n")
}
return strings.TrimRight(b.String(), "\n")
}
// renderMessageFields renders a message's own fields, oneof blocks, reserved
// ranges/names, and extension ranges — everything about the message except
// its nested types.
func renderMessageFields(b *strings.Builder, msg protoreflect.MessageDescriptor, resolver *dynamicpb.Types, typeStyle, dimStyle, commentStyle lipgloss.Style) {
// Non-oneof fields first. proto3 `optional` fields compile to a hidden
// "synthetic" oneof containing just that field -- treat those as plain
// fields rather than surfacing the synthetic oneof as a visible block.
for i := range msg.Fields().Len() {
f := msg.Fields().Get(i)
if oneof := f.ContainingOneof(); oneof == nil || oneof.IsSynthetic() {
b.WriteString(renderField(f, resolver, typeStyle, dimStyle, commentStyle))
}
}
// Oneof blocks.
for i := range msg.Oneofs().Len() {
oneof := msg.Oneofs().Get(i)
if oneof.IsSynthetic() {
continue
}
if c := leadingComment(oneof); c != "" {
for l := range strings.SplitSeq(c, "\n") {
b.WriteString(commentStyle.Render(l) + "\n")
}
}
header := fmt.Sprintf("oneof %s {", oneof.Name())
if custom := customOptionsAnnotation(oneof.Options(), resolver); custom != "" {
header += " " + custom
}
b.WriteString(dimStyle.Render(header) + "\n")
for j := range oneof.Fields().Len() {
b.WriteString(" " + renderField(oneof.Fields().Get(j), resolver, typeStyle, dimStyle, commentStyle))
}
b.WriteString(dimStyle.Render("}") + "\n")
}
renderRanges(b, "reserved", msg.ReservedRanges(), dimStyle)
for i := range msg.ReservedNames().Len() {
b.WriteString(dimStyle.Render(fmt.Sprintf("reserved %q;", msg.ReservedNames().Get(i))) + "\n")
}
// Extension ranges — field numbers reserved for third-party extensions.
// Rendered separately from renderRanges since each range can carry its
// own custom options (e.g. a declaration of who owns the range).
for i := range msg.ExtensionRanges().Len() {
r := msg.ExtensionRanges().Get(i)
lo, hi := int(r[0]), int(r[1])-1
var text string
switch {
case protowire.Number(hi) == protowire.MaxValidNumber:
text = fmt.Sprintf("extensions %d to max;", lo)
case lo == hi:
text = fmt.Sprintf("extensions %d;", lo)
default:
text = fmt.Sprintf("extensions %d to %d;", lo, hi)
}
if custom := customOptionsAnnotation(msg.ExtensionRangeOptions(i), resolver); custom != "" {
text += " " + custom
}
b.WriteString(dimStyle.Render(text) + "\n")
}
}
// renderRanges renders field-number ranges, used for both "reserved" and
// "extensions" declarations, collapsing to "N;", "N to M;", or "N to max;".
func renderRanges(b *strings.Builder, keyword string, ranges protoreflect.FieldRanges, dimStyle lipgloss.Style) {
for i := range ranges.Len() {
r := ranges.Get(i)
lo, hi := int(r[0]), int(r[1])-1
switch {
case protowire.Number(hi) == protowire.MaxValidNumber:
b.WriteString(dimStyle.Render(fmt.Sprintf("%s %d to max;", keyword, lo)) + "\n")
case lo == hi:
b.WriteString(dimStyle.Render(fmt.Sprintf("%s %d;", keyword, lo)) + "\n")
default:
b.WriteString(dimStyle.Render(fmt.Sprintf("%s %d to %d;", keyword, lo, hi)) + "\n")
}
}
}
// renderEnumReserved renders an enum's reserved ranges and names.
func renderEnumReserved(b *strings.Builder, enum protoreflect.EnumDescriptor, dimStyle lipgloss.Style) {
renderEnumRanges(b, enum.ReservedRanges(), dimStyle)
for i := range enum.ReservedNames().Len() {
b.WriteString(dimStyle.Render(fmt.Sprintf("reserved %q;", enum.ReservedNames().Get(i))) + "\n")
}
}
// renderEnumRanges renders enum reserved-number ranges as "N;" or "N to M;".
// Unlike protoreflect.FieldRanges (half-open), protoreflect.EnumRanges are
// fully inclusive, so this can't share renderRanges' off-by-one handling.
func renderEnumRanges(b *strings.Builder, ranges protoreflect.EnumRanges, dimStyle lipgloss.Style) {
for i := range ranges.Len() {
r := ranges.Get(i)
lo, hi := int32(r[0]), int32(r[1])
if lo == hi {
b.WriteString(dimStyle.Render(fmt.Sprintf("reserved %d;", lo)) + "\n")
} else {
b.WriteString(dimStyle.Render(fmt.Sprintf("reserved %d to %d;", lo, hi)) + "\n")
}
}
}
// renderNestedEnums renders enum types declared directly inside msg as
// subsections with a dotted path prefix (e.g. "Outer.Status").
func renderNestedEnums(
b *strings.Builder,
msg protoreflect.MessageDescriptor,
path string,
resolver *dynamicpb.Types,
dimStyle, commentStyle, nameStyle, ruleStyle lipgloss.Style,
annotateFn func(protoreflect.Descriptor) string,
writeCommentFn func(protoreflect.Descriptor),
) {
for i := range msg.Enums().Len() {
enum := msg.Enums().Get(i)
subPath := path + "." + string(enum.Name())
headerText := subPath + annotateFn(enum)
b.WriteString("\n" + nameStyle.Render(headerText) + "\n")
b.WriteString(ruleStyle.Render(strings.Repeat("─", lipgloss.Width(headerText))) + "\n")
writeCommentFn(enum)
b.WriteString("\n")
for j := range enum.Values().Len() {
v := enum.Values().Get(j)
b.WriteString(renderEnumValue(v, enumValueAliasOf(enum, v), resolver, dimStyle, commentStyle))
}
renderEnumReserved(b, enum, dimStyle)
b.WriteString("\n")
}
}
// renderNestedExtensions renders extend blocks declared directly inside msg.
func renderNestedExtensions(b *strings.Builder, msg protoreflect.MessageDescriptor, resolver *dynamicpb.Types, typeStyle, dimStyle, commentStyle lipgloss.Style) {
for i := range msg.Extensions().Len() {
ext := msg.Extensions().Get(i)
b.WriteString(dimStyle.Render(fmt.Sprintf("extend %s {", ext.ContainingMessage().FullName())) + "\n")
b.WriteString(" " + renderField(ext, resolver, typeStyle, dimStyle, commentStyle))
b.WriteString(dimStyle.Render("}") + "\n\n")
}
}
// renderNestedMessages recursively renders nested message types as subsections
// with a dotted path prefix (e.g. "Outer.Inner").
func renderNestedMessages(
b *strings.Builder,
msg protoreflect.MessageDescriptor,
path string,
resolver *dynamicpb.Types,
typeStyle, dimStyle, commentStyle, nameStyle, ruleStyle lipgloss.Style,
annotateFn func(protoreflect.Descriptor) string,
writeCommentFn func(protoreflect.Descriptor),
) {
for i := range msg.Messages().Len() {
nested := msg.Messages().Get(i)
if nested.IsMapEntry() {
continue // synthetic map entry — not a real nested type
}
subPath := path + "." + string(nested.Name())
headerText := subPath + annotateFn(nested)
b.WriteString("\n" + nameStyle.Render(headerText) + "\n")
b.WriteString(ruleStyle.Render(strings.Repeat("─", lipgloss.Width(headerText))) + "\n")
writeCommentFn(nested)
b.WriteString("\n")
renderMessageFields(b, nested, resolver, typeStyle, dimStyle, commentStyle)
b.WriteString("\n")
renderNestedEnums(b, nested, subPath, resolver, dimStyle, commentStyle, nameStyle, ruleStyle, annotateFn, writeCommentFn)
renderNestedExtensions(b, nested, resolver, typeStyle, dimStyle, commentStyle)
renderNestedMessages(b, nested, subPath, resolver, typeStyle, dimStyle, commentStyle, nameStyle, ruleStyle, annotateFn, writeCommentFn)
}
}
func renderMethod(m protoreflect.MethodDescriptor, resolver *dynamicpb.Types, typeStyle, dimStyle, commentStyle lipgloss.Style) string {
var b strings.Builder
input := string(m.Input().Name())
output := string(m.Output().Name())
if m.IsStreamingClient() {
input = "stream " + input
}
if m.IsStreamingServer() {
output = "stream " + output
}
line := fmt.Sprintf("rpc %s(%s) returns (%s)",
string(m.Name()),
typeStyle.Render(input),
typeStyle.Render(output),
)
var annotations []string
if opts, ok := m.Options().(*descriptorpb.MethodOptions); ok && opts != nil {
switch opts.GetIdempotencyLevel() {
case descriptorpb.MethodOptions_NO_SIDE_EFFECTS:
annotations = append(annotations, "no side effects")
case descriptorpb.MethodOptions_IDEMPOTENT:
annotations = append(annotations, "idempotent")
}
if opts.GetDeprecated() {
annotations = append(annotations, "deprecated")
}
}
if len(annotations) > 0 {
line += " " + dimStyle.Render("["+strings.Join(annotations, ", ")+"]")
}
if custom := customOptionsAnnotation(m.Options(), resolver); custom != "" {
line += " " + dimStyle.Render(custom)
}
b.WriteString(line + "\n")
if c := leadingComment(m); c != "" {
for l := range strings.SplitSeq(c, "\n") {
b.WriteString(" " + commentStyle.Render(l) + "\n")
}
}
return b.String()
}
func renderField(f protoreflect.FieldDescriptor, resolver *dynamicpb.Types, typeStyle, dimStyle, commentStyle lipgloss.Style) string {
var b strings.Builder
typeName := fieldTypeName(f)
if f.Kind() == protoreflect.GroupKind && f.ParentFile().Syntax() == protoreflect.Proto2 {
// GroupKind is also how protoreflect reports an Editions field with
// message_encoding=DELIMITED, but Editions has no "group" keyword --
// files using proto3 or Editions syntax can't contain a GroupDecl at
// all -- so that case renders as an ordinary message field instead.
typeName = "group " + typeName
}
switch {
case f.IsList():
typeName = "repeated " + typeName
case f.Cardinality() == protoreflect.Required:
typeName = "required " + typeName
case f.HasOptionalKeyword():
// Covers both a proto2 field explicitly declared "optional" and a
// proto3/editions field with explicit presence (which compiles to a
// hidden synthetic oneof that's never rendered as its own block, so
// the presence tracking is surfaced here instead).
typeName = "optional " + typeName
}
line := fmt.Sprintf("%s %s = %d",
typeStyle.Render(typeName),
string(f.Name()),
f.Number(),
)
if f.HasDefault() {
line += " " + dimStyle.Render(fmt.Sprintf("[default = %s]", formatSingularOptionValue(f, f.Default(), resolver)))
}
wantJSONName := derivedJSONName(string(f.Name()))
if f.IsExtension() {
// Extension fields always get an automatic "[pkg.field]" JSON name
// per the protobuf spec -- that's not an author-written override.
wantJSONName = fmt.Sprintf("[%s]", f.FullName())
}
if f.JSONName() != wantJSONName {
line += " " + dimStyle.Render(fmt.Sprintf("[json_name = %q]", f.JSONName()))
}
if hasExplicitOption(f.Options(), "packed") {
line += " " + dimStyle.Render(fmt.Sprintf("[packed = %v]", f.IsPacked()))
} else if opts, ok := f.Options().(*descriptorpb.FieldOptions); ok {
// FieldOptions.packed is prohibited under Editions -- packed vs.
// expanded wire encoding is controlled by the repeated_field_encoding
// feature instead, so an explicit per-field override there would
// otherwise be invisible to the "packed" check above.
if enc := opts.GetFeatures().GetRepeatedFieldEncoding(); enc != descriptorpb.FeatureSet_REPEATED_FIELD_ENCODING_UNKNOWN {
line += " " + dimStyle.Render(fmt.Sprintf("[features.repeated_field_encoding = %s]", enc))
}
}
if opts, ok := f.Options().(*descriptorpb.FieldOptions); ok {
// Symmetric to the repeated_field_encoding fallback above: since
// Editions has no "group" keyword to signal delimited wire encoding,
// an explicit per-field message_encoding override would otherwise be
// completely invisible -- the field would look like an ordinary
// length-prefixed message field.
if enc := opts.GetFeatures().GetMessageEncoding(); enc != descriptorpb.FeatureSet_MESSAGE_ENCODING_UNKNOWN {
line += " " + dimStyle.Render(fmt.Sprintf("[features.message_encoding = %s]", enc))
}
}
if opts, ok := f.Options().(*descriptorpb.FieldOptions); ok {
if opts.GetDeprecated() {
line += " " + dimStyle.Render("[deprecated]")
}
if opts.GetDebugRedact() {
line += " " + dimStyle.Render("[debug_redact]")
}
}
if custom := customOptionsAnnotation(f.Options(), resolver); custom != "" {
line += " " + dimStyle.Render(custom)
}
b.WriteString(line + "\n")
if c := leadingComment(f); c != "" {
for l := range strings.SplitSeq(c, "\n") {
b.WriteString(" " + commentStyle.Render(l) + "\n")
}
}
return b.String()
}
// enumValueAliasOf returns the name of the canonical enum value that v is an
// alias of (shares its number with an earlier-declared value in enum), or ""
// if v is itself canonical.
func enumValueAliasOf(enum protoreflect.EnumDescriptor, v protoreflect.EnumValueDescriptor) string {
canonical := enum.Values().ByNumber(v.Number())
if canonical == nil || canonical.Name() == v.Name() {
return ""
}
return string(canonical.Name())
}
func renderEnumValue(v protoreflect.EnumValueDescriptor, aliasOf string, resolver *dynamicpb.Types, dimStyle, commentStyle lipgloss.Style) string {
var b strings.Builder
line := fmt.Sprintf("%s = %d", string(v.Name()), v.Number())
if aliasOf != "" {
line += " " + dimStyle.Render(fmt.Sprintf("[alias of %s]", aliasOf))
}
if opts, ok := v.Options().(*descriptorpb.EnumValueOptions); ok && opts != nil && opts.GetDeprecated() {
line += " " + dimStyle.Render("[deprecated]")
}
if custom := customOptionsAnnotation(v.Options(), resolver); custom != "" {
line += " " + dimStyle.Render(custom)
}
b.WriteString(line + "\n")
if c := leadingComment(v); c != "" {
for l := range strings.SplitSeq(c, "\n") {
b.WriteString(" " + commentStyle.Render(l) + "\n")
}
}
return b.String()
}
// cleanComment strips the per-line leading space that proto source info
// stores (from `// comment` → ` comment`) and trims surrounding newlines.
func cleanComment(raw string) string {
if raw == "" {
return ""
}
lines := strings.Split(raw, "\n")
cleaned := make([]string, 0, len(lines))
for _, line := range lines {
cleaned = append(cleaned, strings.TrimPrefix(line, " "))
}
return strings.Trim(strings.Join(cleaned, "\n"), "\n")
}
// leadingComment returns the cleaned leading comment for a descriptor, or "".
func leadingComment(d protoreflect.Descriptor) string {
return cleanComment(d.ParentFile().SourceLocations().ByDescriptor(d).LeadingComments)
}
// isDeprecated reports whether the descriptor has the deprecated option set.
func isDeprecated(d protoreflect.Descriptor) bool {
switch opts := d.Options().(type) {
case *descriptorpb.ServiceOptions:
return opts.GetDeprecated()
case *descriptorpb.MessageOptions:
return opts.GetDeprecated()
case *descriptorpb.EnumOptions:
return opts.GetDeprecated()
case *descriptorpb.FieldOptions:
return opts.GetDeprecated()
}
return false
}
// symbolVisibility returns "local" or "export" if d is a message or enum
// whose "local"/"export" keyword (Editions 2024+) was explicitly written in
// source, or "" otherwise. DescriptorProto/EnumDescriptorProto.Visibility is
// left VISIBILITY_UNSET unless the source explicitly wrote one of those
// keywords on that exact declaration -- an unset value instead resolves from
// the file's default_symbol_visibility feature (or EXPORT pre-2024) -- so
// checking it directly distinguishes an explicit override from the default.
func symbolVisibility(d protoreflect.Descriptor) string {
var vis descriptorpb.SymbolVisibility
switch d := d.(type) {
case protoreflect.MessageDescriptor:
vis = protodesc.ToDescriptorProto(d).GetVisibility()
case protoreflect.EnumDescriptor:
vis = protodesc.ToEnumDescriptorProto(d).GetVisibility()
default:
return ""
}
switch vis {
case descriptorpb.SymbolVisibility_VISIBILITY_LOCAL:
return "local"
case descriptorpb.SymbolVisibility_VISIBILITY_EXPORT:
return "export"
default:
return ""
}
}
// hasExplicitOption reports whether the named field was explicitly set on
// opts, as opposed to merely having a well-defined effective/default value.
// Some options (like FieldOptions.packed) have syntax-dependent implicit
// defaults, so an accessor's return value alone can't tell us whether the
// .proto source actually wrote it out.
func hasExplicitOption(opts protoreflect.ProtoMessage, name protoreflect.Name) bool {
if opts == nil {
return false
}
m := opts.ProtoReflect()
if !m.IsValid() {
return false
}
fd := m.Descriptor().Fields().ByName(name)
if fd == nil {
return false
}
return m.Has(fd)
}
// fileFeatureOverrides returns a "[features.foo = X, features.bar = Y]"
// annotation listing any Editions feature explicitly overridden at the file
// level (e.g. "option features.default_symbol_visibility = LOCAL_ALL;"),
// or "" if the file doesn't override any. FeatureSet fields are sparse --
// only populated when explicitly set at this exact scope, as opposed to
// merely having a resolved effective value inherited from the edition's
// defaults -- so ranging over the populated fields directly (the same
// technique customOptionsAnnotation uses for extensions) finds exactly the
// author-written overrides without hardcoding each of the current features.
func fileFeatureOverrides(fd protoreflect.FileDescriptor) string {
opts, ok := fd.Options().(*descriptorpb.FileOptions)
if !ok || opts == nil {
return ""
}
return featureSetOverrides(opts.GetFeatures())
}
// descriptorFeatureOverrides is fileFeatureOverrides' counterpart for
// messages, enums, and services: each can independently override a feature
// for everything nested inside it (e.g. a message overriding field_presence
// for all its own fields, or an enum overriding its own enum_type), with no
// other trace of it in the rendered output -- unlike a field's own
// field_presence, which is already conveyed by the optional keyword or its
// absence, there's nothing else that would tell a reader why a message,
// enum, or service's contents deviate from the file/edition defaults.
func descriptorFeatureOverrides(d protoreflect.Descriptor) string {
var feats *descriptorpb.FeatureSet
switch opts := d.Options().(type) {
case *descriptorpb.MessageOptions:
feats = opts.GetFeatures()
case *descriptorpb.EnumOptions:
feats = opts.GetFeatures()
case *descriptorpb.ServiceOptions:
feats = opts.GetFeatures()
}
return featureSetOverrides(feats)
}
// featureSetOverrides formats every explicitly-populated field of feats as
// a "[features.foo = X, features.bar = Y]" annotation, or "" if feats is nil
// or has nothing explicitly set. FeatureSet fields are sparse -- populated
// only when explicitly overridden at this exact scope, as opposed to merely
// having a resolved value inherited from an ancestor's default -- so
// ranging over the populated fields directly (the same technique
// customOptionsAnnotation uses for extensions) finds exactly the
// author-written overrides without hardcoding each of the current features.
func featureSetOverrides(feats *descriptorpb.FeatureSet) string {
if feats == nil {
return ""
}
m := feats.ProtoReflect()
var parts []string
m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
parts = append(parts, fmt.Sprintf("features.%s = %s", fd.Name(), formatSingularOptionValue(fd, v, nil)))
return true
})
if len(parts) == 0 {
return ""
}
return "[" + strings.Join(parts, ", ") + "]"
}
// customOptionsAnnotation returns a "[(pkg.ext) = value, ...]" annotation
// listing any custom (extension) options set on opts, or "" if there are
// none. Standard, non-extension fields (e.g. deprecated) are rendered
// elsewhere and are intentionally excluded here to avoid duplication.
func customOptionsAnnotation(opts protoreflect.ProtoMessage, resolver *dynamicpb.Types) string {
if opts == nil {
return ""
}
m := opts.ProtoReflect()
if !m.IsValid() {
return ""
}
var parts []string
m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool {
if !fd.IsExtension() {
return true
}
parts = append(parts, fmt.Sprintf("(%s) = %s", fd.FullName(), formatOptionValue(fd, v, resolver)))
return true
})
if len(parts) == 0 {
return ""
}
return "[" + strings.Join(parts, ", ") + "]"
}
// formatOptionValue formats a single option field's value for display,
// expanding repeated values into a bracketed list.
func formatOptionValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, resolver *dynamicpb.Types) string {
if fd.IsList() {
list := v.List()
parts := make([]string, list.Len())
for i := range list.Len() {
parts[i] = formatSingularOptionValue(fd, list.Get(i), resolver)
}
return "[" + strings.Join(parts, ", ") + "]"
}
return formatSingularOptionValue(fd, v, resolver)
}
// formatSingularOptionValue formats one scalar/message/enum option value.
// Message-kind values are formatted with prototext, which works for
// dynamic (unrecognized-at-compile-time) messages just as well as
// generated ones. resolver, when non-nil, lets prototext expand a
// google.protobuf.Any value whose inner type is only known dynamically (no
// generated Go package) into its compact "[type.url]{...}" form instead of
// falling back to raw type_url/value bytes.
func formatSingularOptionValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, resolver *dynamicpb.Types) string {
switch fd.Kind() {
case protoreflect.MessageKind, protoreflect.GroupKind:
marshalOpts := prototext.MarshalOptions{Multiline: false}
if resolver != nil {
marshalOpts.Resolver = resolver
}
text, err := marshalOpts.Marshal(v.Message().Interface())
if err != nil {
return "{ ... }"
}
return "{ " + strings.TrimSpace(string(text)) + " }"
case protoreflect.EnumKind:
if ev := fd.Enum().Values().ByNumber(v.Enum()); ev != nil {
return string(ev.Name())
}
return fmt.Sprintf("%d", v.Enum())
case protoreflect.StringKind:
return fmt.Sprintf("%q", v.String())
case protoreflect.BytesKind:
return fmt.Sprintf("%q", v.Bytes())
default:
return fmt.Sprintf("%v", v.Interface())
}
}
// fieldTypeName returns a human-readable type name for a field, using
// fully-qualified names for types from other packages.
func fieldTypeName(f protoreflect.FieldDescriptor) string {
if f.IsMap() {
key := f.MapKey().Kind().String()
val := fieldScalarOrRefName(f.MapValue(), f.ParentFile().Package())
return fmt.Sprintf("map<%s, %s>", key, val)
}
return fieldScalarOrRefName(f, f.ParentFile().Package())
}
// fieldScalarOrRefName returns the type name for a field, qualifying
// message/enum types from other packages with their full package path.
func fieldScalarOrRefName(f protoreflect.FieldDescriptor, pkg protoreflect.FullName) string {
switch f.Kind() {
case protoreflect.MessageKind, protoreflect.GroupKind:
msg := f.Message()
if msg.ParentFile().Package() != pkg {
return string(msg.FullName())
}
return string(msg.Name())
case protoreflect.EnumKind:
en := f.Enum()
if en.ParentFile().Package() != pkg {
return string(en.FullName())
}
return string(en.Name())
default:
return f.Kind().String()
}
}