man_docs.go 6.7 KB

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