help.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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. tmpl(os.Stdout, helpTemplate, makeTmplData(cmd))
  40. }
  41. }
  42. var usageTemplate = `{{.Long | trim}}
  43. Usage:
  44. {{.UsageLine}} <command> [arguments]
  45. The commands are:
  46. {{range .Commands}}{{if and (ne .Short "") (or (.Runnable) .Commands)}}
  47. {{.Name | width $.CommandsWidth}} {{.Short}}{{end}}{{end}}
  48. Use "{{.Exec}} help{{with .LongName}} {{.}}{{end}} <command>" for more information about a command.
  49. {{if eq (.UsageLine) (.Exec)}}
  50. Additional help topics:
  51. {{range .Commands}}{{if and (not .Runnable) (not .Commands)}}
  52. {{.Name | width $.CommandsWidth}} {{.Short}}{{end}}{{end}}
  53. Use "{{.Exec}} help{{with .LongName}} {{.}}{{end}} <topic>" for more information about that topic.
  54. {{end}}
  55. `
  56. var helpTemplate = `{{if .Runnable}}usage: {{.UsageLine}}
  57. {{end}}{{.Long | trim}}
  58. `
  59. // An errWriter wraps a writer, recording whether a write error occurred.
  60. type errWriter struct {
  61. w io.Writer
  62. err error
  63. }
  64. func (w *errWriter) Write(b []byte) (int, error) {
  65. n, err := w.w.Write(b)
  66. if err != nil {
  67. w.err = err
  68. }
  69. return n, err
  70. }
  71. // tmpl executes the given template text on data, writing the result to w.
  72. func tmpl(w io.Writer, text string, data interface{}) {
  73. t := template.New("top")
  74. t.Funcs(template.FuncMap{"trim": strings.TrimSpace, "capitalize": capitalize, "width": width})
  75. template.Must(t.Parse(text))
  76. ew := &errWriter{w: w}
  77. err := t.Execute(ew, data)
  78. if ew.err != nil {
  79. // I/O error writing. Ignore write on closed pipe.
  80. if strings.Contains(ew.err.Error(), "pipe") {
  81. SetExitStatus(1)
  82. Exit()
  83. }
  84. Fatalf("writing output: %v", ew.err)
  85. }
  86. if err != nil {
  87. panic(err)
  88. }
  89. }
  90. func capitalize(s string) string {
  91. if s == "" {
  92. return s
  93. }
  94. r, n := utf8.DecodeRuneInString(s)
  95. return string(unicode.ToTitle(r)) + s[n:]
  96. }
  97. func width(width int, value string) string {
  98. format := fmt.Sprintf("%%-%ds", width)
  99. return fmt.Sprintf(format, value)
  100. }
  101. // PrintUsage prints usage of cmd to w
  102. func PrintUsage(w io.Writer, cmd *Command) {
  103. bw := bufio.NewWriter(w)
  104. tmpl(bw, usageTemplate, makeTmplData(cmd))
  105. bw.Flush()
  106. }
  107. // buildCommandsText build text of command and its children as template
  108. func buildCommandsText(cmd *Command) {
  109. buildCommandText(cmd)
  110. for _, cmd := range cmd.Commands {
  111. buildCommandsText(cmd)
  112. }
  113. }
  114. // buildCommandText build command text as template
  115. func buildCommandText(cmd *Command) {
  116. cmd.UsageLine = buildText(cmd.UsageLine, makeTmplData(cmd))
  117. cmd.Short = buildText(cmd.Short, makeTmplData(cmd))
  118. cmd.Long = buildText(cmd.Long, makeTmplData(cmd))
  119. }
  120. func buildText(text string, data interface{}) string {
  121. buf := bytes.NewBuffer([]byte{})
  122. text = strings.ReplaceAll(text, "\t", " ")
  123. tmpl(buf, text, data)
  124. return buf.String()
  125. }
  126. type tmplData struct {
  127. *Command
  128. *CommandEnvHolder
  129. }
  130. func makeTmplData(cmd *Command) tmplData {
  131. // Minimum width of the command column
  132. width := 12
  133. for _, c := range cmd.Commands {
  134. l := len(c.Name())
  135. if width < l {
  136. width = l
  137. }
  138. }
  139. CommandEnv.CommandsWidth = width
  140. return tmplData{
  141. Command: cmd,
  142. CommandEnvHolder: &CommandEnv,
  143. }
  144. }