You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

176 lines
5.1 KiB

  1. package cli
  2. import (
  3. "fmt"
  4. "os"
  5. "strings"
  6. "github.com/pkg/errors"
  7. "github.com/spf13/cobra"
  8. "github.com/spf13/viper"
  9. data "github.com/tendermint/go-wire/data"
  10. "github.com/tendermint/go-wire/data/base58"
  11. )
  12. const (
  13. HomeFlag = "home"
  14. TraceFlag = "trace"
  15. OutputFlag = "output"
  16. EncodingFlag = "encoding"
  17. )
  18. // Executable is the minimal interface to *corba.Command, so we can
  19. // wrap if desired before the test
  20. type Executable interface {
  21. Execute() error
  22. }
  23. // PrepareBaseCmd is meant for tendermint and other servers
  24. func PrepareBaseCmd(cmd *cobra.Command, envPrefix, defaultHome string) Executor {
  25. cobra.OnInitialize(func() { initEnv(envPrefix) })
  26. cmd.PersistentFlags().StringP(HomeFlag, "", defaultHome, "directory for config and data")
  27. cmd.PersistentFlags().Bool(TraceFlag, false, "print out full stack trace on errors")
  28. cmd.PersistentPreRunE = concatCobraCmdFuncs(bindFlagsLoadViper, cmd.PersistentPreRunE)
  29. return Executor{cmd, os.Exit}
  30. }
  31. // PrepareMainCmd is meant for client side libs that want some more flags
  32. //
  33. // This adds --encoding (hex, btc, base64) and --output (text, json) to
  34. // the command. These only really make sense in interactive commands.
  35. func PrepareMainCmd(cmd *cobra.Command, envPrefix, defaultHome string) Executor {
  36. cmd.PersistentFlags().StringP(EncodingFlag, "e", "hex", "Binary encoding (hex|b64|btc)")
  37. cmd.PersistentFlags().StringP(OutputFlag, "o", "text", "Output format (text|json)")
  38. cmd.PersistentPreRunE = concatCobraCmdFuncs(setEncoding, validateOutput, cmd.PersistentPreRunE)
  39. return PrepareBaseCmd(cmd, envPrefix, defaultHome)
  40. }
  41. // initEnv sets to use ENV variables if set.
  42. func initEnv(prefix string) {
  43. copyEnvVars(prefix)
  44. // env variables with TM prefix (eg. TM_ROOT)
  45. viper.SetEnvPrefix(prefix)
  46. viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
  47. viper.AutomaticEnv()
  48. }
  49. // This copies all variables like TMROOT to TM_ROOT,
  50. // so we can support both formats for the user
  51. func copyEnvVars(prefix string) {
  52. prefix = strings.ToUpper(prefix)
  53. ps := prefix + "_"
  54. for _, e := range os.Environ() {
  55. kv := strings.SplitN(e, "=", 2)
  56. if len(kv) == 2 {
  57. k, v := kv[0], kv[1]
  58. if strings.HasPrefix(k, prefix) && !strings.HasPrefix(k, ps) {
  59. k2 := strings.Replace(k, prefix, ps, 1)
  60. os.Setenv(k2, v)
  61. }
  62. }
  63. }
  64. }
  65. // Executor wraps the cobra Command with a nicer Execute method
  66. type Executor struct {
  67. *cobra.Command
  68. Exit func(int) // this is os.Exit by default, override in tests
  69. }
  70. type ExitCoder interface {
  71. ExitCode() int
  72. }
  73. // execute adds all child commands to the root command sets flags appropriately.
  74. // This is called by main.main(). It only needs to happen once to the rootCmd.
  75. func (e Executor) Execute() error {
  76. e.SilenceUsage = true
  77. e.SilenceErrors = true
  78. err := e.Command.Execute()
  79. if err != nil {
  80. if viper.GetBool(TraceFlag) {
  81. fmt.Fprintf(os.Stderr, "ERROR: %+v\n", err)
  82. } else {
  83. fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
  84. }
  85. // return error code 1 by default, can override it with a special error type
  86. exitCode := 1
  87. if ec, ok := err.(ExitCoder); ok {
  88. exitCode = ec.ExitCode()
  89. }
  90. e.Exit(exitCode)
  91. }
  92. return err
  93. }
  94. type cobraCmdFunc func(cmd *cobra.Command, args []string) error
  95. // Returns a single function that calls each argument function in sequence
  96. // RunE, PreRunE, PersistentPreRunE, etc. all have this same signature
  97. func concatCobraCmdFuncs(fs ...cobraCmdFunc) cobraCmdFunc {
  98. return func(cmd *cobra.Command, args []string) error {
  99. for _, f := range fs {
  100. if f != nil {
  101. if err := f(cmd, args); err != nil {
  102. return err
  103. }
  104. }
  105. }
  106. return nil
  107. }
  108. }
  109. // Bind all flags and read the config into viper
  110. func bindFlagsLoadViper(cmd *cobra.Command, args []string) error {
  111. // cmd.Flags() includes flags from this command and all persistent flags from the parent
  112. if err := viper.BindPFlags(cmd.Flags()); err != nil {
  113. return err
  114. }
  115. homeDir := viper.GetString(HomeFlag)
  116. viper.Set(HomeFlag, homeDir)
  117. viper.SetConfigName("config") // name of config file (without extension)
  118. viper.AddConfigPath(homeDir) // search root directory
  119. // If a config file is found, read it in.
  120. if err := viper.ReadInConfig(); err == nil {
  121. // stderr, so if we redirect output to json file, this doesn't appear
  122. // fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed())
  123. } else if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
  124. // we ignore not found error, only parse error
  125. // stderr, so if we redirect output to json file, this doesn't appear
  126. fmt.Fprintf(os.Stderr, "%#v", err)
  127. }
  128. return nil
  129. }
  130. // setEncoding reads the encoding flag
  131. func setEncoding(cmd *cobra.Command, args []string) error {
  132. // validate and set encoding
  133. enc := viper.GetString("encoding")
  134. switch enc {
  135. case "hex":
  136. data.Encoder = data.HexEncoder
  137. case "b64":
  138. data.Encoder = data.B64Encoder
  139. case "btc":
  140. data.Encoder = base58.BTCEncoder
  141. default:
  142. return errors.Errorf("Unsupported encoding: %s", enc)
  143. }
  144. return nil
  145. }
  146. func validateOutput(cmd *cobra.Command, args []string) error {
  147. // validate output format
  148. output := viper.GetString(OutputFlag)
  149. switch output {
  150. case "text", "json":
  151. default:
  152. return errors.Errorf("Unsupported output format: %s", output)
  153. }
  154. return nil
  155. }