man_docs.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. "strconv"
  22. "strings"
  23. "time"
  24. "github.com/cpuguy83/go-md2man/md2man"
  25. "github.com/spf13/cobra"
  26. "github.com/spf13/pflag"
  27. )
  28. // GenManTree will generate a man page for this command and all descendants
  29. // in the directory given. The header may be nil. This function may not work
  30. // correctly if your command names have `-` in them. If you have `cmd` with two
  31. // subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`
  32. // it is undefined which help output will be in the file `cmd-sub-third.1`.
  33. func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error {
  34. return GenManTreeFromOpts(cmd, GenManTreeOptions{
  35. Header: header,
  36. Path: dir,
  37. CommandSeparator: "-",
  38. })
  39. }
  40. // GenManTreeFromOpts generates a man page for the command and all descendants.
  41. // The pages are written to the opts.Path directory.
  42. func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {
  43. header := opts.Header
  44. if header == nil {
  45. header = &GenManHeader{}
  46. }
  47. for _, c := range cmd.Commands() {
  48. if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
  49. continue
  50. }
  51. if err := GenManTreeFromOpts(c, opts); err != nil {
  52. return err
  53. }
  54. }
  55. section := "1"
  56. if header.Section != "" {
  57. section = header.Section
  58. }
  59. separator := "_"
  60. if opts.CommandSeparator != "" {
  61. separator = opts.CommandSeparator
  62. }
  63. basename := strings.Replace(cmd.CommandPath(), " ", separator, -1)
  64. filename := filepath.Join(opts.Path, basename+"."+section)
  65. f, err := os.Create(filename)
  66. if err != nil {
  67. return err
  68. }
  69. defer f.Close()
  70. headerCopy := *header
  71. return GenMan(cmd, &headerCopy, f)
  72. }
  73. // GenManTreeOptions is the options for generating the man pages.
  74. // Used only in GenManTreeFromOpts.
  75. type GenManTreeOptions struct {
  76. Header *GenManHeader
  77. Path string
  78. CommandSeparator string
  79. }
  80. // GenManHeader is a lot like the .TH header at the start of man pages. These
  81. // include the title, section, date, source, and manual. We will use the
  82. // current time if Date is unset and will use "Auto generated by spf13/cobra"
  83. // if the Source is unset.
  84. type GenManHeader struct {
  85. Title string
  86. Section string
  87. Date *time.Time
  88. date string
  89. Source string
  90. Manual string
  91. }
  92. // GenMan will generate a man page for the given command and write it to
  93. // w. The header argument may be nil, however obviously w may not.
  94. func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {
  95. if header == nil {
  96. header = &GenManHeader{}
  97. }
  98. if err := fillHeader(header, cmd.CommandPath()); err != nil {
  99. return err
  100. }
  101. b := genMan(cmd, header)
  102. _, err := w.Write(md2man.Render(b))
  103. return err
  104. }
  105. func fillHeader(header *GenManHeader, name string) error {
  106. if header.Title == "" {
  107. header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))
  108. }
  109. if header.Section == "" {
  110. header.Section = "1"
  111. }
  112. if header.Date == nil {
  113. now := time.Now()
  114. if epoch := os.Getenv("SOURCE_DATE_EPOCH"); epoch != "" {
  115. unixEpoch, err := strconv.ParseInt(epoch, 10, 64)
  116. if err != nil {
  117. return fmt.Errorf("invalid SOURCE_DATE_EPOCH: %v", err)
  118. }
  119. now = time.Unix(unixEpoch, 0)
  120. }
  121. header.Date = &now
  122. }
  123. header.date = (*header.Date).Format("Jan 2006")
  124. if header.Source == "" {
  125. header.Source = "Auto generated by spf13/cobra"
  126. }
  127. return nil
  128. }
  129. func manPreamble(buf *bytes.Buffer, header *GenManHeader, cmd *cobra.Command, dashedName string) {
  130. description := cmd.Long
  131. if len(description) == 0 {
  132. description = cmd.Short
  133. }
  134. buf.WriteString(fmt.Sprintf(`%% %s(%s)%s
  135. %% %s
  136. %% %s
  137. # NAME
  138. `, header.Title, header.Section, header.date, header.Source, header.Manual))
  139. buf.WriteString(fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short))
  140. buf.WriteString("# SYNOPSIS\n")
  141. buf.WriteString(fmt.Sprintf("**%s**\n\n", cmd.UseLine()))
  142. buf.WriteString("# DESCRIPTION\n")
  143. buf.WriteString(description + "\n\n")
  144. }
  145. func manPrintFlags(buf *bytes.Buffer, flags *pflag.FlagSet) {
  146. flags.VisitAll(func(flag *pflag.Flag) {
  147. if len(flag.Deprecated) > 0 || flag.Hidden {
  148. return
  149. }
  150. format := ""
  151. if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {
  152. format = fmt.Sprintf("**-%s**, **--%s**", flag.Shorthand, flag.Name)
  153. } else {
  154. format = fmt.Sprintf("**--%s**", flag.Name)
  155. }
  156. if len(flag.NoOptDefVal) > 0 {
  157. format += "["
  158. }
  159. if flag.Value.Type() == "string" {
  160. // put quotes on the value
  161. format += "=%q"
  162. } else {
  163. format += "=%s"
  164. }
  165. if len(flag.NoOptDefVal) > 0 {
  166. format += "]"
  167. }
  168. format += "\n\t%s\n\n"
  169. buf.WriteString(fmt.Sprintf(format, flag.DefValue, flag.Usage))
  170. })
  171. }
  172. func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) {
  173. flags := command.NonInheritedFlags()
  174. if flags.HasAvailableFlags() {
  175. buf.WriteString("# OPTIONS\n")
  176. manPrintFlags(buf, flags)
  177. buf.WriteString("\n")
  178. }
  179. flags = command.InheritedFlags()
  180. if flags.HasAvailableFlags() {
  181. buf.WriteString("# OPTIONS INHERITED FROM PARENT COMMANDS\n")
  182. manPrintFlags(buf, flags)
  183. buf.WriteString("\n")
  184. }
  185. }
  186. func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
  187. cmd.InitDefaultHelpCmd()
  188. cmd.InitDefaultHelpFlag()
  189. // something like `rootcmd-subcmd1-subcmd2`
  190. dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1)
  191. buf := new(bytes.Buffer)
  192. manPreamble(buf, header, cmd, dashCommandName)
  193. manPrintOptions(buf, cmd)
  194. if len(cmd.Example) > 0 {
  195. buf.WriteString("# EXAMPLE\n")
  196. buf.WriteString(fmt.Sprintf("```\n%s\n```\n", cmd.Example))
  197. }
  198. if hasSeeAlso(cmd) {
  199. buf.WriteString("# SEE ALSO\n")
  200. seealsos := make([]string, 0)
  201. if cmd.HasParent() {
  202. parentPath := cmd.Parent().CommandPath()
  203. dashParentPath := strings.Replace(parentPath, " ", "-", -1)
  204. seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section)
  205. seealsos = append(seealsos, seealso)
  206. cmd.VisitParents(func(c *cobra.Command) {
  207. if c.DisableAutoGenTag {
  208. cmd.DisableAutoGenTag = c.DisableAutoGenTag
  209. }
  210. })
  211. }
  212. children := cmd.Commands()
  213. sort.Sort(byName(children))
  214. for _, c := range children {
  215. if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
  216. continue
  217. }
  218. seealso := fmt.Sprintf("**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)
  219. seealsos = append(seealsos, seealso)
  220. }
  221. buf.WriteString(strings.Join(seealsos, ", ") + "\n")
  222. }
  223. if !cmd.DisableAutoGenTag {
  224. buf.WriteString(fmt.Sprintf("# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006")))
  225. }
  226. return buf.Bytes()
  227. }