From f4636a3a738c8a2a870534ea96a8b18d17fd23cb Mon Sep 17 00:00:00 2001 From: Grzegorz Dlugoszewski Date: Thu, 4 Jun 2020 13:02:24 +0200 Subject: [PATCH] Fix reading config values from cli flags * InitConfig needs to be called after cmd.Execute, otherwise the flags are not parsed yet * Values need to be checked also for emptiness, not only for being unset --- cmd/git-get/main.go | 12 ++++-------- pkg/config.go | 10 ++++++++-- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/cmd/git-get/main.go b/cmd/git-get/main.go index 7b7be8c..96e49d4 100644 --- a/cmd/git-get/main.go +++ b/cmd/git-get/main.go @@ -24,20 +24,16 @@ var cmd = &cobra.Command{ } var list bool -var reposRoot string func init() { - // pkg.LoadConf() - cmd.PersistentFlags().BoolVarP(&list, "list", "l", false, "Lists all repositories inside git-get root") - cmd.PersistentFlags().StringVarP(&reposRoot, "reposRoot", "r", "", "repos root") - viper.BindPFlag("reposRoot", cmd.PersistentFlags().Lookup("reposRoot")) - - pkg.InitConfig() - + cmd.PersistentFlags().StringP(pkg.KeyReposRoot, "r", "", "repos root") + viper.BindPFlag(pkg.KeyReposRoot, cmd.PersistentFlags().Lookup(pkg.KeyReposRoot)) } func Run(cmd *cobra.Command, args []string) { + pkg.InitConfig() + if list { paths, err := pkg.FindRepos() exitIfError(err) diff --git a/pkg/config.go b/pkg/config.go index 07cb927..907ebd9 100644 --- a/pkg/config.go +++ b/pkg/config.go @@ -25,6 +25,8 @@ type gitconfig struct { // InitConfig initializes viper config registry. Values are looked up in the following order: cli flag, env variable, gitconfig file, default value // Viper doesn't support gitconfig file format so it can't find missing values there automatically. They need to be specified in setMissingValues func. +// +// Because it reads the cli flags it needs to be called after the cmd.Execute(). func InitConfig() { viper.SetEnvPrefix(strings.ToUpper(GitgetPrefix)) viper.AutomaticEnv() @@ -47,11 +49,11 @@ func loadGitconfig() *gitconfig { // setMissingValues checks if config values are provided by flags or env vars. If not, it tries loading them from gitconfig file. // If that fails, the default values are used. func setMissingValues(cfg *gitconfig) { - if !viper.IsSet(KeyReposRoot) { + if isUnsetOrEmpty(KeyReposRoot) { viper.Set(KeyReposRoot, cfg.get(KeyReposRoot, path.Join(home(), DefReposRoot))) } - if !viper.IsSet(KeyDefaultHost) { + if isUnsetOrEmpty(KeyDefaultHost) { viper.Set(KeyDefaultHost, cfg.get(KeyDefaultHost, DefDefaultHost)) } } @@ -98,3 +100,7 @@ func home() string { return home } + +func isUnsetOrEmpty(key string) bool { + return !viper.IsSet(key) || strings.TrimSpace(viper.GetString(key)) == "" +}