From 86fffbd28ca006896c1369e9f5bc6362eaba4779 Mon Sep 17 00:00:00 2001 From: Benoit Masson Date: Tue, 27 Sep 2016 15:46:53 +0200 Subject: [PATCH] Fix: find() looks into "overrides" first MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit overrides (elements added with Set()) should have highest priority, checked first (was after PFlags). From README.md: > Viper uses the following precedence order. Each item takes precedence > over the item below it: > • explicit call to Set > • flag > • env > • config > • key/value store > • default + fix TestBindPFlags() to use a new Viper instance (otherwise, "port" was defined in an earlier test function with Set() and took precedence) --- viper.go | 14 +++++++++++--- viper_test.go | 5 +++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/viper.go b/viper.go index 1d3c7f6..b36048d 100644 --- a/viper.go +++ b/viper.go @@ -759,7 +759,13 @@ func (v *Viper) find(key string) interface{} { // if the requested key is an alias, then return the proper key key = v.realKey(key) - // PFlag Override first + // Set() override first + val, exists = v.override[key] + if exists { + return val + } + + // PFlag override next flag, exists := v.pflags[key] if exists && flag.HasChanged() { switch flag.ValueType() { @@ -787,7 +793,6 @@ func (v *Viper) find(key string) interface{} { return val } } - envkey, exists := v.env[key] if exists { if val = v.getEnv(envkey); val != "" { @@ -795,12 +800,13 @@ func (v *Viper) find(key string) interface{} { } } + // Config file next val, exists = v.config[key] if exists { return val } - // Test for nested config parameter + // test for nested config parameter if strings.Contains(key, v.keyDelim) { path := strings.Split(key, v.keyDelim) @@ -815,11 +821,13 @@ func (v *Viper) find(key string) interface{} { } } + // K/V store next val, exists = v.kvstore[key] if exists { return val } + // Default as last chance val, exists = v.defaults[key] if exists { return val diff --git a/viper_test.go b/viper_test.go index 4c938f7..aa03650 100644 --- a/viper_test.go +++ b/viper_test.go @@ -479,6 +479,7 @@ func TestUnmarshal(t *testing.T) { } func TestBindPFlags(t *testing.T) { + v := New() // create independent Viper object flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError) var testValues = map[string]*string{ @@ -497,7 +498,7 @@ func TestBindPFlags(t *testing.T) { testValues[name] = flagSet.String(name, "", "test") } - err := BindPFlags(flagSet) + err := v.BindPFlags(flagSet) if err != nil { t.Fatalf("error binding flag set, %v", err) } @@ -508,7 +509,7 @@ func TestBindPFlags(t *testing.T) { }) for name, expected := range mutatedTestValues { - assert.Equal(t, expected, Get(name)) + assert.Equal(t, expected, v.Get(name)) } }