6
0
mirror of https://github.com/grdl/git-get.git synced 2026-02-10 07:54:28 +00:00

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
This commit is contained in:
Grzegorz Dlugoszewski
2020-06-04 13:02:24 +02:00
parent 7d2c9b1954
commit f4636a3a73
2 changed files with 12 additions and 10 deletions

View File

@@ -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)

View File

@@ -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)) == ""
}