Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refs #189: set config dir based on XDG Base Directory Specification #220

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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")
}