~bigbes/tarantool

tarantool-protobuf

ref: 956bf2a2a4baf60a231a5e0377b418860a47cd32 tarantool-protobuf/cmd/protoc-gen-tarantool-doc/main.go -rw-r--r-- 8.4 KiB
956bf2a2 — Eugene Blikh c-accel: fix strdup on glibc with -std=c99 2 months ago
                                                                                
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
// protoc-gen-tarantool-doc generates Markdown reference documentation from
// proto3 .proto files. One Markdown file per input proto, named after the
// proto file (foo.proto -> foo.md). Output mirrors protoc's path layout
// relative to the -I directory.
//
// Usage:
//   protoc --tarantool-doc_out=./docs \
//          --plugin=./protoc-gen-tarantool-doc foo.proto
//
// Output sections (in order, omitted when empty):
//   - Header with package + imports
//   - Messages (per-message: leading comment, fields table, oneofs, nested)
//   - Enums (per-enum: leading comment, values table)
//   - Services (per-service: leading comment, methods table)
//
// Leading comments on messages/enums/fields/services/methods are preserved
// from SourceCodeInfo via protogen.
package main

import (
	"fmt"
	"io"
	"os"
	"path"
	"sort"
	"strings"

	"google.golang.org/protobuf/compiler/protogen"
	"google.golang.org/protobuf/proto"
	"google.golang.org/protobuf/reflect/protoreflect"
	"google.golang.org/protobuf/types/descriptorpb"
	"google.golang.org/protobuf/types/pluginpb"
)

func main() {
	in, err := io.ReadAll(os.Stdin)
	if err != nil {
		fail("read stdin: %v", err)
	}
	req := &pluginpb.CodeGeneratorRequest{}
	if err := proto.Unmarshal(in, req); err != nil {
		fail("parse CodeGeneratorRequest: %v", err)
	}

	// Inject a synthetic go_package so protogen accepts the input even when
	// none of the files declare one (same trick as the codegen plugin).
	for _, f := range req.ProtoFile {
		if f.Options == nil {
			f.Options = &descriptorpb.FileOptions{}
		}
		if f.Options.GoPackage == nil {
			stub := "tarantooldoc_synthetic/" + strings.TrimSuffix(f.GetName(), ".proto")
			f.Options.GoPackage = proto.String(stub)
		}
	}

	plugin, err := protogen.Options{}.New(req)
	if err != nil {
		fail("init protogen: %v", err)
	}
	plugin.SupportedFeatures = uint64(pluginpb.CodeGeneratorResponse_FEATURE_PROTO3_OPTIONAL)

	for _, file := range plugin.Files {
		if !file.Generate {
			continue
		}
		writeFile(plugin, file)
	}

	out, err := proto.Marshal(plugin.Response())
	if err != nil {
		fail("marshal CodeGeneratorResponse: %v", err)
	}
	if _, err := os.Stdout.Write(out); err != nil {
		fail("write stdout: %v", err)
	}
}

func writeFile(plugin *protogen.Plugin, file *protogen.File) {
	base := strings.TrimSuffix(path.Base(file.Desc.Path()), ".proto") + ".md"
	relDir := path.Dir(file.Desc.Path())
	outPath := base
	if relDir != "" && relDir != "." {
		outPath = path.Join(relDir, base)
	}
	g := plugin.NewGeneratedFile(outPath, "")

	var b strings.Builder
	fmt.Fprintf(&b, "# %s\n\n", file.Desc.Path())
	if pkg := file.Desc.Package(); pkg != "" {
		fmt.Fprintf(&b, "**Package:** `%s`\n\n", pkg)
	}

	if imports := file.Desc.Imports(); imports.Len() > 0 {
		b.WriteString("**Imports:**\n\n")
		for i := 0; i < imports.Len(); i++ {
			fmt.Fprintf(&b, "- `%s`\n", imports.Get(i).Path())
		}
		b.WriteString("\n")
	}

	if len(file.Messages) > 0 {
		b.WriteString("## Messages\n\n")
		for _, m := range file.Messages {
			renderMessage(&b, m, 3)
		}
	}

	if len(file.Enums) > 0 {
		b.WriteString("## Enums\n\n")
		for _, e := range file.Enums {
			renderEnum(&b, e, 3)
		}
	}

	if len(file.Services) > 0 {
		b.WriteString("## Services\n\n")
		for _, s := range file.Services {
			renderService(&b, s)
		}
	}

	g.P(b.String())
}

// ----- rendering helpers ----------------------------------------------------

func heading(level int) string { return strings.Repeat("#", level) + " " }

func cleanComment(c protogen.Comments) string {
	// protogen.Comments leaves each line with a leading space and trailing
	// newline. Strip these and join with single newlines.
	raw := strings.TrimRight(string(c), "\n")
	if raw == "" {
		return ""
	}
	lines := strings.Split(raw, "\n")
	for i, l := range lines {
		lines[i] = strings.TrimSpace(strings.TrimPrefix(l, " "))
	}
	return strings.Join(lines, " ")
}

