Skip to content

Commit

Permalink
fix: load multiple env files by convention (#2199)
Browse files Browse the repository at this point in the history
  • Loading branch information
sweatybridge committed Apr 29, 2024
1 parent cecb69b commit 7d81f8a
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions internal/utils/config.go
Expand Up @@ -482,8 +482,8 @@ func LoadConfigFS(fsys afero.Fs) error {
fmt.Fprintf(os.Stderr, "Unknown config fields: %+v\n", undecoded)
}
// Load secrets from .env file
if err := godotenv.Load(); err != nil && !errors.Is(err, os.ErrNotExist) {
return errors.Errorf("failed to load %s: %w", Bold(".env"), err)
if err := loadDefaultEnv(); err != nil {
return err
}
if err := viper.Unmarshal(&Config); err != nil {
return errors.Errorf("failed to parse env to config: %w", err)
Expand Down Expand Up @@ -837,3 +837,28 @@ func RemoveDuplicates(slice []string) (result []string) {
}
return result
}

func loadDefaultEnv() error {
env := viper.GetString("ENV")
if env == "" {
env = "development"
}
filenames := []string{".env." + env + ".local"}
if env != "test" {
filenames = append(filenames, ".env.local")
}
filenames = append(filenames, ".env."+env, ".env")
for _, path := range filenames {
if err := loadEnvIfExists(path); err != nil {
return err
}
}
return nil
}

func loadEnvIfExists(path string) error {
if err := godotenv.Load(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return errors.Errorf("failed to load %s: %w", Bold(".env"), err)
}
return nil
}

0 comments on commit 7d81f8a

Please sign in to comment.