comments.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright The OpenTelemetry Authors
  2. // SPDX-License-Identifier: Apache-2.0
  3. package configschema // import "github.com/open-telemetry/opentelemetry-collector-contrib/cmd/configschema"
  4. import (
  5. "go/ast"
  6. "go/parser"
  7. "go/token"
  8. "io/fs"
  9. "path/filepath"
  10. "reflect"
  11. "strings"
  12. )
  13. // commentsForStruct returns a map of fieldname -> comment for a struct
  14. func commentsForStruct(v reflect.Value, dr DirResolver) (map[string]string, error) {
  15. elem := v
  16. if v.Kind() == reflect.Ptr {
  17. elem = v.Elem()
  18. }
  19. packagePath, err := dr.TypeToPackagePath(elem.Type())
  20. if err != nil {
  21. return nil, err
  22. }
  23. return searchDirsForComments(packagePath, elem.Type().String())
  24. }
  25. func searchDirsForComments(packageDir, typeName string) (map[string]string, error) {
  26. out := map[string]string{}
  27. err := filepath.WalkDir(packageDir, func(path string, d fs.DirEntry, err error) error {
  28. if d.IsDir() {
  29. commentsForStructName(out, path, typeName)
  30. }
  31. return nil
  32. })
  33. return out, err
  34. }
  35. func commentsForStructName(comments map[string]string, dir, typeName string) {
  36. fset := token.NewFileSet()
  37. pkgs, err := parser.ParseDir(fset, dir, nil, parser.ParseComments)
  38. if err != nil {
  39. panic(err)
  40. }
  41. parts := strings.Split(typeName, ".")
  42. targetPkg := parts[0]
  43. targetType := parts[1]
  44. for pkgName, pkg := range pkgs {
  45. if pkgName != targetPkg {
  46. continue
  47. }
  48. for _, file := range pkg.Files {
  49. for _, decl := range file.Decls {
  50. if gd, ok := decl.(*ast.GenDecl); ok {
  51. for _, spec := range gd.Specs {
  52. if ts, ok := spec.(*ast.TypeSpec); ok {
  53. if ts.Name.Name == targetType {
  54. if structComments := gd.Doc.Text(); structComments != "" {
  55. comments["_struct"] = structComments
  56. }
  57. if st, ok := ts.Type.(*ast.StructType); ok {
  58. for _, field := range st.Fields.List {
  59. if name := fieldName(field); name != "" {
  60. comments[name] = field.Doc.Text()
  61. }
  62. }
  63. }
  64. }
  65. }
  66. }
  67. }
  68. }
  69. }
  70. }
  71. }
  72. func fieldName(field *ast.Field) string {
  73. if field.Names != nil {
  74. return field.Names[0].Name
  75. } else if se, ok := field.Type.(*ast.SelectorExpr); ok {
  76. return se.Sel.Name
  77. } else if id, ok := field.Type.(*ast.Ident); ok {
  78. return id.Name
  79. }
  80. return ""
  81. }