Skip to content

Commit

Permalink
add xdg style config path
Browse files Browse the repository at this point in the history
  • Loading branch information
cgsdev0 committed Jul 1, 2024
1 parent 0c301fa commit 317a42c
Showing 1 changed file with 18 additions and 8 deletions.
26 changes: 18 additions & 8 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,17 @@ func init() {
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.bootdev.yaml)")
}

func readViperConfig(paths []string) error {
for _, path := range paths {
_, err := os.Stat(path)
if err == nil {
viper.SetConfigFile(path)
break
}
}
return viper.ReadInConfig()
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
viper.SetDefault("base_url", "https://boot.dev")
Expand All @@ -54,14 +65,13 @@ func initConfig() {
home, err := os.UserHomeDir()
cobra.CheckErr(err)

// Search config in home directory with name ".bootdev" (without extension).
viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(".bootdev")
if err := viper.ReadInConfig(); err != nil {
home, err := os.UserHomeDir()
cobra.CheckErr(err)
viper.SafeWriteConfigAs(path.Join(home, ".bootdev.yaml"))
// viper's built in config path thing sucks, let's do it ourselves
defaultPath := path.Join(home, ".bootdev.yaml")
configPaths := []string{}
configPaths = append(configPaths, path.Join(home, ".config", "bootdev", "config.yaml"))
configPaths = append(configPaths, defaultPath)
if err := readViperConfig(configPaths); err != nil {
viper.SafeWriteConfigAs(defaultPath)
viper.ReadInConfig()
cobra.CheckErr(err)
}
Expand Down

0 comments on commit 317a42c

Please # to comment.