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.

158 lines
4.8 KiB

  1. package cli
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "strings"
  7. "github.com/pkg/errors"
  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. fmt.Fprintf(os.Stderr, "ERROR: %+v\n", err)
  81. } else {
  82. fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
  83. }
  84. // return error code 1 by default, can override it with a special error type
  85. exitCode := 1
  86. if ec, ok := err.(ExitCoder); ok {
  87. exitCode = ec.ExitCode()
  88. }
  89. e.Exit(exitCode)
  90. }
  91. return err
  92. }
  93. type cobraCmdFunc func(cmd *cobra.Command, args []string) error
  94. // Returns a single function that calls each argument function in sequence
  95. // RunE, PreRunE, PersistentPreRunE, etc. all have this same signature
  96. func concatCobraCmdFuncs(fs ...cobraCmdFunc) cobraCmdFunc {
  97. return func(cmd *cobra.Command, args []string) error {
  98. for _, f := range fs {
  99. if f != nil {
  100. if err := f(cmd, args); err != nil {
  101. return err
  102. }
  103. }
  104. }
  105. return nil
  106. }
  107. }
  108. // Bind all flags and read the config into viper
  109. func bindFlagsLoadViper(cmd *cobra.Command, args []string) error {
  110. // cmd.Flags() includes flags from this command and all persistent flags from the parent
  111. if err := viper.BindPFlags(cmd.Flags()); err != nil {
  112. return err
  113. }
  114. homeDir := viper.GetString(HomeFlag)
  115. viper.Set(HomeFlag, homeDir)
  116. viper.SetConfigName("config") // name of config file (without extension)
  117. viper.AddConfigPath(homeDir) // search root directory
  118. viper.AddConfigPath(filepath.Join(homeDir, "config")) // search root directory /config
  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. func validateOutput(cmd *cobra.Command, args []string) error {
  131. // validate output format
  132. output := viper.GetString(OutputFlag)
  133. switch output {
  134. case "text", "json":
  135. default:
  136. return errors.Errorf("Unsupported output format: %s", output)
  137. }
  138. return nil
  139. }