# HG changeset patch # User Sascha L. Teichmann # Date 1532449291 -7200 # Node ID 696c19abe869d285d19aea91e99d9f20875defee # Parent 11d1a488b08fe9f9462fe9acba70fd4a6c20c3bf Argh! If one is using its own storage for config like we do the config loaded by viper needs to be injected back into cobra [https://github.com/spf13/cobra/issues/367]. diff -r 11d1a488b08f -r 696c19abe869 cmd/gemma/root.go --- a/cmd/gemma/root.go Tue Jul 24 17:45:17 2018 +0200 +++ b/cmd/gemma/root.go Tue Jul 24 18:21:31 2018 +0200 @@ -14,6 +14,7 @@ "gemma.intevation.de/gemma/config" homedir "github.com/mitchellh/go-homedir" "github.com/spf13/cobra" + "github.com/spf13/pflag" "github.com/spf13/viper" ) @@ -23,10 +24,13 @@ Run: start, } +// This is not part of the persistent config. +var configFile string + func init() { cobra.OnInitialize(initConfig) fl := rootCmd.PersistentFlags - fl().StringVarP(&config.Config.File, "config", "c", "", "config file (default is $HOME/.gemma.toml)") + fl().StringVarP(&configFile, "config", "c", "", "config file (default is $HOME/.gemma.toml)") fl().StringVarP(&config.Config.DBHost, "dbhost", "H", "localhost", "host of the database") fl().UintVarP(&config.Config.DBPort, "dbport", "P", 5432, "port of the database") fl().StringVarP(&config.Config.DBName, "dbname", "d", "gemma", "name of the database") @@ -52,9 +56,9 @@ func initConfig() { // Don't forget to read config either from cfgFile or from home directory! - if config.Config.File != "" { + if configFile != "" { // Use config file from the flag. - viper.SetConfigFile(config.Config.File) + viper.SetConfigFile(configFile) } else { // Find home directory. home, err := homedir.Dir() @@ -68,7 +72,7 @@ viper.SetConfigName(".gemma") } if err := viper.ReadInConfig(); err != nil { - if _, ok := err.(viper.ConfigFileNotFoundError); ok { + if _, ok := err.(viper.ConfigFileNotFoundError); ok && configFile == "" { // Don't bother if not found. return } @@ -76,8 +80,22 @@ } } +func injectViper(cmd *cobra.Command) { + cmd.Flags().VisitAll(func(f *pflag.Flag) { + if !f.Changed { + if viper.IsSet(f.Name) { + cmd.Flags().Set(f.Name, viper.GetString(f.Name)) + } + } + }) +} + func start(cmd *cobra.Command, args []string) { + // XXX: This hack is needed because we have our + // own config storage. + injectViper(cmd) + // Install connection pool cp, err := auth.NewConnectionPool(config.Config.SessionStore) if err != nil { @@ -89,7 +107,6 @@ if err != nil { log.Fatalf("error: %v\n", err) } - log.Printf("web: %s\n", p) mux := http.NewServeMux() mux.Handle("/", http.StripPrefix("/", http.FileServer(http.Dir(p)))) mux.HandleFunc("/api/token", token) diff -r 11d1a488b08f -r 696c19abe869 config/config.go --- a/config/config.go Tue Jul 24 17:45:17 2018 +0200 +++ b/config/config.go Tue Jul 24 18:21:31 2018 +0200 @@ -3,7 +3,6 @@ var Config Configuration type Configuration struct { - File string DBHost string DBPort uint DBName string