3
0

Make env file loading more stable

This commit is contained in:
Denis Arh
2021-06-28 11:54:30 +02:00
parent 744bb70548
commit a94e39b393
2 changed files with 25 additions and 5 deletions

View File

@@ -20,10 +20,14 @@ func (app *CortezaApp) InitCLI() {
// path to all environmental files (or locations with .env file)
// filled from flag values
envs = []string{"."}
envs []string
)
app.Command = cli.RootCommand(func() error {
if len(envs) == 0 {
envs = []string{"."}
}
if err := cli.LoadEnv(envs...); err != nil {
return fmt.Errorf("failed to load environmental variables: %w", err)
}

View File

@@ -11,18 +11,34 @@ import (
// LoadEnv loads env-variables (KEY=VAL) from provided files and paths (by searching for .env file in the given path)
//
// Please not that loaded values DO NOT OVERRIDE the existing environmental variables
// Please note that loaded values
// DO NOT OVERRIDE the existing
// environmental variables
func LoadEnv(pp ...string) error {
// preparse the input and try to figure out if .env should be appended
for i, p := range pp {
var checked = make([]string, 0, len(pp))
for _, p := range pp {
if s, err := os.Stat(p); err != nil {
return err
} else if s.IsDir() {
pp[i] = path.Join(p, ".env")
//pp[i] = path.Join(p, ".env")
chk := path.Join(p, ".env")
if _, err = os.Stat(chk); err == nil {
// make sure only .env files
checked = append(checked, chk)
} else if err != os.ErrNotExist {
return err
}
} else {
checked = append(checked, p)
}
}
return godotenv.Load(pp...)
if len(checked) == 0 {
return nil
}
return godotenv.Load(checked...)
}
// EnvCommand outputs all loaded env variables