man_docs.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  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. mangen "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.IsHelpCommand() {
  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. type GenManTreeOptions struct {
  73. Header *GenManHeader
  74. Path string
  75. CommandSeparator string
  76. }
  77. // GenManHeader is a lot like the .TH header at the start of man pages. These
  78. // include the title, section, date, source, and manual. We will use the
  79. // current time if Date if unset and will use "Auto generated by spf13/cobra"
  80. // if the Source is unset.
  81. type GenManHeader struct {
  82. Title string
  83. Section string
  84. Date *time.Time
  85. date string
  86. Source string
  87. Manual string
  88. }
  89. // GenMan will generate a man page for the given command and write it to
  90. // w. The header argument may be nil, however obviously w may not.
  91. func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {
  92. if header == nil {
  93. header = &GenManHeader{}
  94. }
  95. fillHeader(header, cmd.CommandPath())
  96. b := genMan(cmd, header)
  97. _, err := w.Write(mangen.Render(b))
  98. return err
  99. }
  100. func fillHeader(header *GenManHeader, name string) {
  101. if header.Title == "" {
  102. header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))
  103. }
  104. if header.Section == "" {
  105. header.Section = "1"
  106. }
  107. if header.Date == nil {
  108. now := time.Now()
  109. header.Date = &now
  110. }
  111. header.date = (*header.Date).Format("Jan 2006")
  112. if header.Source == "" {
  113. header.Source = "Auto generated by spf13/cobra"
  114. }
  115. }
  116. func manPreamble(out io.Writer, header *GenManHeader, cmd *cobra.Command, dashedName string) {
  117. description := cmd.Long
  118. if len(description) == 0 {
  119. description = cmd.Short
  120. }
  121. fmt.Fprintf(out, `%% %s(%s)%s
  122. %% %s
  123. %% %s
  124. # NAME
  125. `, header.Title, header.Section, header.date, header.Source, header.Manual)
  126. fmt.Fprintf(out, "%s \\- %s\n\n", dashedName, cmd.Short)
  127. fmt.Fprintf(out, "# SYNOPSIS\n")
  128. fmt.Fprintf(out, "**%s**\n\n", cmd.UseLine())
  129. fmt.Fprintf(out, "# DESCRIPTION\n")
  130. fmt.Fprintf(out, "%s\n\n", description)
  131. }
  132. func manPrintFlags(out io.Writer, flags *pflag.FlagSet) {
  133. flags.VisitAll(func(flag *pflag.Flag) {
  134. if len(flag.Deprecated) > 0 || flag.Hidden {
  135. return
  136. }
  137. format := ""
  138. if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {
  139. format = fmt.Sprintf("**-%s**, **--%s**", flag.Shorthand, flag.Name)
  140. } else {
  141. format = fmt.Sprintf("**--%s**", flag.Name)
  142. }
  143. if len(flag.NoOptDefVal) > 0 {
  144. format = format + "["
  145. }
  146. if flag.Value.Type() == "string" {
  147. // put quotes on the value
  148. format = format + "=%q"
  149. } else {
  150. format = format + "=%s"
  151. }
  152. if len(flag.NoOptDefVal) > 0 {
  153. format = format + "]"
  154. }
  155. format = format + "\n\t%s\n\n"
  156. fmt.Fprintf(out, format, flag.DefValue, flag.Usage)
  157. })
  158. }
  159. func manPrintOptions(out io.Writer, command *cobra.Command) {
  160. flags := command.NonInheritedFlags()
  161. if flags.HasFlags() {
  162. fmt.Fprintf(out, "# OPTIONS\n")
  163. manPrintFlags(out, flags)
  164. fmt.Fprintf(out, "\n")
  165. }
  166. flags = command.InheritedFlags()
  167. if flags.HasFlags() {
  168. fmt.Fprintf(out, "# OPTIONS INHERITED FROM PARENT COMMANDS\n")
  169. manPrintFlags(out, flags)
  170. fmt.Fprintf(out, "\n")
  171. }
  172. }
  173. func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
  174. // something like `rootcmd-subcmd1-subcmd2`
  175. dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1)
  176. buf := new(bytes.Buffer)
  177. manPreamble(buf, header, cmd, dashCommandName)
  178. manPrintOptions(buf, cmd)
  179. if len(cmd.Example) > 0 {
  180. fmt.Fprintf(buf, "# EXAMPLE\n")
  181. fmt.Fprintf(buf, "\n%s\n\n", cmd.Example)
  182. }
  183. if hasSeeAlso(cmd) {
  184. fmt.Fprintf(buf, "# SEE ALSO\n")
  185. seealsos := make([]string, 0)
  186. if cmd.HasParent() {
  187. parentPath := cmd.Parent().CommandPath()
  188. dashParentPath := strings.Replace(parentPath, " ", "-", -1)
  189. seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section)
  190. seealsos = append(seealsos, seealso)
  191. cmd.VisitParents(func(c *cobra.Command) {
  192. if c.DisableAutoGenTag {
  193. cmd.DisableAutoGenTag = c.DisableAutoGenTag
  194. }
  195. })
  196. }
  197. children := cmd.Commands()
  198. sort.Sort(byName(children))
  199. for _, c := range children {
  200. if !c.IsAvailableCommand() || c.IsHelpCommand() {
  201. continue
  202. }
  203. seealso := fmt.Sprintf("**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)
  204. seealsos = append(seealsos, seealso)
  205. }
  206. fmt.Fprintf(buf, "%s\n", strings.Join(seealsos, ", "))
  207. }
  208. if !cmd.DisableAutoGenTag {
  209. fmt.Fprintf(buf, "# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006"))
  210. }
  211. return buf.Bytes()
  212. }