From 5c2119a8ed4ae21be7ddc9a820ef7d465ba8434a Mon Sep 17 00:00:00 2001 From: Sean Zheng Date: Fri, 26 Jul 2024 13:20:33 +0800 Subject: [PATCH] refactor: refactor configuration handling across files - Remove unnecessary import of `fmt` - Refactor the assignment of `config` flag to use a multi-line format - Bind the `config` flag to `viper` for persistent flags - Remove redundant code related to reading config file and environment variables Signed-off-by: Sean Zheng --- cmd/root.go | 29 +++++++---------------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index b820b22..261d869 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -1,7 +1,6 @@ package cmd import ( - "fmt" "os" "github.com/spf13/cobra" @@ -35,7 +34,13 @@ func init() { // Cobra supports persistent flags, which, if defined here, // will be global for your application. - rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.config/ryze/.ryze.yaml)") + rootCmd.PersistentFlags().StringVar( + &cfgFile, + "config", + "", + "config file (default is $HOME/.config/ryze/.ryze.yaml)", + ) + _ = viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config")) // Cobra also supports local flags, which will only run // when this action is called directly. @@ -44,24 +49,4 @@ func init() { // initConfig reads in config file and ENV variables if set. func initConfig() { - if cfgFile != "" { - // Use config file from the flag. - viper.SetConfigFile(cfgFile) - } else { - // Find home directory. - home, err := os.UserHomeDir() - cobra.CheckErr(err) - - // Search config in home directory with name ".ryze" (without extension). - viper.AddConfigPath(home) - viper.SetConfigType("yaml") - viper.SetConfigName(".ryze") - } - - viper.AutomaticEnv() // read in environment variables that match - - // If a config file is found, read it in. - if err := viper.ReadInConfig(); err == nil { - fmt.Fprintln(os.Stderr, "Using config file:", viper.ConfigFileUsed()) - } }