config.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. package app
  2. import (
  3. "fmt"
  4. "github.com/gosuri/uitable"
  5. "github.com/spf13/cobra"
  6. "github.com/spf13/pflag"
  7. "github.com/spf13/viper"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. )
  12. const configFlagName = "config"
  13. var cfgFile string
  14. func init() {
  15. pflag.StringVarP(&cfgFile, "config", "c", cfgFile, "Read configuration from specified `FILE`, "+
  16. "support JSON, TOML, YAML, HCL, or Java properties formats.")
  17. }
  18. func addConfigFlag(basename string, fs *pflag.FlagSet) {
  19. fs.AddFlag(pflag.Lookup(configFlagName))
  20. viper.AutomaticEnv()
  21. viper.SetEnvPrefix(strings.Replace(strings.ToUpper(basename), "-", "_", -1))
  22. viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_"))
  23. cobra.OnInitialize(func() {
  24. if cfgFile != "" {
  25. viper.SetConfigFile(cfgFile)
  26. } else {
  27. viper.AddConfigPath(".")
  28. if names := strings.Split(basename, "-"); len(names) > 1 {
  29. viper.AddConfigPath(filepath.Join(os.Getenv("HOME"), "."+names[0]))
  30. viper.AddConfigPath(filepath.Join("/etc", names[0]))
  31. }
  32. viper.SetConfigName(basename)
  33. }
  34. if err := viper.ReadInConfig(); err != nil {
  35. _, _ = fmt.Fprintf(os.Stderr, "Error: failed to read configuration file(%s): %v\n", cfgFile, err)
  36. os.Exit(1)
  37. }
  38. })
  39. }
  40. func printConfig() {
  41. if keys := viper.AllKeys(); len(keys) > 0 {
  42. fmt.Printf("%v Configuration items:\n", progressMessage)
  43. table := uitable.New()
  44. table.Separator = " "
  45. table.MaxColWidth = 80
  46. table.RightAlign(0)
  47. for _, k := range keys {
  48. table.AddRow(fmt.Sprintf("%s:", k), viper.Get(k))
  49. }
  50. fmt.Printf("%v", table)
  51. }
  52. }