package app import ( "fmt" "github.com/gosuri/uitable" "github.com/spf13/cobra" "github.com/spf13/pflag" "github.com/spf13/viper" "os" "path/filepath" "strings" ) const configFlagName = "config" var cfgFile string func init() { pflag.StringVarP(&cfgFile, "config", "c", cfgFile, "Read configuration from specified `FILE`, "+ "support JSON, TOML, YAML, HCL, or Java properties formats.") } func addConfigFlag(basename string, fs *pflag.FlagSet) { fs.AddFlag(pflag.Lookup(configFlagName)) viper.AutomaticEnv() viper.SetEnvPrefix(strings.Replace(strings.ToUpper(basename), "-", "_", -1)) viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_", "-", "_")) cobra.OnInitialize(func() { if cfgFile != "" { viper.SetConfigFile(cfgFile) } else { viper.AddConfigPath(".") if names := strings.Split(basename, "-"); len(names) > 1 { viper.AddConfigPath(filepath.Join(os.Getenv("HOME"), "."+names[0])) viper.AddConfigPath(filepath.Join("/etc", names[0])) } viper.SetConfigName(basename) } if err := viper.ReadInConfig(); err != nil { _, _ = fmt.Fprintf(os.Stderr, "Error: failed to read configuration file(%s): %v\n", cfgFile, err) os.Exit(1) } }) } func printConfig() { if keys := viper.AllKeys(); len(keys) > 0 { fmt.Printf("%v Configuration items:\n", progressMessage) table := uitable.New() table.Separator = " " table.MaxColWidth = 80 table.RightAlign(0) for _, k := range keys { table.AddRow(fmt.Sprintf("%s:", k), viper.Get(k)) } fmt.Printf("%v", table) } }