From 9db46a5669932ec638dff8d2ff867466790aab00 Mon Sep 17 00:00:00 2001 From: Marco Vito Moscaritolo Date: Mon, 12 Nov 2018 22:10:43 +0100 Subject: [PATCH] refs #189: set config dir based on XDG Base Directory Specification --- cmd/root.go | 51 +++++++++++++++++++++++++++++++-------------------- 1 file changed, 31 insertions(+), 20 deletions(-) diff --git a/cmd/root.go b/cmd/root.go index 1f35e71a..9c78398b 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -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") } @@ -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") +}