Skip to content

Commit

Permalink
refactor: refactor configuration handling across files
Browse files Browse the repository at this point in the history
- 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 <[email protected]>
  • Loading branch information
blackhorseya committed Jul 26, 2024
1 parent 1fb1b2d commit 5c2119a
Showing 1 changed file with 7 additions and 22 deletions.
29 changes: 7 additions & 22 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package cmd

import (
"fmt"
"os"

"github.com/spf13/cobra"
Expand Down Expand Up @@ -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.
Expand All @@ -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())
}
}

0 comments on commit 5c2119a

Please sign in to comment.