From 99c00780f635f8a5f231077c687da73787ebc63c Mon Sep 17 00:00:00 2001 From: jynychen Date: Thu, 29 Aug 2019 23:55:06 +0800 Subject: [PATCH] Support search `.env` or other dotfiles in path --- viper.go | 6 ++---- viper_test.go | 59 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/viper.go b/viper.go index 5133de7..2cf9956 100644 --- a/viper.go +++ b/viper.go @@ -1820,10 +1820,8 @@ func (v *Viper) SetFs(fs afero.Fs) { // Does not include extension. func SetConfigName(in string) { v.SetConfigName(in) } func (v *Viper) SetConfigName(in string) { - if in != "" { - v.configName = in - v.configFile = "" - } + v.configFile = "" + v.configName = in } // SetConfigType sets the type of the configuration returned by the diff --git a/viper_test.go b/viper_test.go index 592551c..95cb96d 100644 --- a/viper_test.go +++ b/viper_test.go @@ -1749,6 +1749,65 @@ func TestWatchFile(t *testing.T) { } +// make .env for testing +func initDotEnvFile(t *testing.T) (string, func()) { + + root, err := ioutil.TempDir("", "") + + cleanup := true + defer func() { + if cleanup { + os.Chdir("..") + os.RemoveAll(root) + } + }() + + assert.Nil(t, err) + + err = os.Chdir(root) + assert.Nil(t, err) + + configfile := ".env" + + err = ioutil.WriteFile( + path.Join(root, configfile), + dotenvWriteExpected, + 0640, + ) + assert.Nil(t, err) + + cleanup = false + return root, func() { + os.Chdir("..") + os.RemoveAll(root) + } +} + +func TestFindDotEnvFile(t *testing.T) { + v := New() + v.SetConfigType("env") + err := v.ReadConfig(bytes.NewBuffer(dotenvWriteExpected)) + if err != nil { + t.Fatal(err) + } + + root, cleanup := initDotEnvFile(t) + defer cleanup() + + v2 := New() + v2.AddConfigPath(root) + v2.SetConfigName("") + v2.SetConfigType("env") + err = v2.ReadInConfig() + if err != nil { + t.Fatal(err) + } + + assert.Equal(t, v.GetString("title"), v2.GetString("title")) + assert.Equal(t, v.GetString("type"), v2.GetString("type")) + assert.Equal(t, v.GetString("kind"), v2.GetString("kind")) +} + func BenchmarkGetBool(b *testing.B) { key := "BenchmarkGetBool" v = New()