rest_docs.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. //Copyright 2015 Red Hat Inc. All rights reserved.
  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. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package doc
  14. import (
  15. "bytes"
  16. "fmt"
  17. "io"
  18. "os"
  19. "path/filepath"
  20. "sort"
  21. "strings"
  22. "time"
  23. "github.com/spf13/cobra"
  24. )
  25. func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
  26. flags := cmd.NonInheritedFlags()
  27. flags.SetOutput(buf)
  28. if flags.HasFlags() {
  29. buf.WriteString("Options\n")
  30. buf.WriteString("~~~~~~~\n\n::\n\n")
  31. flags.PrintDefaults()
  32. buf.WriteString("\n")
  33. }
  34. parentFlags := cmd.InheritedFlags()
  35. parentFlags.SetOutput(buf)
  36. if parentFlags.HasFlags() {
  37. buf.WriteString("Options inherited from parent commands\n")
  38. buf.WriteString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n::\n\n")
  39. parentFlags.PrintDefaults()
  40. buf.WriteString("\n")
  41. }
  42. return nil
  43. }
  44. // linkHandler for default ReST hyperlink markup
  45. func defaultLinkHandler(name, ref string) string {
  46. return fmt.Sprintf("`%s <%s.rst>`_", name, ref)
  47. }
  48. // GenReST creates reStructured Text output.
  49. func GenReST(cmd *cobra.Command, w io.Writer) error {
  50. return GenReSTCustom(cmd, w, defaultLinkHandler)
  51. }
  52. // GenReSTCustom creates custom reStructured Text output.
  53. func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, string) string) error {
  54. cmd.InitDefaultHelpCmd()
  55. cmd.InitDefaultHelpFlag()
  56. buf := new(bytes.Buffer)
  57. name := cmd.CommandPath()
  58. short := cmd.Short
  59. long := cmd.Long
  60. if len(long) == 0 {
  61. long = short
  62. }
  63. ref := strings.Replace(name, " ", "_", -1)
  64. buf.WriteString(".. _" + ref + ":\n\n")
  65. buf.WriteString(name + "\n")
  66. buf.WriteString(strings.Repeat("-", len(name)) + "\n\n")
  67. buf.WriteString(short + "\n\n")
  68. buf.WriteString("Synopsis\n")
  69. buf.WriteString("~~~~~~~~\n\n")
  70. buf.WriteString("\n" + long + "\n\n")
  71. if cmd.Runnable() {
  72. buf.WriteString(fmt.Sprintf("::\n\n %s\n\n", cmd.UseLine()))
  73. }
  74. if len(cmd.Example) > 0 {
  75. buf.WriteString("Examples\n")
  76. buf.WriteString("~~~~~~~~\n\n")
  77. buf.WriteString(fmt.Sprintf("::\n\n%s\n\n", indentString(cmd.Example, " ")))
  78. }
  79. if err := printOptionsReST(buf, cmd, name); err != nil {
  80. return err
  81. }
  82. if hasSeeAlso(cmd) {
  83. buf.WriteString("SEE ALSO\n")
  84. buf.WriteString("~~~~~~~~\n\n")
  85. if cmd.HasParent() {
  86. parent := cmd.Parent()
  87. pname := parent.CommandPath()
  88. ref = strings.Replace(pname, " ", "_", -1)
  89. buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(pname, ref), parent.Short))
  90. cmd.VisitParents(func(c *cobra.Command) {
  91. if c.DisableAutoGenTag {
  92. cmd.DisableAutoGenTag = c.DisableAutoGenTag
  93. }
  94. })
  95. }
  96. children := cmd.Commands()
  97. sort.Sort(byName(children))
  98. for _, child := range children {
  99. if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
  100. continue
  101. }
  102. cname := name + " " + child.Name()
  103. ref = strings.Replace(cname, " ", "_", -1)
  104. buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(cname, ref), child.Short))
  105. }
  106. buf.WriteString("\n")
  107. }
  108. if !cmd.DisableAutoGenTag {
  109. buf.WriteString("*Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "*\n")
  110. }
  111. _, err := buf.WriteTo(w)
  112. return err
  113. }
  114. // GenReSTTree will generate a ReST page for this command and all
  115. // descendants in the directory given.
  116. // This function may not work correctly if your command names have `-` in them.
  117. // If you have `cmd` with two subcmds, `sub` and `sub-third`,
  118. // and `sub` has a subcommand called `third`, it is undefined which
  119. // help output will be in the file `cmd-sub-third.1`.
  120. func GenReSTTree(cmd *cobra.Command, dir string) error {
  121. emptyStr := func(s string) string { return "" }
  122. return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler)
  123. }
  124. // GenReSTTreeCustom is the the same as GenReSTTree, but
  125. // with custom filePrepender and linkHandler.
  126. func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
  127. for _, c := range cmd.Commands() {
  128. if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
  129. continue
  130. }
  131. if err := GenReSTTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
  132. return err
  133. }
  134. }
  135. basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".rst"
  136. filename := filepath.Join(dir, basename)
  137. f, err := os.Create(filename)
  138. if err != nil {
  139. return err
  140. }
  141. defer f.Close()
  142. if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
  143. return err
  144. }
  145. if err := GenReSTCustom(cmd, f, linkHandler); err != nil {
  146. return err
  147. }
  148. return nil
  149. }
  150. // adapted from: https://github.com/kr/text/blob/main/indent.go
  151. func indentString(s, p string) string {
  152. var res []byte
  153. b := []byte(s)
  154. prefix := []byte(p)
  155. bol := true
  156. for _, c := range b {
  157. if bol && c != '\n' {
  158. res = append(res, prefix...)
  159. }
  160. res = append(res, c)
  161. bol = c == '\n'
  162. }
  163. return string(res)
  164. }