cobra.go 6.6 KB

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