Debian Codegraph @

pkg/format/render_markdown.go

raw
1 package format
2
3 import (
4 "reflect"
5 "sort"
6 "strings"
7 )
8
9 // MarkdownTreeRenderer renders a ContainerNode tree into a markdown documentation string.
10 type MarkdownTreeRenderer struct {
11 // HeaderPrefix is the prefix string added to section headers (e.g., "## " for H2 headers).
12 HeaderPrefix string
13 // PropsDescription is the introductory text displayed before the query/param properties list.
14 PropsDescription string
15 // PropsEmptyMessage is the message displayed when no query/param properties are available.
16 PropsEmptyMessage string
17 }
18
19 // Constants for dynamic path segment offsets.
20 // These offsets are added to URLPath to represent dynamic path segments beyond the base path.
21 const (
22 // PathOffset1 represents the first dynamic path segment (URLPath + 1).
23 PathOffset1 = 1
24 // PathOffset2 represents the second dynamic path segment (URLPath + 2).
25 PathOffset2 = 2
26 // PathOffset3 represents the third dynamic path segment (URLPath + 3).
27 PathOffset3 = 3
28 )
29
30 // RenderTree renders a ContainerNode tree into a markdown documentation string.
31 // It categorizes fields into URL fields and query/param fields, sorts them appropriately,
32 // and generates formatted markdown documentation including URL structure and field descriptions.
33 //
34 // Parameters:
35 // - root: The container node tree containing all field information to render.
36 // - scheme: The URL scheme (e.g., "https", "smtp") used when displaying URL field examples.
37 //
38 // Returns a formatted markdown documentation string.
39 func (r MarkdownTreeRenderer) RenderTree(root *ContainerNode, scheme string) string {
40 stringBuilder := strings.Builder{}
41
42 // Initialize slices to categorize fields by their URL part types.
43 // queryFields holds fields that are query parameters or have no URL parts.
44 queryFields := make([]*FieldInfo, 0, len(root.Items))
45 // urlFields holds fields that map to standard URL components (user, password, host, port, path).
46 urlFields := make([]*FieldInfo, 0, len(root.Items))
47 // dynamicURLFields holds fields that map to dynamic path segments (path offsets 1-3).
48 dynamicURLFields := make([]*FieldInfo, 0, len(root.Items))
49
50 // Categorize each field based on its URLParts.
51 for _, node := range root.Items {
52 field := node.Field()
53 for _, urlPart := range field.URLParts {
54 switch urlPart {
55 case URLQuery:
56 // Query parameter fields are added to queryFields.
57 queryFields = append(queryFields, field)
58 case URLPath + PathOffset1,
59 URLPath + PathOffset2,
60 URLPath + PathOffset3:
61 // Dynamic path segments are added to dynamicURLFields.
62 dynamicURLFields = append(dynamicURLFields, field)
63 case URLUser, URLPassword, URLHost, URLPort, URLPath:
64 // Standard URL components are added to urlFields.
65 urlFields = append(urlFields, field)
66 }
67 }
68
69 // Fields with no URL parts default to queryFields.
70 if len(field.URLParts) < 1 {
71 queryFields = append(queryFields, field)
72 }
73 }
74
75 // Append dynamic fields to urlFields so they appear in the URL section.
76 urlFields = append(urlFields, dynamicURLFields...)
77
78 // Sort urlFields by their primary URLPart to ensure consistent ordering.
79 // The order follows the URL structure: user, password, host, port, path.
80 sort.SliceStable(urlFields, func(i, j int) bool {
81 urlPartA := URLQuery
82 if len(urlFields[i].URLParts) > 0 {
83 urlPartA = urlFields[i].URLParts[0]
84 }
85
86 urlPartB := URLQuery
87 if len(urlFields[j].URLParts) > 0 {
88 urlPartB = urlFields[j].URLParts[0]
89 }
90
91 return urlPartA < urlPartB
92 })
93
94 // Generate the URL Fields section.
95 r.writeURLFields(&stringBuilder, urlFields, scheme)
96
97 // Add blank line between URL Fields section and Query/Param Props section.
98 if len(urlFields) > 0 {
99 stringBuilder.WriteString("\n")
100 }
101
102 // Sort queryFields to place required fields first, followed by optional fields.
103 sort.SliceStable(queryFields, func(i, j int) bool {
104 return queryFields[i].Required && !queryFields[j].Required
105 })
106
107 // Filter out fields without key tags, as they cannot be set via query parameters.
108 keyedFields := make([]*FieldInfo, 0, len(queryFields))
109 for _, field := range queryFields {
110 if len(field.Keys) > 0 {
111 keyedFields = append(keyedFields, field)
112 }
113 }
114
115 // Generate the Query/Param Props section header.
116 r.writeHeader(&stringBuilder, "Query/Param Props")
117
118 // Add either the description or empty message based on whether query fields exist.
119 if len(keyedFields) > 0 {
120 stringBuilder.WriteString(r.PropsDescription)
121 } else {
122 stringBuilder.WriteString(r.PropsEmptyMessage)
123 }
124
125 // Add a blank line after the description if both exist.
126 if len(keyedFields) > 0 && r.PropsDescription != "" {
127 // If PropsDescription doesn't end with a newline, we need to end the line
128 // and add a blank line (\n\n). If it already ends with a newline, we only
129 // need to add one more for the blank line.
130 if strings.HasSuffix(r.PropsDescription, "\n") {
131 stringBuilder.WriteString("\n")
132 } else {
133 stringBuilder.WriteString("\n\n")
134 }
135 }
136
137 // Generate documentation for each query field.
138 for i, field := range keyedFields {
139 // Add blank line between fields.
140 if i > 0 {
141 stringBuilder.WriteString("\n")
142 }
143
144 // Write the primary field information (name, description, required/default).
145 r.writeFieldPrimary(&stringBuilder, field)
146
147 // Write additional field information (aliases, enum values).
148 r.writeFieldExtras(&stringBuilder, field)
149 }
150
151 return stringBuilder.String()
152 }
153
154 // writeFieldExtras writes additional field information including aliases and possible enum values.
155 //
156 // Parameters:
157 // - stringBuilder: The string builder to append the formatted output to.
158 // - field: The field information to extract aliases and enum values from.
159 func (MarkdownTreeRenderer) writeFieldExtras(stringBuilder *strings.Builder, field *FieldInfo) {
160 // Output aliases if the field has more than one key (alternative names).
161 if len(field.Keys) > 1 {
162 stringBuilder.WriteString(" Aliases: `")
163
164 for i, key := range field.Keys {
165 if i == 0 {
166 // Skip the primary key since it is shown as the field name above.
167 continue
168 }
169
170 if i > 1 {
171 stringBuilder.WriteString("`, `")
172 }
173
174 stringBuilder.WriteString(key)
175 }
176
177 stringBuilder.WriteString("`\n")
178 }
179
180 // Output possible enum values if the field has an enum formatter.
181 if field.EnumFormatter != nil {
182 stringBuilder.WriteString(" Possible values: `")
183
184 for i, name := range field.EnumFormatter.Names() {
185 if i != 0 {
186 stringBuilder.WriteString("`, `")
187 }
188
189 stringBuilder.WriteString(name)
190 }
191
192 stringBuilder.WriteString("`\n")
193 }
194 }
195
196 // writeFieldPrimary writes the primary field information including name, description,
197 // required status, and default value.
198 //
199 // Parameters:
200 // - stringBuilder: The string builder to append the formatted output to.
201 // - field: The field information to render.
202 func (MarkdownTreeRenderer) writeFieldPrimary(stringBuilder *strings.Builder, field *FieldInfo) {
203 fieldKey := field.Name
204 if len(field.Keys) > 0 {
205 fieldKey = field.Keys[0]
206 }
207
208 // Write the field name in bold.
209 stringBuilder.WriteString("* __")
210 stringBuilder.WriteString(fieldKey)
211 stringBuilder.WriteString("__")
212
213 // Append the field description if available.
214 if field.Description != "" {
215 stringBuilder.WriteString(" - ")
216 stringBuilder.WriteString(field.Description)
217 }
218
219 // Mark required fields or show the default value for optional fields.
220 if field.Required {
221 stringBuilder.WriteString(" (__Required__)\n")
222 } else {
223 stringBuilder.WriteString("\n Default: ")
224
225 // Display "*empty*" for fields with no default value.
226 if field.DefaultValue == "" {
227 stringBuilder.WriteString("*empty*")
228 } else {
229 // For boolean fields, prepend a checkmark or xmark based on the value.
230 if field.Type.Kind() == reflect.Bool {
231 defaultValue, _ := ParseBool(field.DefaultValue, false)
232 if defaultValue {
233 stringBuilder.WriteString("✔ ")
234 } else {
235 stringBuilder.WriteString("❌ ")
236 }
237 }
238
239 // Wrap the default value in backticks for code formatting.
240 stringBuilder.WriteByte('`')
241 stringBuilder.WriteString(field.DefaultValue)
242 stringBuilder.WriteByte('`')
243 }
244
245 stringBuilder.WriteString("\n")
246 }
247 }
248
249 // writeHeader writes a section header with the configured prefix.
250 //
251 // Parameters:
252 // - stringBuilder: The string builder to append the formatted header to.
253 // - text: The header text to write.
254 func (r MarkdownTreeRenderer) writeHeader(stringBuilder *strings.Builder, text string) {
255 stringBuilder.WriteString(r.HeaderPrefix)
256 stringBuilder.WriteString(text)
257 stringBuilder.WriteString("\n\n")
258 }
259
260 // writeURLFields writes the URL Fields section with an example URL for each field.
261 // Each field is highlighted in the context of a complete URL structure.
262 //
263 // Parameters:
264 // - stringBuilder: The string builder to append the formatted output to.
265 // - urlFields: The list of fields that are part of the URL.
266 // - scheme: The URL scheme to use in the example URLs.
267 func (r MarkdownTreeRenderer) writeURLFields(
268 stringBuilder *strings.Builder,
269 urlFields []*FieldInfo,
270 scheme string,
271 ) {
272 // Track which fields have been printed to avoid duplicates.
273 fieldsPrinted := make(map[string]bool)
274
275 // Write the section header.
276 r.writeHeader(stringBuilder, "URL Fields")
277
278 // Generate documentation for each unique URL field.
279 for _, field := range urlFields {
280 // Skip nil fields and fields that have already been processed.
281 if field == nil || fieldsPrinted[field.Name] {
282 continue
283 }
284
285 // Write the primary field information.
286 r.writeFieldPrimary(stringBuilder, field)
287
288 // Write the URL example on a new line within the same list item.
289 stringBuilder.WriteString("<br>URL part: <code class=\"service-url\">")
290 stringBuilder.WriteString(scheme)
291 stringBuilder.WriteString("://")
292
293 // Detect the presence of user and password fields for proper URL formatting.
294 hasUser := false
295 hasPassword := false
296 // Track the highest URLPart to determine if trailing slash is needed.
297 maxPart := URLUser
298
299 for _, f := range urlFields {
300 if f != nil {
301 for _, part := range f.URLParts {
302 switch part {
303 case URLQuery, URLHost, URLPort, URLPath: // No-op for these cases.
304 case URLUser:
305 hasUser = true
306 case URLPassword:
307 hasPassword = true
308 }
309
310 // Update the maximum URLPart encountered.
311 if part > maxPart {
312 maxPart = part
313 }
314 }
315 }
316 }
317
318 // Build the URL with the current field highlighted.
319 // Iterate through all possible URL parts to construct the complete URL structure.
320 for i := URLUser; i <= URLPath+PathOffset3; i++ {
321 for _, fieldInfo := range urlFields {
322 // Skip fields that don't correspond to the current URL part.
323 if fieldInfo == nil || !fieldInfo.IsURLPart(i) {
324 continue
325 }
326
327 // Add the appropriate separator between URL components.
328 if i > URLUser {
329 lastPart := i - 1
330 if lastPart == URLPassword && (hasUser || hasPassword) {
331 // Add ':' separator only if credentials are present.
332 stringBuilder.WriteRune(lastPart.Suffix())
333 } else if lastPart != URLPassword {
334 // Add standard separators like '/' or '@'.
335 stringBuilder.WriteRune(lastPart.Suffix())
336 }
337 }
338
339 // Convert the field name to lowercase for the URL example.
340 slug := strings.ToLower(fieldInfo.Name)
341 // Special case: when displaying port, use "port" as the label.
342 if slug == "host" && i == URLPort {
343 slug = "port"
344 }
345
346 // Highlight the current field with bold HTML tags.
347 if fieldInfo == field {
348 stringBuilder.WriteString("<strong>")
349 stringBuilder.WriteString(slug)
350 stringBuilder.WriteString("</strong>")
351 } else {
352 stringBuilder.WriteString(slug)
353 }
354
355 break
356 }
357 }
358
359 // Add trailing '/' if no dynamic path segments follow the base path.
360 if maxPart < URLPath+PathOffset1 {
361 stringBuilder.WriteByte('/')
362 }
363
364 stringBuilder.WriteString("</code>\n")
365
366 // Mark this field as printed to avoid duplicates.
367 fieldsPrinted[field.Name] = true
368 }
369 }