Skip to content

Commit

Permalink
Fix error when a config file is not present (#434)
Browse files Browse the repository at this point in the history
  • Loading branch information
optik-aper authored Mar 27, 2024
1 parent 74ce61b commit 7296ac5
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,10 +65,12 @@ func Execute() {
}

func init() {
configPath := configHome()

// init the config file with viper
initConfig()

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", configHome(), "config file (default is $HOME/.vultr-cli.yaml)")
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", configPath, "config file (default is $HOME/.vultr-cli.yaml)")
if err := viper.BindPFlag("config", rootCmd.PersistentFlags().Lookup("config")); err != nil {
fmt.Printf("error binding root pflag 'config': %v\n", err)
}
Expand Down Expand Up @@ -115,7 +117,7 @@ func init() {
)
}

// initConfig reads in config file and ENV variables if set.
// initConfig reads in config file to viper if it exists
func initConfig() {
configPath := viper.GetString("config")

Expand All @@ -137,9 +139,10 @@ func initConfig() {
}

func configHome() string {
// check for a config file at ~/.config/vultr-cli.yaml
// check for a config file in the user config directory
configFolder, errConfig := os.UserConfigDir()
if errConfig != nil {
fmt.Printf("Unable to determine default user config directory : %v", errConfig)
os.Exit(1)
}

Expand All @@ -152,6 +155,7 @@ func configHome() string {
// check for a config file at ~/.vultr-cli.yaml
configFolder, errHome := os.UserHomeDir()
if errHome != nil {
fmt.Printf("Unable to check user config in home directory: %v", errHome)
os.Exit(1)
}

Expand All @@ -160,6 +164,7 @@ func configHome() string {
// if it doesn't exist, create one
f, err := os.Create(filepath.Clean(configFile))
if err != nil {
fmt.Printf("Unable to create default config file : %v", err)
os.Exit(1)
}

Expand Down

0 comments on commit 7296ac5

Please sign in to comment.