help.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. // Copyright 2017 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package base
  5. import (
  6. "bufio"
  7. "bytes"
  8. "fmt"
  9. "io"
  10. "os"
  11. "strings"
  12. "text/template"
  13. "unicode"
  14. "unicode/utf8"
  15. )
  16. // Help implements the 'help' command.
  17. func Help(w io.Writer, args []string) {
  18. cmd := RootCommand
  19. Args:
  20. for i, arg := range args {
  21. for _, sub := range cmd.Commands {
  22. if sub.Name() == arg {
  23. cmd = sub
  24. continue Args
  25. }
  26. }
  27. // helpSuccess is the help command using as many args as possible that would succeed.
  28. helpSuccess := CommandEnv.Exec + " help"
  29. if i > 0 {
  30. helpSuccess += " " + strings.Join(args[:i], " ")
  31. }
  32. fmt.Fprintf(os.Stderr, "%s help %s: unknown help topic. Run '%s'.\n", CommandEnv.Exec, strings.Join(args, " "), helpSuccess)
  33. SetExitStatus(2) // failed at 'v2ray help cmd'
  34. Exit()
  35. }
  36. if len(cmd.Commands) > 0 {
  37. PrintUsage(os.Stdout, cmd)
  38. } else {
  39. buildCommandText(cmd)
  40. tmpl(os.Stdout, helpTemplate, makeTmplData(cmd))
  41. }
  42. }
  43. var usageTemplate = `{{.Long | trim}}
  44. Usage:
  45. {{.UsageLine}} <command> [arguments]
  46. The commands are:
  47. {{range .Commands}}{{if and (ne .Short "") (or (.Runnable) .Commands)}}
  48. {{.Name | width $.CommandsWidth}} {{.Short}}{{end}}{{end}}
  49. Use "{{.Exec}} help{{with .LongName}} {{.}}{{end}} <command>" for more information about a command.
  50. {{if eq (.UsageLine) (.Exec)}}
  51. Additional help topics:
  52. {{range .Commands}}{{if and (not .Runnable) (not .Commands)}}
  53. {{.Name | width $.CommandsWidth}} {{.Short}}{{end}}{{end}}
  54. Use "{{.Exec}} help{{with .LongName}} {{.}}{{end}} <topic>" for more information about that topic.
  55. {{end}}
  56. `
  57. var helpTemplate = `{{if .Runnable}}usage: {{.UsageLine}}
  58. {{end}}{{.Long | trim}}
  59. `
  60. // An errWriter wraps a writer, recording whether a write error occurred.
  61. type errWriter struct {
  62. w io.Writer
  63. err error
  64. }
  65. func (w *errWriter) Write(b []byte) (int, error) {
  66. n, err := w.w.Write(b)
  67. if err != nil {
  68. w.err = err
  69. }
  70. return n, err
  71. }
  72. // tmpl executes the given template text on data, writing the result to w.
  73. func tmpl(w io.Writer, text string, data interface{}) {
  74. t := template.New("top")
  75. t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize, "width": width})
  76. template.Must(t.Parse(text))
  77. ew := &errWriter{w: w}
  78. err := t.Execute(ew, data)
  79. if ew.err != nil {
  80. // I/O error writing. Ignore write on closed pipe.
  81. if strings.Contains(ew.err.Error(), "pipe") {
  82. SetExitStatus(1)
  83. Exit()
  84. }
  85. Fatalf("writing output: %v", ew.err)
  86. }
  87. if err != nil {
  88. panic(err)
  89. }
  90. }
  91. func capitalize(s string) string {
  92. if s == "" {
  93. return s
  94. }
  95. r, n := utf8.DecodeRuneInString(s)
  96. return string(unicode.ToTitle(r)) + s[n:]
  97. }
  98. func width(width int, value string) string {
  99. format := fmt.Sprintf("%%-%ds", width)
  100. return fmt.Sprintf(format, value)
  101. }
  102. // PrintUsage prints usage of cmd to w
  103. func PrintUsage(w io.Writer, cmd *Command) {
  104. buildCommandText(cmd)
  105. bw := bufio.NewWriter(w)
  106. tmpl(bw, usageTemplate, makeTmplData(cmd))
  107. bw.Flush()
  108. }
  109. // buildCommandText build command text as template
  110. func buildCommandText(cmd *Command) {
  111. data := makeTmplData(cmd)
  112. cmd.UsageLine = buildText(cmd.UsageLine, data)
  113. // DO NOT SUPPORT ".Short":
  114. // - It's not necessary
  115. // - Or, we have to build text for all sub commands of current command, like "v2ray help api"
  116. // cmd.Short = buildText(cmd.Short, data)
  117. cmd.Long = buildText(cmd.Long, data)
  118. }
  119. func buildText(text string, data interface{}) string {
  120. buf := bytes.NewBuffer([]byte{})
  121. text = strings.ReplaceAll(text, "\t", " ")
  122. tmpl(buf, text, data)
  123. return buf.String()
  124. }
  125. type tmplData struct {
  126. *Command
  127. *CommandEnvHolder
  128. }
  129. func makeTmplData(cmd *Command) tmplData {
  130. // Minimum width of the command column
  131. width := 12
  132. for _, c := range cmd.Commands {
  133. l := len(c.Name())
  134. if width < l {
  135. width = l
  136. }
  137. }
  138. CommandEnv.CommandsWidth = width
  139. return tmplData{
  140. Command: cmd,
  141. CommandEnvHolder: &CommandEnv,
  142. }
  143. }