templater.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. "k8s.io/kubernetes/pkg/kubectl/util/term"
  21. "github.com/spf13/cobra"
  22. flag "github.com/spf13/pflag"
  23. )
  24. type FlagExposer interface {
  25. ExposeFlags(cmd *cobra.Command, flags ...string) FlagExposer
  26. }
  27. func ActsAsRootCommand(cmd *cobra.Command, filters []string, groups ...CommandGroup) FlagExposer {
  28. if cmd == nil {
  29. panic("nil root command")
  30. }
  31. templater := &templater{
  32. RootCmd: cmd,
  33. UsageTemplate: MainUsageTemplate(),
  34. HelpTemplate: MainHelpTemplate(),
  35. CommandGroups: groups,
  36. Filtered: filters,
  37. }
  38. cmd.SetUsageFunc(templater.UsageFunc())
  39. cmd.SetHelpFunc(templater.HelpFunc())
  40. return templater
  41. }
  42. func UseOptionsTemplates(cmd *cobra.Command) {
  43. templater := &templater{
  44. UsageTemplate: OptionsUsageTemplate(),
  45. HelpTemplate: OptionsHelpTemplate(),
  46. }
  47. cmd.SetUsageFunc(templater.UsageFunc())
  48. cmd.SetHelpFunc(templater.HelpFunc())
  49. }
  50. type templater struct {
  51. UsageTemplate string
  52. HelpTemplate string
  53. RootCmd *cobra.Command
  54. CommandGroups
  55. Filtered []string
  56. }
  57. func (templater *templater) ExposeFlags(cmd *cobra.Command, flags ...string) FlagExposer {
  58. cmd.SetUsageFunc(templater.UsageFunc(flags...))
  59. return templater
  60. }
  61. func (templater *templater) HelpFunc() func(*cobra.Command, []string) {
  62. return func(c *cobra.Command, s []string) {
  63. t := template.New("help")
  64. t.Funcs(templater.templateFuncs())
  65. template.Must(t.Parse(templater.HelpTemplate))
  66. out := term.NewResponsiveWriter(c.OutOrStdout())
  67. err := t.Execute(out, c)
  68. if err != nil {
  69. c.Println(err)
  70. }
  71. }
  72. }
  73. func (templater *templater) UsageFunc(exposedFlags ...string) func(*cobra.Command) error {
  74. return func(c *cobra.Command) error {
  75. t := template.New("usage")
  76. t.Funcs(templater.templateFuncs(exposedFlags...))
  77. template.Must(t.Parse(templater.UsageTemplate))
  78. out := term.NewResponsiveWriter(c.OutOrStderr())
  79. return t.Execute(out, c)
  80. }
  81. }
  82. func (templater *templater) templateFuncs(exposedFlags ...string) template.FuncMap {
  83. return template.FuncMap{
  84. "trim": strings.TrimSpace,
  85. "trimRight": func(s string) string { return strings.TrimRightFunc(s, unicode.IsSpace) },
  86. "trimLeft": func(s string) string { return strings.TrimLeftFunc(s, unicode.IsSpace) },
  87. "gt": cobra.Gt,
  88. "eq": cobra.Eq,
  89. "rpad": rpad,
  90. "appendIfNotPresent": appendIfNotPresent,
  91. "flagsNotIntersected": flagsNotIntersected,
  92. "visibleFlags": visibleFlags,
  93. "flagsUsages": flagsUsages,
  94. "cmdGroups": templater.cmdGroups,
  95. "cmdGroupsString": templater.cmdGroupsString,
  96. "rootCmd": templater.rootCmdName,
  97. "isRootCmd": templater.isRootCmd,
  98. "optionsCmdFor": templater.optionsCmdFor,
  99. "usageLine": templater.usageLine,
  100. "exposed": func(c *cobra.Command) *flag.FlagSet {
  101. exposed := flag.NewFlagSet("exposed", flag.ContinueOnError)
  102. if len(exposedFlags) > 0 {
  103. for _, name := range exposedFlags {
  104. if flag := c.Flags().Lookup(name); flag != nil {
  105. exposed.AddFlag(flag)
  106. }
  107. }
  108. }
  109. return exposed
  110. },
  111. }
  112. }
  113. func (templater *templater) cmdGroups(c *cobra.Command, all []*cobra.Command) []CommandGroup {
  114. if len(templater.CommandGroups) > 0 && c == templater.RootCmd {
  115. all = filter(all, templater.Filtered...)
  116. return AddAdditionalCommands(templater.CommandGroups, "Other Commands:", all)
  117. }
  118. all = filter(all, "options")
  119. return []CommandGroup{
  120. {
  121. Message: "Available Commands:",
  122. Commands: all,
  123. },
  124. }
  125. }
  126. func (t *templater) cmdGroupsString(c *cobra.Command) string {
  127. groups := []string{}
  128. for _, cmdGroup := range t.cmdGroups(c, c.Commands()) {
  129. cmds := []string{cmdGroup.Message}
  130. for _, cmd := range cmdGroup.Commands {
  131. if cmd.IsAvailableCommand() {
  132. cmds = append(cmds, " "+rpad(cmd.Name(), cmd.NamePadding())+" "+cmd.Short)
  133. }
  134. }
  135. groups = append(groups, strings.Join(cmds, "\n"))
  136. }
  137. return strings.Join(groups, "\n\n")
  138. }
  139. func (t *templater) rootCmdName(c *cobra.Command) string {
  140. return t.rootCmd(c).CommandPath()
  141. }
  142. func (t *templater) isRootCmd(c *cobra.Command) bool {
  143. return t.rootCmd(c) == c
  144. }
  145. func (t *templater) parents(c *cobra.Command) []*cobra.Command {
  146. parents := []*cobra.Command{c}
  147. for current := c; !t.isRootCmd(current) && current.HasParent(); {
  148. current = current.Parent()
  149. parents = append(parents, current)
  150. }
  151. return parents
  152. }
  153. func (t *templater) rootCmd(c *cobra.Command) *cobra.Command {
  154. if c != nil && !c.HasParent() {
  155. return c
  156. }
  157. if t.RootCmd == nil {
  158. panic("nil root cmd")
  159. }
  160. return t.RootCmd
  161. }
  162. func (t *templater) optionsCmdFor(c *cobra.Command) string {
  163. if !c.Runnable() {
  164. return ""
  165. }
  166. rootCmdStructure := t.parents(c)
  167. for i := len(rootCmdStructure) - 1; i >= 0; i-- {
  168. cmd := rootCmdStructure[i]
  169. if _, _, err := cmd.Find([]string{"options"}); err == nil {
  170. return cmd.CommandPath() + " options"
  171. }
  172. }
  173. return ""
  174. }
  175. func (t *templater) usageLine(c *cobra.Command) string {
  176. usage := c.UseLine()
  177. suffix := "[options]"
  178. if c.HasFlags() && !strings.Contains(usage, suffix) {
  179. usage += " " + suffix
  180. }
  181. return usage
  182. }
  183. func flagsUsages(f *flag.FlagSet) string {
  184. x := new(bytes.Buffer)
  185. f.VisitAll(func(flag *flag.Flag) {
  186. if flag.Hidden {
  187. return
  188. }
  189. format := "--%s=%s: %s\n"
  190. if flag.Value.Type() == "string" {
  191. format = "--%s='%s': %s\n"
  192. }
  193. if len(flag.Shorthand) > 0 {
  194. format = " -%s, " + format
  195. } else {
  196. format = " %s " + format
  197. }
  198. fmt.Fprintf(x, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
  199. })
  200. return x.String()
  201. }
  202. func rpad(s string, padding int) string {
  203. template := fmt.Sprintf("%%-%ds", padding)
  204. return fmt.Sprintf(template, s)
  205. }
  206. func appendIfNotPresent(s, stringToAppend string) string {
  207. if strings.Contains(s, stringToAppend) {
  208. return s
  209. }
  210. return s + " " + stringToAppend
  211. }
  212. func flagsNotIntersected(l *flag.FlagSet, r *flag.FlagSet) *flag.FlagSet {
  213. f := flag.NewFlagSet("notIntersected", flag.ContinueOnError)
  214. l.VisitAll(func(flag *flag.Flag) {
  215. if r.Lookup(flag.Name) == nil {
  216. f.AddFlag(flag)
  217. }
  218. })
  219. return f
  220. }
  221. func visibleFlags(l *flag.FlagSet) *flag.FlagSet {
  222. hidden := "help"
  223. f := flag.NewFlagSet("visible", flag.ContinueOnError)
  224. l.VisitAll(func(flag *flag.Flag) {
  225. if flag.Name != hidden {
  226. f.AddFlag(flag)
  227. }
  228. })
  229. return f
  230. }
  231. func filter(cmds []*cobra.Command, names ...string) []*cobra.Command {
  232. out := []*cobra.Command{}
  233. for _, c := range cmds {
  234. if c.Hidden {
  235. continue
  236. }
  237. skip := false
  238. for _, name := range names {
  239. if name == c.Name() {
  240. skip = true
  241. break
  242. }
  243. }
  244. if skip {
  245. continue
  246. }
  247. out = append(out, c)
  248. }
  249. return out
  250. }