cobra.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. // Copyright © 2013 Steve Francia <spf@spf13.com>.
  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. // Commands similar to git, go tools and other modern CLI tools
  14. // inspired by go, go-Commander, gh and subcommand
  15. package cobra
  16. import (
  17. "fmt"
  18. "io"
  19. "reflect"
  20. "strconv"
  21. "strings"
  22. "text/template"
  23. "unicode"
  24. )
  25. var templateFuncs = template.FuncMap{
  26. "trim": strings.TrimSpace,
  27. "trimRightSpace": trimRightSpace,
  28. "trimTrailingWhitespaces": trimRightSpace,
  29. "appendIfNotPresent": appendIfNotPresent,
  30. "rpad": rpad,
  31. "gt": Gt,
  32. "eq": Eq,
  33. }
  34. var initializers []func()
  35. // EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
  36. // to automatically enable in CLI tools.
  37. // Set this to true to enable it.
  38. var EnablePrefixMatching = false
  39. // EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
  40. // To disable sorting, set it to false.
  41. var EnableCommandSorting = true
  42. // MousetrapHelpText enables an information splash screen on Windows
  43. // if the CLI is started from explorer.exe.
  44. // To disable the mousetrap, just set this variable to blank string ("").
  45. // Works only on Microsoft Windows.
  46. var MousetrapHelpText string = `This is a command line tool.
  47. You need to open cmd.exe and run it from there.
  48. `
  49. // AddTemplateFunc adds a template function that's available to Usage and Help
  50. // template generation.
  51. func AddTemplateFunc(name string, tmplFunc interface{}) {
  52. templateFuncs[name] = tmplFunc
  53. }
  54. // AddTemplateFuncs adds multiple template functions that are available to Usage and
  55. // Help template generation.
  56. func AddTemplateFuncs(tmplFuncs template.FuncMap) {
  57. for k, v := range tmplFuncs {
  58. templateFuncs[k] = v
  59. }
  60. }
  61. // OnInitialize sets the passed functions to be run when each command's
  62. // Execute method is called.
  63. func OnInitialize(y ...func()) {
  64. initializers = append(initializers, y...)
  65. }
  66. // FIXME Gt is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
  67. // Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
  68. // Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
  69. // ints and then compared.
  70. func Gt(a interface{}, b interface{}) bool {
  71. var left, right int64
  72. av := reflect.ValueOf(a)
  73. switch av.Kind() {
  74. case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
  75. left = int64(av.Len())
  76. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  77. left = av.Int()
  78. case reflect.String:
  79. left, _ = strconv.ParseInt(av.String(), 10, 64)
  80. }
  81. bv := reflect.ValueOf(b)
  82. switch bv.Kind() {
  83. case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
  84. right = int64(bv.Len())
  85. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  86. right = bv.Int()
  87. case reflect.String:
  88. right, _ = strconv.ParseInt(bv.String(), 10, 64)
  89. }
  90. return left > right
  91. }
  92. // FIXME Eq is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
  93. // Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
  94. func Eq(a interface{}, b interface{}) bool {
  95. av := reflect.ValueOf(a)
  96. bv := reflect.ValueOf(b)
  97. switch av.Kind() {
  98. case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
  99. panic("Eq called on unsupported type")
  100. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  101. return av.Int() == bv.Int()
  102. case reflect.String:
  103. return av.String() == bv.String()
  104. }
  105. return false
  106. }
  107. func trimRightSpace(s string) string {
  108. return strings.TrimRightFunc(s, unicode.IsSpace)
  109. }
  110. // FIXME appendIfNotPresent is unused by cobra and should be removed in a version 2. It exists only for compatibility with users of cobra.
  111. // appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
  112. func appendIfNotPresent(s, stringToAppend string) string {
  113. if strings.Contains(s, stringToAppend) {
  114. return s
  115. }
  116. return s + " " + stringToAppend
  117. }
  118. // rpad adds padding to the right of a string.
  119. func rpad(s string, padding int) string {
  120. template := fmt.Sprintf("%%-%ds", padding)
  121. return fmt.Sprintf(template, s)
  122. }
  123. // tmpl executes the given template text on data, writing the result to w.
  124. func tmpl(w io.Writer, text string, data interface{}) error {
  125. t := template.New("top")
  126. t.Funcs(templateFuncs)
  127. template.Must(t.Parse(text))
  128. return t.Execute(w, data)
  129. }
  130. // ld compares two strings and returns the levenshtein distance between them.
  131. func ld(s, t string, ignoreCase bool) int {
  132. if ignoreCase {
  133. s = strings.ToLower(s)
  134. t = strings.ToLower(t)
  135. }
  136. d := make([][]int, len(s)+1)
  137. for i := range d {
  138. d[i] = make([]int, len(t)+1)
  139. }
  140. for i := range d {
  141. d[i][0] = i
  142. }
  143. for j := range d[0] {
  144. d[0][j] = j
  145. }
  146. for j := 1; j <= len(t); j++ {
  147. for i := 1; i <= len(s); i++ {
  148. if s[i-1] == t[j-1] {
  149. d[i][j] = d[i-1][j-1]
  150. } else {
  151. min := d[i-1][j]
  152. if d[i][j-1] < min {
  153. min = d[i][j-1]
  154. }
  155. if d[i-1][j-1] < min {
  156. min = d[i-1][j-1]
  157. }
  158. d[i][j] = min + 1
  159. }
  160. }
  161. }
  162. return d[len(s)][len(t)]
  163. }
  164. func stringInSlice(a string, list []string) bool {
  165. for _, b := range list {
  166. if b == a {
  167. return true
  168. }
  169. }
  170. return false
  171. }