Skip to content

Commit

Permalink
Merge pull request #220 from mavimo/feature/189-use-xdg-config-home-a…
Browse files Browse the repository at this point in the history
…s-config-base-dir

refs #189: set config dir based on XDG Base Directory Specification
  • Loading branch information
xetys authored Nov 13, 2018
2 parents 82be217 + b37da5b commit 908dcf6
Showing 1 changed file with 31 additions and 20 deletions.
51 changes: 31 additions & 20 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,7 @@ func Execute() {
func init() {
cobra.OnInitialize(initConfig)

// Here you will define your flags and configuration settings.
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.hetzner-kube.yaml)")

// Cobra also supports local flags, which will only run
// when this action is called directly.
// rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file to use")
rootCmd.PersistentFlags().BoolP("debug", "d", false, "debug mode")
}

Expand All @@ -74,23 +67,41 @@ func initConfig() {
// Use config file from the flag.
viper.SetConfigFile(cfgFile)
} else {
// Find home directory.
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
os.Exit(1)
}

// Search config in home directory with name ".hetzner-kube" (without extension).
viper.AddConfigPath(home)
viper.SetConfigName(".hetzner-kube")

setConfigDirectory()
}

viper.AutomaticEnv() // read in environment variables that match
// read in environment variables that match
viper.AutomaticEnv()

// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
}
}

func setConfigDirectory() {
// Find config dir based on XDG Base Directory Specification
// https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
xdgConfig := os.Getenv("XDG_CONFIG_HOME")
if xdgConfig != "" {
viper.AddConfigPath(xdgConfig)
}

// Failback to home directory
home, err := homedir.Dir()
if err != nil {
fmt.Println(err)
}

if err == nil {
viper.AddConfigPath(home)
}

if xdgConfig == "" && err != nil {
fmt.Println("Unable to detect any config location, please specify it with --config flag")
os.Exit(1)
}

// Search config directory with name ".hetzner-kube" (without extension).
viper.SetConfigName(".hetzner-kube")
}

0 comments on commit 908dcf6

Please sign in to comment.