Add viper configuration

This commit is contained in:
Jip J. Dekker 2016-11-24 23:55:42 +01:00
parent 8e6bacfc59
commit 0c997b7d63

30
main.go
View File

@ -1,11 +1,15 @@
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var cfgFile string
var rootCmd = &cobra.Command{
Use: "chonozinc [description]",
Short: "Test and time your minizinc models!",
@ -16,8 +20,34 @@ var rootCmd = &cobra.Command{
Run: func(cmd *cobra.Command, args []string) {},
}
// initConfig reads in config file and ENV variables if set.
func initConfig() {
if cfgFile != "" { // enable ability to specify config file via flag
viper.SetConfigFile(cfgFile)
}
viper.SetConfigName("config") // name of config file (without extension)
viper.AddConfigPath("$HOME/.config/chronozinc") // adding home directory as first search path
viper.SetEnvPrefix("czn") // set environment prefix
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err == nil {
fmt.Println("Using config file:", viper.ConfigFileUsed())
} else {
fmt.Println("No config file found; using ENV and defaults")
}
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.test.yaml)")
}