// renderMessage emits a section for one message and recurses into nested
// types. `level` controls Markdown heading depth.
func renderMessage(b *strings.Builder, m *protogen.Message, level int) {
	// Skip synthetic map-entry messages.
	if m.Desc.IsMapEntry() {
		return
	}

	full := string(m.Desc.FullName())
	fmt.Fprintf(b, "%s`%s`\n\n", heading(level), full)
	if c := cleanComment(m.Comments.Leading); c != "" {
		fmt.Fprintf(b, "%s\n\n", c)
	}

	// Collect oneof groupings to annotate fields.
	oneofByField := map[string]string{}
	for _, oo := range m.Oneofs {
		if oo.Desc.IsSynthetic() {
			continue
		}
		for _, f := range oo.Fields {
			oneofByField[string(f.Desc.Name())] = string(oo.Desc.Name())
		}
	}

	if len(m.Fields) > 0 {
		b.WriteString("| # | Field | Type | Label | Description |\n")
		b.WriteString("|---|-------|------|-------|-------------|\n")
		// Display in declaration order.
		fields := append([]*protogen.Field(nil), m.Fields...)
		sort.SliceStable(fields, func(i, j int) bool {
			return fields[i].Desc.Number() < fields[j].Desc.Number()
		})
		for _, f := range fields {
			fmt.Fprintf(b, "| %d | `%s` | %s | %s | %s |\n",
				f.Desc.Number(),
				f.Desc.Name(),
				fieldTypeText(f),
				labelText(f, oneofByField[string(f.Desc.Name())]),
				inlineComment(f.Comments.Leading))
		}
		b.WriteString("\n")
	}

	// Recurse into nested messages and enums under deeper headings.
	for _, nm := range m.Messages {
		renderMessage(b, nm, level+1)
	}
	for _, ne := range m.Enums {
		renderEnum(b, ne, level+1)
	}
}

func renderEnum(b *strings.Builder, e *protogen.Enum, level int) {
	fmt.Fprintf(b, "%s`%s`\n\n", heading(level), e.Desc.FullName())
	if c := cleanComment(e.Comments.Leading); c != "" {
		fmt.Fprintf(b, "%s\n\n", c)
	}
	b.WriteString("| Value | Name | Description |\n")
	b.WriteString("|-------|------|-------------|\n")
	for _, v := range e.Values {
		fmt.Fprintf(b, "| %d | `%s` | %s |\n",
			v.Desc.Number(),
			v.Desc.Name(),
			inlineComment(v.Comments.Leading))
	}
	b.WriteString("\n")
}

func renderService(b *strings.Builder, s *protogen.Service) {
	fmt.Fprintf(b, "### `%s`\n\n", s.Desc.FullName())
	if c := cleanComment(s.Comments.Leading); c != "" {
		fmt.Fprintf(b, "%s\n\n", c)
	}
	if len(s.Methods) == 0 {
		return
	}
	b.WriteString("| Method | Request | Response | Streaming | Description |\n")
	b.WriteString("|--------|---------|----------|-----------|-------------|\n")
	for _, m := range s.Methods {
		streaming := streamingText(m)
		fmt.Fprintf(b, "| `%s` | `%s` | `%s` | %s | %s |\n",
			m.Desc.Name(),
			m.Desc.Input().FullName(),
			m.Desc.Output().FullName(),
			streaming,
			inlineComment(m.Comments.Leading))
	}
	b.WriteString("\n")
}

// fieldTypeText renders a field's type as a Markdown fragment. Scalars stay
// lowercase; messages/enums become full-name code spans. Map fields render
// as `map<K, V>`.
func fieldTypeText(f *protogen.Field) string {
	d := f.Desc
	if d.IsMap() {
		return fmt.Sprintf("`map<%s, %s>`",
			scalarOrName(d.MapKey()),
			scalarOrName(d.MapValue()))
	}
	return "`" + scalarOrName(d) + "`"
}

// scalarOrName resolves a FieldDescriptor's type as either the lowercase
// proto3 scalar name or the full name of the referenced message/enum.
func scalarOrName(d protoreflect.FieldDescriptor) string {
	switch d.Kind() {
	case protoreflect.MessageKind, protoreflect.GroupKind:
		return string(d.Message().FullName())
	case protoreflect.EnumKind:
		return string(d.Enum().FullName())
	}
	return d.Kind().String()
}

func labelText(f *protogen.Field, oneof string) string {
	parts := []string{}
	d := f.Desc
	if d.IsList() && !d.IsMap() {
		parts = append(parts, "repeated")
	}
	if d.HasOptionalKeyword() {
		parts = append(parts, "optional")
	}
	if oneof != "" {
		parts = append(parts, fmt.Sprintf("oneof `%s`", oneof))
	}
	if len(parts) == 0 {
		return "—"
	}
	return strings.Join(parts, ", ")
}

func streamingText(m *protogen.Method) string {
	cs := m.Desc.IsStreamingClient()
	ss := m.Desc.IsStreamingServer()
	switch {
	case cs && ss:
		return "bidi"
	case cs:
		return "client"
	case ss:
		return "server"
	}
	return "unary"
}

// inlineComment squashes a leading comment to a single line for use inside a
// Markdown table cell (newlines and pipes break table rendering). Empty
// comments render as an em-dash to keep the column non-empty.
func inlineComment(c protogen.Comments) string {
	s := cleanComment(c)
	if s == "" {
		return "—"
	}
	s = strings.ReplaceAll(s, "|", "\\|")
	s = strings.ReplaceAll(s, "\n", " ")
	return s
}

func fail(format string, args ...any) {
	fmt.Fprintf(os.Stderr, "protoc-gen-tarantool-doc: "+format+"\n", args...)
	os.Exit(1)
}