Debian Codegraph @

cmd/gen.go

raw
1 package cmd
2
3 import (
4 "encoding/json"
5 "fmt"
6 "go/ast"
7 "go/parser"
8 "go/token"
9 "io"
10 "os"
11 "path"
12 "path/filepath"
13 "reflect"
14 "sort"
15 "strings"
16
17 "github.com/invopop/jsonschema"
18 "github.com/spf13/cobra"
19 "github.com/spf13/cobra/doc"
20
21 godoc "go/doc"
22
23 "github.com/miniscruff/changie/core"
24 )
25
26 const fmTemplate = `---
27 title: "%s"
28 description: "Help for using the '%s' command"
29 ---
30 `
31
32 type CoreTypes map[string]*godoc.Type
33
34 type TypeProps struct {
35 Name string
36 Doc string
37 File string
38 Line int
39 ExampleLang string
40 ExampleContent string
41 Fields []FieldProps
42 }
43
44 type FieldProps struct {
45 Name string
46 TypeName string
47 Doc string
48 File string
49 Line int
50 Key string
51 MapKeyTypeName string
52 MapValueTypeName string
53 ExampleLang string
54 ExampleContent string
55 TemplateType string
56 IsCustomType bool
57 Required bool
58 Slice bool
59 }
60
61 type Gen struct {
62 *cobra.Command
63 }
64
65 func NewGen() *Gen {
66 g := &Gen{}
67
68 cmd := &cobra.Command{
69 Use: "gen",
70 Short: "Generate documentation",
71 Long: `Generate markdown documentation.`,
72 RunE: g.Run,
73 Args: cobra.NoArgs,
74 Hidden: true,
75 }
76
77 g.Command = cmd
78
79 return g
80 }
81
82 func (g *Gen) Run(cmd *cobra.Command, args []string) error {
83 err := os.MkdirAll(filepath.Join("docs", "config"), core.CreateDirMode)
84 if err != nil {
85 return fmt.Errorf("creating docs/config directory: %w", err)
86 }
87
88 err = os.MkdirAll(filepath.Join("docs", "cli"), core.CreateDirMode)
89 if err != nil {
90 return fmt.Errorf("creating docs/cli directory: %w", err)
91 }
92
93 file, err := os.Create(filepath.Join("docs", "config", "index.md"))
94 if err != nil {
95 return fmt.Errorf("creating or opening config index: %w", err)
96 }
97
98 defer file.Close()
99
100 fset, corePackages := getCorePackages("core")
101
102 writeConfigFrontMatter(file)
103 genConfigDocs(fset, file, corePackages)
104
105 // This auto generates a h4 which is added to our table of contents.
106 cmd.Root().DisableAutoGenTag = true
107
108 jsonReflector := jsonschema.Reflector{}
109 jsonReflector.FieldNameTag = "yaml"
110 jsonReflector.ExpandedStruct = true
111
112 err = jsonReflector.AddGoComments("github.com/miniscruff/changie", "./")
113 if err != nil {
114 return fmt.Errorf("creating jsonschema go comments: %w", err)
115 }
116
117 jsonSchemaFile, err := os.Create(filepath.Join("docs", "schema.json"))
118 if err != nil {
119 return fmt.Errorf("creating or opening json schema file: %w", err)
120 }
121 defer jsonSchemaFile.Close()
122
123 schema := jsonReflector.Reflect(&core.Config{})
124 schemaEncoder := json.NewEncoder(jsonSchemaFile)
125 schemaEncoder.SetIndent("", " ")
126
127 err = schemaEncoder.Encode(schema)
128 if err != nil {
129 return fmt.Errorf("creating or opening config index: %w", err)
130 }
131
132 return doc.GenMarkdownTreeCustom(cmd.Root(), "docs/cli", filePrepender, linkHandler)
133 }
134
135 func filePrepender(filename string) string {
136 name := filepath.Base(filename)
137 base := strings.TrimSuffix(name, path.Ext(name))
138 title := strings.ReplaceAll(base, "_", " ")
139
140 return fmt.Sprintf(fmTemplate, title, title)
141 }
142
143 func linkHandler(name string) string {
144 base := strings.TrimSuffix(name, path.Ext(name))
145 return strings.ToLower(base) + ".md"
146 }
147
148 func genConfigDocs(fset *token.FileSet, writer io.Writer, corePackages CoreTypes) {
149 allTypeProps := buildUniqueTypes(fset, corePackages, "Config", "TemplateCache")
150
151 // grab our root config and store it so we can sort the rest
152 // but keep Config at the top
153 rootConfigType := allTypeProps[0]
154 allTypeProps = allTypeProps[1:]
155
156 sort.Slice(
157 allTypeProps,
158 func(i, j int) bool {
159 return allTypeProps[i].Name < allTypeProps[j].Name
160 },
161 )
162
163 // put the now sorted items back after our root
164 allTypeProps = append([]TypeProps{rootConfigType}, allTypeProps...)
165
166 for _, typeProps := range allTypeProps {
167 // we would have already written by this point, so we should be fine
168 // not ideal but should work
169 _ = writeType(writer, typeProps)
170 }
171 }
172
173 func buildUniqueTypes(
174 fset *token.FileSet,
175 coreTypes CoreTypes,
176 packageName ...string,
177 ) []TypeProps {
178 typeQueue := packageName
179 completed := make(map[string]struct{}, 0)
180 allTypeProps := make([]TypeProps, 0)
181
182 for len(typeQueue) != 0 {
183 typeName := typeQueue[0]
184 typeQueue = typeQueue[1:]
185
186 docType, found := coreTypes[typeName]
187 if !found {
188 continue
189 }
190
191 // don't write objects more than once
192 _, seen := completed[typeName]
193 if seen {
194 continue
195 }
196
197 completed[typeName] = struct{}{}
198
199 typeProps := buildType(fset, docType, coreTypes, &typeQueue)
200 allTypeProps = append(allTypeProps, typeProps)
201 }
202
203 return allTypeProps
204 }
205
206 func getCorePackages(packageName string) (*token.FileSet, CoreTypes) {
207 corePackages := make(CoreTypes)
208 packagePath := fmt.Sprintf("./%v", packageName)
209
210 fset := token.NewFileSet()
211
212 entries, err := os.ReadDir(packagePath)
213 if err != nil {
214 return fset, corePackages
215 }
216
217 files := make([]*ast.File, 0, len(entries))
218
219 for _, entry := range entries {
220 name := entry.Name()
221 if entry.IsDir() || !strings.HasSuffix(name, ".go") {
222 continue
223 }
224
225 file, err := parser.ParseFile(fset, filepath.Join(packagePath, name), nil, parser.ParseComments)
226 if err != nil || file.Name.Name != packageName {
227 continue
228 }
229
230 files = append(files, file)
231 }
232
233 p, err := godoc.NewFromFiles(fset, files, "./")
234 if err != nil {
235 return fset, corePackages
236 }
237
238 for _, t := range p.Types {
239 corePackages[t.Name] = t
240 }
241
242 return fset, corePackages
243 }
244
245 func writeConfigFrontMatter(writer io.Writer) {
246 _, _ = writer.Write([]byte(`---
247 title: "Configuration"
248 hide:
249 - navigation
250 ---
251 `))
252 }
253
254 func buildType(fset *token.FileSet, docType *godoc.Type, coreTypes CoreTypes, queue *[]string) TypeProps {
255 tokPos := docType.Decl.TokPos
256 typeFile := fset.File(tokPos)
257
258 typeProps := TypeProps{
259 Name: docType.Name,
260 Doc: docType.Doc,
261 File: typeFile.Name(),
262 Line: typeFile.Position(tokPos).Line,
263 }
264
265 fieldProps := make([]FieldProps, 0)
266
267 // if any method has an example, we want to list it on the documentation,
268 // kind of an arbitrary rule but it works for now.
269 for _, method := range docType.Methods {
270 if strings.Contains(method.Doc, "example:") {
271 newField := buildMethod(fset, method)
272 fieldProps = append(fieldProps, newField)
273 }
274 }
275
276 before, after, found := strings.Cut(typeProps.Doc, "example:")
277 if found {
278 typeProps.Doc = before
279 lang, content, _ := strings.Cut(strings.Trim(after, " "), "\n")
280 typeProps.ExampleLang = lang
281 typeProps.ExampleContent = formatExample(content)
282 }
283
284 for _, spec := range docType.Decl.Specs {
285 typeSpec, _ := spec.(*ast.TypeSpec)
286 structType, ok := typeSpec.Type.(*ast.StructType)
287
288 if !ok {
289 continue
290 }
291
292 for _, field := range structType.Fields.List {
293 newField := buildField(fset, field, coreTypes, queue)
294 fieldProps = append(fieldProps, newField)
295 }
296 }
297
298 sort.Slice(
299 fieldProps,
300 func(i, j int) bool {
301 return fieldProps[i].Name < fieldProps[j].Name
302 },
303 )
304
305 typeProps.Fields = fieldProps
306
307 return typeProps
308 }
309
310 func buildMethod(fset *token.FileSet, method *godoc.Func) FieldProps {
311 tokPos := method.Decl.Pos()
312 tokenFile := fset.File(tokPos)
313
314 props := FieldProps{
315 Name: method.Name,
316 File: tokenFile.Name(),
317 Line: tokenFile.Line(tokPos),
318 Doc: method.Doc,
319 Key: strings.ToLower(method.Name),
320 IsCustomType: false,
321 Slice: false,
322 }
323
324 before, after, found := strings.Cut(props.Doc, "example:")
325 if found {
326 props.Doc = before
327 lang, content, _ := strings.Cut(strings.Trim(after, " "), "\n")
328 props.ExampleLang = lang
329 props.ExampleContent = formatExample(content)
330 }
331
332 return props
333 }
334
335 func buildField(fset *token.FileSet, field *ast.Field, coreTypes CoreTypes, queue *[]string) FieldProps {
336 tokPos := field.Pos()
337 tokenFile := fset.File(tokPos)
338
339 props := FieldProps{
340 Name: field.Names[0].Name,
341 File: tokenFile.Name(),
342 Line: tokenFile.Line(tokPos),
343 Doc: field.Doc.Text(),
344 Slice: false,
345 }
346
347 switch fieldType := field.Type.(type) {
348 case *ast.Ident:
349 *queue = append(*queue, fieldType.Name)
350 props.TypeName = fieldType.Name
351 case *ast.ArrayType:
352 rootType := fieldType.Elt.(*ast.Ident)
353 *queue = append(*queue, rootType.Name)
354 props.TypeName = rootType.Name
355 props.Slice = true
356 case *ast.StarExpr:
357 rootType := fieldType.X.(*ast.Ident)
358 *queue = append(*queue, rootType.Name)
359 props.TypeName = rootType.Name
360 props.Required = false
361 case *ast.SelectorExpr:
362 rootType := fieldType.Sel
363 *queue = append(*queue, rootType.Name)
364 props.TypeName = rootType.Name
365 case *ast.MapType:
366 mapKeyType := fieldType.Key.(*ast.Ident)
367 *queue = append(*queue, mapKeyType.Name)
368
369 mapValueType := fieldType.Value.(*ast.Ident)
370 *queue = append(*queue, mapValueType.Name)
371
372 // reset type name to empty as we need to use map key type and value type
373 props.TypeName = ""
374 props.MapKeyTypeName = mapKeyType.Name
375 props.MapValueTypeName = mapValueType.Name
376 default:
377 panic(fmt.Errorf("unknown field type: %T for field: '%v'", fieldType, field.Names[0]))
378 }
379
380 before, after, found := strings.Cut(props.Doc, "example:")
381 if found {
382 props.Doc = before
383 lang, content, _ := strings.Cut(strings.Trim(after, " "), "\n")
384 props.ExampleLang = lang
385 props.ExampleContent = formatExample(content)
386 }
387
388 _, isCoreType := coreTypes[props.TypeName]
389 props.IsCustomType = isCoreType
390 props.Key = props.Name
391 parseFieldStructTags(field, &props, queue)
392
393 return props
394 }
395
396 func parseFieldStructTags(field *ast.Field, props *FieldProps, queue *[]string) {
397 if field.Tag == nil {
398 return
399 }
400
401 tags := reflect.StructTag(strings.Trim(field.Tag.Value, "`"))
402
403 if yaml, ok := tags.Lookup("yaml"); ok {
404 // yaml can include more than a name, but its the first word separated by comma
405 key, _, _ := strings.Cut(yaml, ",")
406 if key != "" && key != "-" {
407 props.Key = key
408 } else {
409 props.Key = strings.ToLower(props.Key)
410 }
411 }
412
413 if isRequired, ok := tags.Lookup("required"); ok {
414 props.Required = isRequired == "true"
415 }
416
417 if templateType, ok := tags.Lookup("templateType"); ok {
418 props.TemplateType = templateType
419 *queue = append(*queue, templateType)
420 }
421 }
422
423 func writeType(writer io.Writer, typeProps TypeProps) error {
424 // Do not write our root Config type header
425 if typeProps.Name != "Config" {
426 anchor := strings.ToLower(typeProps.Name) + "-type"
427
428 _, err := writer.Write(fmt.Appendf(
429 []byte{},
430 "## %s %v\n%s\n",
431 typeProps.Name,
432 buildSourceAnchorLink(anchor, typeProps.File, typeProps.Line),
433 typeProps.Doc,
434 ))
435 if err != nil {
436 return err
437 }
438 }
439
440 if typeProps.ExampleContent != "" {
441 _, _ = writer.Write(fmt.Appendf(
442 []byte{},
443 "??? Example\n ```%v\n %v\n ```\n",
444 typeProps.ExampleLang,
445 strings.Trim(typeProps.ExampleContent, "\n"),
446 ))
447 }
448
449 for _, f := range typeProps.Fields {
450 err := writeField(writer, typeProps, f)
451 if err != nil {
452 return err
453 }
454 }
455
456 _, _ = writer.Write([]byte("\n---\n"))
457
458 return nil
459 }
460
461 func writeField(writer io.Writer, parent TypeProps, field FieldProps) error {
462 typePrefix := ""
463 if field.Slice {
464 typePrefix = "[]"
465 }
466
467 anchor := strings.ToLower(parent.Name) + "-" + strings.ToLower(field.Key)
468
469 _, err := writer.Write(fmt.Appendf(
470 []byte{},
471 "### %s %v\n",
472 field.Key,
473 buildSourceAnchorLink(anchor, field.File, field.Line),
474 ))
475 if err != nil {
476 return err
477 }
478
479 switch {
480 case field.IsCustomType:
481 _, _ = writer.Write(fmt.Appendf(
482 []byte{},
483 "type: [%s%s](#%s-type)",
484 typePrefix,
485 field.TypeName,
486 strings.ToLower(field.TypeName),
487 ))
488 case field.TypeName != "":
489 _, _ = writer.Write(fmt.Appendf([]byte{}, "type: `%s%s`", typePrefix, field.TypeName))
490 case field.MapKeyTypeName != "":
491 // currently no option of having a map of custom types or slices
492 // but that is not used right now
493 _, _ = writer.Write(fmt.Appendf(
494 []byte{},
495 "type: map [ `%s` ] `%s`",
496 field.MapKeyTypeName,
497 field.MapValueTypeName,
498 ))
499 }
500
501 if field.TypeName != "" || field.MapKeyTypeName != "" {
502 _, _ = writer.Write([]byte(" | "))
503
504 if field.Required {
505 _, _ = writer.Write([]byte("required"))
506 } else {
507 _, _ = writer.Write([]byte("optional"))
508 }
509 }
510
511 if field.TemplateType != "" {
512 _, _ = writer.Write([]byte(" | "))
513 _, _ = writer.Write(fmt.Appendf(
514 []byte{},
515 "template type: [%s](#%s-type)",
516 field.TemplateType,
517 strings.ToLower(field.TemplateType),
518 ))
519 }
520
521 _, _ = writer.Write([]byte("\n\n"))
522 _, _ = writer.Write([]byte(field.Doc))
523
524 if field.ExampleContent != "" {
525 _, _ = writer.Write(fmt.Appendf(
526 []byte{},
527 "??? Example\n ```%v\n %v\n ```\n",
528 field.ExampleLang,
529 strings.Trim(field.ExampleContent, "\n"),
530 ))
531 }
532
533 _, _ = writer.Write([]byte("\n"))
534
535 return nil
536 }
537
538 func buildSourceAnchorLink(anchor, fileName string, line int) string {
539 file := strings.ReplaceAll(fileName, "\\", "/")
540 url := fmt.Sprintf("https://github.com/miniscruff/changie/blob/<< current_version >>/%v#L%v", file, line)
541
542 return "[:octicons-code-24:](" + url + ") [:octicons-link-24:](#" + anchor + ") {: #" + anchor + "}"
543 }
544
545 func formatExample(content string) string {
546 return strings.ReplaceAll(strings.Trim(content, "\n\t "), "\n", "\n ")
547 }