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.

160 lines
4.8 KiB

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