main.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. // Copyright 2021 the Kilo authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // This file was adapted from https://github.com/prometheus-operator/prometheus-operator/blob/master/cmd/po-docgen/api.go.
  15. package main
  16. import (
  17. "bytes"
  18. "fmt"
  19. "go/ast"
  20. "go/doc"
  21. "go/parser"
  22. "go/token"
  23. "os"
  24. "reflect"
  25. "strings"
  26. )
  27. const (
  28. firstParagraph = `# API
  29. This document is a reference of the API types introduced by Kilo.
  30. > **Note**: this document is generated from code comments. When contributing a change to this document, please do so by changing the code comments.`
  31. )
  32. var (
  33. links = map[string]string{
  34. "metav1.ObjectMeta": "https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#objectmeta-v1-meta",
  35. "metav1.ListMeta": "https://kubernetes.io/docs/reference/generated/kubernetes-api/v1.21/#listmeta-v1-meta",
  36. }
  37. selfLinks = map[string]string{}
  38. typesDoc = map[string]KubeTypes{}
  39. )
  40. func toSectionLink(name string) string {
  41. name = strings.ToLower(name)
  42. name = strings.ReplaceAll(name, " ", "-")
  43. return name
  44. }
  45. func printTOC(types []KubeTypes) {
  46. fmt.Printf("\n## Table of Contents\n")
  47. for _, t := range types {
  48. strukt := t[0]
  49. if len(t) > 1 {
  50. fmt.Printf("* [%s](#%s)\n", strukt.Name, toSectionLink(strukt.Name))
  51. }
  52. }
  53. }
  54. func printAPIDocs(paths []string) {
  55. fmt.Println(firstParagraph)
  56. types := parseDocumentationFrom(paths)
  57. for _, t := range types {
  58. strukt := t[0]
  59. selfLinks[strukt.Name] = "#" + strings.ToLower(strukt.Name)
  60. typesDoc[toLink(strukt.Name)] = t[1:]
  61. }
  62. // we need to parse once more to now add the self links and the inlined fields
  63. types = parseDocumentationFrom(paths)
  64. printTOC(types)
  65. for _, t := range types {
  66. strukt := t[0]
  67. if len(t) > 1 {
  68. fmt.Printf("\n## %s\n\n%s\n\n", strukt.Name, strukt.Doc)
  69. fmt.Println("| Field | Description | Scheme | Required |")
  70. fmt.Println("| ----- | ----------- | ------ | -------- |")
  71. fields := t[1:]
  72. for _, f := range fields {
  73. fmt.Println("|", f.Name, "|", f.Doc, "|", f.Type, "|", f.Mandatory, "|")
  74. }
  75. fmt.Println("")
  76. fmt.Println("[Back to TOC](#table-of-contents)")
  77. }
  78. }
  79. }
  80. // Pair of strings. We need the name of fields and the doc.
  81. type Pair struct {
  82. Name, Doc, Type string
  83. Mandatory bool
  84. }
  85. // KubeTypes is an array to represent all available types in a parsed file. [0] is for the type itself
  86. type KubeTypes []Pair
  87. // parseDocumentationFrom gets all types' documentation and returns them as an
  88. // array. Each type is again represented as an array (we have to use arrays as we
  89. // need to be sure of the order of the fields). This function returns fields and
  90. // struct definitions that have no documentation as {name, ""}.
  91. func parseDocumentationFrom(srcs []string) []KubeTypes {
  92. var docForTypes []KubeTypes
  93. for _, src := range srcs {
  94. pkg := astFrom(src)
  95. for _, kubType := range pkg.Types {
  96. if structType, ok := kubType.Decl.Specs[0].(*ast.TypeSpec).Type.(*ast.StructType); ok {
  97. var ks KubeTypes
  98. ks = append(ks, Pair{kubType.Name, fmtRawDoc(kubType.Doc), "", false})
  99. for _, field := range structType.Fields.List {
  100. // Skip fields that are not tagged.
  101. if field.Tag == nil {
  102. _, _ = fmt.Fprintf(os.Stderr, "Tag is nil, skipping field: %v of type %v\n", field, field.Type)
  103. continue
  104. }
  105. // Treat inlined fields separately as we don't want the original types to appear in the doc.
  106. if isInlined(field) {
  107. // Skip external types, as we don't want their content to be part of the API documentation.
  108. if isInternalType(field.Type) {
  109. ks = append(ks, typesDoc[fieldType(field.Type)]...)
  110. }
  111. continue
  112. }
  113. typeString := fieldType(field.Type)
  114. fieldMandatory := fieldRequired(field)
  115. if n := fieldName(field); n != "-" {
  116. fieldDoc := fmtRawDoc(field.Doc.Text())
  117. ks = append(ks, Pair{n, fieldDoc, typeString, fieldMandatory})
  118. }
  119. }
  120. docForTypes = append(docForTypes, ks)
  121. }
  122. }
  123. }
  124. return docForTypes
  125. }
  126. func astFrom(filePath string) *doc.Package {
  127. fset := token.NewFileSet()
  128. m := make(map[string]*ast.File)
  129. f, err := parser.ParseFile(fset, filePath, nil, parser.ParseComments)
  130. if err != nil {
  131. fmt.Println(err)
  132. return nil
  133. }
  134. m[filePath] = f
  135. apkg, _ := ast.NewPackage(fset, m, nil, nil) //nolint:all
  136. return doc.New(apkg, "", 0)
  137. }
  138. func fmtRawDoc(rawDoc string) string {
  139. var buffer bytes.Buffer
  140. delPrevChar := func() {
  141. if buffer.Len() > 0 {
  142. buffer.Truncate(buffer.Len() - 1) // Delete the last " " or "\n"
  143. }
  144. }
  145. // Ignore all lines after ---
  146. rawDoc = strings.Split(rawDoc, "---")[0]
  147. for line := range strings.SplitSeq(rawDoc, "\n") {
  148. line = strings.TrimRight(line, " ")
  149. leading := strings.TrimLeft(line, " ")
  150. switch {
  151. case len(line) == 0: // Keep paragraphs
  152. delPrevChar()
  153. buffer.WriteString("\n\n")
  154. case strings.HasPrefix(leading, "TODO"): // Ignore one line TODOs
  155. case strings.HasPrefix(leading, "+"): // Ignore instructions to go2idl
  156. default:
  157. if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") {
  158. delPrevChar()
  159. line = "\n" + line + "\n" // Replace it with newline. This is useful when we have a line with: "Example:\n\tJSON-someting..."
  160. } else {
  161. line += " "
  162. }
  163. buffer.WriteString(line)
  164. }
  165. }
  166. postDoc := strings.TrimRight(buffer.String(), "\n")
  167. postDoc = strings.ReplaceAll(postDoc, "\\\"", "\"") // replace user's \" to "
  168. postDoc = strings.ReplaceAll(postDoc, "\"", "\\\"") // Escape "
  169. postDoc = strings.ReplaceAll(postDoc, "\n", "\\n")
  170. postDoc = strings.ReplaceAll(postDoc, "\t", "\\t")
  171. postDoc = strings.ReplaceAll(postDoc, "|", "\\|")
  172. return postDoc
  173. }
  174. func toLink(typeName string) string {
  175. selfLink, hasSelfLink := selfLinks[typeName]
  176. if hasSelfLink {
  177. return wrapInLink(typeName, selfLink)
  178. }
  179. link, hasLink := links[typeName]
  180. if hasLink {
  181. return wrapInLink(typeName, link)
  182. }
  183. return typeName
  184. }
  185. func wrapInLink(text, link string) string {
  186. return fmt.Sprintf("[%s](%s)", text, link)
  187. }
  188. func isInlined(field *ast.Field) bool {
  189. jsonTag := reflect.StructTag(field.Tag.Value[1 : len(field.Tag.Value)-1]).Get("json") // Delete first and last quotation
  190. return strings.Contains(jsonTag, "inline")
  191. }
  192. func isInternalType(typ ast.Expr) bool {
  193. switch typ := typ.(type) {
  194. case *ast.SelectorExpr:
  195. pkg := typ.X.(*ast.Ident)
  196. return strings.HasPrefix(pkg.Name, "monitoring")
  197. case *ast.StarExpr:
  198. return isInternalType(typ.X)
  199. case *ast.ArrayType:
  200. return isInternalType(typ.Elt)
  201. case *ast.MapType:
  202. return isInternalType(typ.Key) && isInternalType(typ.Value)
  203. default:
  204. return true
  205. }
  206. }
  207. // fieldName returns the name of the field as it should appear in JSON format
  208. // "-" indicates that this field is not part of the JSON representation
  209. func fieldName(field *ast.Field) string {
  210. jsonTag := reflect.StructTag(field.Tag.Value[1 : len(field.Tag.Value)-1]).Get("json") // Delete first and last quotation
  211. jsonTag = strings.Split(jsonTag, ",")[0] // This can return "-"
  212. if jsonTag == "" {
  213. if field.Names != nil {
  214. return field.Names[0].Name
  215. }
  216. return field.Type.(*ast.Ident).Name
  217. }
  218. return jsonTag
  219. }
  220. // fieldRequired returns whether a field is a required field.
  221. func fieldRequired(field *ast.Field) bool {
  222. jsonTag := ""
  223. if field.Tag != nil {
  224. jsonTag = reflect.StructTag(field.Tag.Value[1 : len(field.Tag.Value)-1]).Get("json") // Delete first and last quotation
  225. return !strings.Contains(jsonTag, "omitempty")
  226. }
  227. return false
  228. }
  229. func fieldType(typ ast.Expr) string {
  230. switch typ := typ.(type) {
  231. case *ast.Ident:
  232. return toLink(typ.Name)
  233. case *ast.StarExpr:
  234. return "*" + toLink(fieldType(typ.X))
  235. case *ast.SelectorExpr:
  236. pkg := typ.X.(*ast.Ident)
  237. t := typ.Sel
  238. return toLink(pkg.Name + "." + t.Name)
  239. case *ast.ArrayType:
  240. return "[]" + toLink(fieldType(typ.Elt))
  241. case *ast.MapType:
  242. return "map[" + toLink(fieldType(typ.Key)) + "]" + toLink(fieldType(typ.Value))
  243. default:
  244. return ""
  245. }
  246. }
  247. func main() {
  248. printAPIDocs(os.Args[1:])
  249. }