Skip to content

Commit

Permalink
split env file loading to separate function
Browse files Browse the repository at this point in the history
  • Loading branch information
suttod committed Jun 21, 2023
1 parent 64ce431 commit 184d6db
Showing 1 changed file with 13 additions and 18 deletions.
31 changes: 13 additions & 18 deletions cobrautil.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package cobrautil

import (
"fmt"
"os"
"strings"

"github.com/joho/godotenv"
Expand All @@ -23,21 +22,6 @@ func IsBuiltinCommand(cmd *cobra.Command) bool {
)
}

// Read dotenv files according to conventions
func ReadDotEnv(prefix string) {
env := os.Getenv(prefix + "_ENV")
if env == "" {
env = "development"
}

godotenv.Load(".env." + env + ".local")
if env != "test" {
godotenv.Load(".env.local")
}
godotenv.Load(".env." + env)
godotenv.Load() // The Original .env
}

// SyncViperPreRunE returns a Cobra run func that synchronizes Viper environment
// flags prefixed with the provided argument.
//
Expand All @@ -49,8 +33,6 @@ func SyncViperPreRunE(prefix string) CobraRunFunc {
return nil // No-op for builtins
}

ReadDotEnv(prefix)

v := viper.New()
v.AllowEmptyEnv(true)
viper.SetEnvPrefix(prefix)
Expand All @@ -69,6 +51,19 @@ func SyncViperPreRunE(prefix string) CobraRunFunc {
}
}

// SyncViperPreRunEWithFiles returns a Cobra run func that synchronizes
// Viper environment flags prefixed with the provided argument.
//
// If envfile is not an empty string, it should contain a path of a dotenv file.
// Viper will load environment variables from file with lower precedence,
// than env of the process.
func SyncViperPreRunEWithFile(prefix string, envfile string) CobraRunFunc {
if envfile != "" {
godotenv.Load(envfile)
}
return SyncViperPreRunE(prefix)
}

// CobraRunFunc is the signature of cobra.Command RunFuncs.
type CobraRunFunc func(cmd *cobra.Command, args []string) error

Expand Down

0 comments on commit 184d6db

Please sign in to comment.