diff --git a/drivers/env/.env b/drivers/env/.env new file mode 100644 index 0000000..e60e20b --- /dev/null +++ b/drivers/env/.env @@ -0,0 +1,3 @@ +ENV_VAR=true + =true +#COMMENTED=true \ No newline at end of file diff --git a/drivers/env/env.go b/drivers/env/env.go index e834215..7d4fd0a 100644 --- a/drivers/env/env.go +++ b/drivers/env/env.go @@ -118,39 +118,29 @@ func (d envDriver) GenDoc(registers ...tinyconf.Registered) string { } func New() (tinyconf.Driver, error) { - err := setENVs() + setENVsFromExecutable() + setENVsFromWD() return envDriver{ name: "env", - }, err + }, nil } -func setENVs() error { - execPath, err := os.Executable() - if err != nil { - return err - } - +func setENVsFromExecutable() { + execPath, _ := os.Executable() envPath := path.Dir(execPath) - wd, err := os.Getwd() - if err != nil { - return err - } - - if err = setENVsFromPath(envPath); err != nil { - return err - } - if err = setENVsFromPath(wd); err != nil { - return err - } + setENVsFromPath(envPath) +} - return nil +func setENVsFromWD() { + wd, _ := os.Getwd() + setENVsFromPath(wd) } -func setENVsFromPath(envDirPath string) error { +func setENVsFromPath(envDirPath string) { envFile, err := os.Open(path.Join(envDirPath, ".env")) if err != nil { - return err + return } fileScanner := bufio.NewScanner(envFile) @@ -165,16 +155,14 @@ func setENVsFromPath(envDirPath string) error { } for _, envLine := range envLines { - e := strings.Split(envLine, "=") - val := "" - if len(e) > 1 { - val = e[1] + envRow := strings.Split(envLine, "=") + envVal := "" + if len(envRow) > 1 { + envVal = envRow[1] } - if err = os.Setenv(e[0], val); err != nil { - return err + if err = os.Setenv(strings.TrimSpace(envRow[0]), envVal); err != nil { + return } } - - return nil } diff --git a/drivers/env/env_test.go b/drivers/env/env_test.go index ca922d7..e9ccdea 100644 --- a/drivers/env/env_test.go +++ b/drivers/env/env_test.go @@ -293,7 +293,36 @@ func BenchmarkEnvDriver_GenDoc(b *testing.B) { } func TestNew(t *testing.T) { - driver, err := New() - assert.NoError(t, err) - assert.NotNil(t, driver) + tests := map[string]struct { + envVarName string + expectedVal string + }{ + "EnvSet": { + "ENV_VAR", + "true", + }, + "EnvNotSet": { + "ENV_NOT_SET", + "", + }, + "EnvCommented": { + "COMMENTED", + "", + }, + "EnvEmpty": { + "", + "", + }, + } + + for name, test := range tests { + t.Run(name, func(t *testing.T) { + driver, err := New() + envVar := os.Getenv(test.envVarName) + + assert.NoError(t, err) + assert.NotNil(t, driver) + assert.Equal(t, test.expectedVal, envVar) + }) + } }