mirror of
https://github.com/spf13/viper
synced 2025-05-11 06:37:27 +00:00
Support search .env
or other dotfiles in path
This commit is contained in:
parent
bd1db6bb8c
commit
435ffae7be
2 changed files with 61 additions and 4 deletions
6
viper.go
6
viper.go
|
@ -1820,10 +1820,8 @@ func (v *Viper) SetFs(fs afero.Fs) {
|
||||||
// Does not include extension.
|
// Does not include extension.
|
||||||
func SetConfigName(in string) { v.SetConfigName(in) }
|
func SetConfigName(in string) { v.SetConfigName(in) }
|
||||||
func (v *Viper) SetConfigName(in string) {
|
func (v *Viper) SetConfigName(in string) {
|
||||||
if in != "" {
|
v.configFile = ""
|
||||||
v.configName = in
|
v.configName = in
|
||||||
v.configFile = ""
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// SetConfigType sets the type of the configuration returned by the
|
// SetConfigType sets the type of the configuration returned by the
|
||||||
|
|
|
@ -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) {
|
func BenchmarkGetBool(b *testing.B) {
|
||||||
key := "BenchmarkGetBool"
|
key := "BenchmarkGetBool"
|
||||||
v = New()
|
v = New()
|
||||||
|
|
Loading…
Add table
Reference in a new issue