templater.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /*
  2. Copyright 2016 The Kubernetes Authors.
  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. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package templates
  14. import (
  15. "bytes"
  16. "fmt"
  17. "strings"
  18. "text/template"
  19. "unicode"
  20. "github.com/spf13/cobra"
  21. flag "github.com/spf13/pflag"
  22. )
  23. // Content of this package was borrowed from openshift/origin.
  24. type CommandGroup struct {
  25. Message string
  26. Commands []*cobra.Command
  27. }
  28. type CommandGroups []CommandGroup
  29. func (g CommandGroups) Add(c *cobra.Command) {
  30. for _, group := range g {
  31. for _, command := range group.Commands {
  32. c.AddCommand(command)
  33. }
  34. }
  35. }
  36. func (g CommandGroups) Has(c *cobra.Command) bool {
  37. for _, group := range g {
  38. for _, command := range group.Commands {
  39. if command == c {
  40. return true
  41. }
  42. }
  43. }
  44. return false
  45. }
  46. func AddAdditionalCommands(g CommandGroups, message string, cmds []*cobra.Command) CommandGroups {
  47. group := CommandGroup{Message: message}
  48. for _, c := range cmds {
  49. // Don't show commands that has no short description
  50. if !g.Has(c) && len(c.Short) != 0 {
  51. group.Commands = append(group.Commands, c)
  52. }
  53. }
  54. if len(group.Commands) == 0 {
  55. return g
  56. }
  57. return append(g, group)
  58. }
  59. func filter(cmds []*cobra.Command, names ...string) []*cobra.Command {
  60. out := []*cobra.Command{}
  61. for _, c := range cmds {
  62. if c.Hidden {
  63. continue
  64. }
  65. skip := false
  66. for _, name := range names {
  67. if name == c.Name() {
  68. skip = true
  69. break
  70. }
  71. }
  72. if skip {
  73. continue
  74. }
  75. out = append(out, c)
  76. }
  77. return out
  78. }
  79. type FlagExposer interface {
  80. ExposeFlags(cmd *cobra.Command, flags ...string) FlagExposer
  81. }
  82. func ActsAsRootCommand(cmd *cobra.Command, filters []string, groups ...CommandGroup) FlagExposer {
  83. if cmd == nil {
  84. panic("nil root command")
  85. }
  86. cmd.SetHelpTemplate(MainHelpTemplate())
  87. templater := &templater{
  88. RootCmd: cmd,
  89. UsageTemplate: MainUsageTemplate(),
  90. CommandGroups: groups,
  91. Filtered: filters,
  92. }
  93. cmd.SetUsageFunc(templater.UsageFunc())
  94. return templater
  95. }
  96. func UseOptionsTemplates(cmd *cobra.Command) {
  97. cmd.SetHelpTemplate(OptionsHelpTemplate())
  98. templater := &templater{
  99. UsageTemplate: OptionsUsageTemplate(),
  100. }
  101. cmd.SetUsageFunc(templater.UsageFunc())
  102. }
  103. type templater struct {
  104. UsageTemplate string
  105. RootCmd *cobra.Command
  106. CommandGroups
  107. Filtered []string
  108. }
  109. func (templater *templater) ExposeFlags(cmd *cobra.Command, flags ...string) FlagExposer {
  110. cmd.SetUsageFunc(templater.UsageFunc(flags...))
  111. return templater
  112. }
  113. func (templater *templater) UsageFunc(exposedFlags ...string) func(*cobra.Command) error {
  114. return func(c *cobra.Command) error {
  115. t := template.New("custom")
  116. t.Funcs(template.FuncMap{
  117. "trim": strings.TrimSpace,
  118. "trimRight": func(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) },
  119. "trimLeft": func(s string) string { return strings.TrimLeftFunc(s, unicode.IsSpace) },
  120. "gt": cobra.Gt,
  121. "eq": cobra.Eq,
  122. "rpad": rpad,
  123. "appendIfNotPresent": appendIfNotPresent,
  124. "flagsNotIntersected": flagsNotIntersected,
  125. "visibleFlags": visibleFlags,
  126. "flagsUsages": flagsUsages,
  127. "indentLines": indentLines,
  128. "cmdGroups": templater.cmdGroups,
  129. "rootCmd": templater.rootCmdName,
  130. "isRootCmd": templater.isRootCmd,
  131. "optionsCmdFor": templater.optionsCmdFor,
  132. "usageLine": templater.usageLine,
  133. "exposed": func(c *cobra.Command) *flag.FlagSet {
  134. exposed := flag.NewFlagSet("exposed", flag.ContinueOnError)
  135. if len(exposedFlags) > 0 {
  136. for _, name := range exposedFlags {
  137. if flag := c.Flags().Lookup(name); flag != nil {
  138. exposed.AddFlag(flag)
  139. }
  140. }
  141. }
  142. return exposed
  143. },
  144. })
  145. template.Must(t.Parse(templater.UsageTemplate))
  146. return t.Execute(c.OutOrStdout(), c)
  147. }
  148. }
  149. func (templater *templater) cmdGroups(c *cobra.Command, all []*cobra.Command) []CommandGroup {
  150. if len(templater.CommandGroups) > 0 && c == templater.RootCmd {
  151. all = filter(all, templater.Filtered...)
  152. return AddAdditionalCommands(templater.CommandGroups, "Other Commands:", all)
  153. }
  154. all = filter(all, "options")
  155. return []CommandGroup{
  156. {
  157. Message: "Available Commands:",
  158. Commands: all,
  159. },
  160. }
  161. }
  162. func (t *templater) rootCmdName(c *cobra.Command) string {
  163. return t.rootCmd(c).CommandPath()
  164. }
  165. func (t *templater) isRootCmd(c *cobra.Command) bool {
  166. return t.rootCmd(c) == c
  167. }
  168. func (t *templater) parents(c *cobra.Command) []*cobra.Command {
  169. parents := []*cobra.Command{c}
  170. for current := c; !t.isRootCmd(current) && current.HasParent(); {
  171. current = current.Parent()
  172. parents = append(parents, current)
  173. }
  174. return parents
  175. }
  176. func (t *templater) rootCmd(c *cobra.Command) *cobra.Command {
  177. if c != nil && !c.HasParent() {
  178. return c
  179. }
  180. if t.RootCmd == nil {
  181. panic("nil root cmd")
  182. }
  183. return t.RootCmd
  184. }
  185. func (t *templater) optionsCmdFor(c *cobra.Command) string {
  186. if !c.Runnable() {
  187. return ""
  188. }
  189. rootCmdStructure := t.parents(c)
  190. for i := len(rootCmdStructure) - 1; i >= 0; i-- {
  191. cmd := rootCmdStructure[i]
  192. if _, _, err := cmd.Find([]string{"options"}); err == nil {
  193. return cmd.CommandPath() + " options"
  194. }
  195. }
  196. return ""
  197. }
  198. func (t *templater) usageLine(c *cobra.Command) string {
  199. usage := c.UseLine()
  200. suffix := "[options]"
  201. if c.HasFlags() && !strings.Contains(usage, suffix) {
  202. usage += " " + suffix
  203. }
  204. return usage
  205. }
  206. func flagsUsages(f *flag.FlagSet) string {
  207. x := new(bytes.Buffer)
  208. f.VisitAll(func(flag *flag.Flag) {
  209. if flag.Hidden {
  210. return
  211. }
  212. format := "--%s=%s: %s\n"
  213. if flag.Value.Type() == "string" {
  214. format = "--%s='%s': %s\n"
  215. }
  216. if len(flag.Shorthand) > 0 {
  217. format = " -%s, " + format
  218. } else {
  219. format = " %s " + format
  220. }
  221. fmt.Fprintf(x, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
  222. })
  223. return x.String()
  224. }
  225. func rpad(s string, padding int) string {
  226. template := fmt.Sprintf("%%-%ds", padding)
  227. return fmt.Sprintf(template, s)
  228. }
  229. func indentLines(s string, indentation int) string {
  230. r := []string{}
  231. for _, line := range strings.Split(s, "\n") {
  232. indented := strings.Repeat(" ", indentation) + line
  233. r = append(r, indented)
  234. }
  235. return strings.Join(r, "\n")
  236. }
  237. func appendIfNotPresent(s, stringToAppend string) string {
  238. if strings.Contains(s, stringToAppend) {
  239. return s
  240. }
  241. return s + " " + stringToAppend
  242. }
  243. func flagsNotIntersected(l *flag.FlagSet, r *flag.FlagSet) *flag.FlagSet {
  244. f := flag.NewFlagSet("notIntersected", flag.ContinueOnError)
  245. l.VisitAll(func(flag *flag.Flag) {
  246. if r.Lookup(flag.Name) == nil {
  247. f.AddFlag(flag)
  248. }
  249. })
  250. return f
  251. }
  252. func visibleFlags(l *flag.FlagSet) *flag.FlagSet {
  253. hidden := "help"
  254. f := flag.NewFlagSet("visible", flag.ContinueOnError)
  255. l.VisitAll(func(flag *flag.Flag) {
  256. if flag.Name != hidden {
  257. f.AddFlag(flag)
  258. }
  259. })
  260. return f
  261. }