diff --git a/cobrautil.go b/cobrautil.go index 2bed329..ef255a3 100644 --- a/cobrautil.go +++ b/cobrautil.go @@ -4,6 +4,7 @@ import ( "fmt" "strings" + "github.com/joho/godotenv" "github.com/jzelinskie/stringz" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -21,8 +22,8 @@ func IsBuiltinCommand(cmd *cobra.Command) bool { ) } -// SyncViperPreRunE returns a Cobra run func that synchronizes Viper environment -// flags prefixed with the provided argument. +// SyncViperPreRunE returns a CobraRunFunc that synchronizes Viper environment +// flags with the provided prefix. // // Thanks to Carolyn Van Slyck: https://github.com/carolynvs/stingoftheviper func SyncViperPreRunE(prefix string) CobraRunFunc { @@ -50,6 +51,20 @@ func SyncViperPreRunE(prefix string) CobraRunFunc { } } +// SyncViperDotEnvPreRunE returns a CobraRunFunc that loads a .dotenv file +// before synchronizing Viper environment flags with the provided prefix. +// +// If empty, envfilePath defaults to ".env". +// The .dotenv file is loaded first before any additional Viper behavior. +func SyncViperDotEnvPreRunE(prefix string, envfilePath string) CobraRunFunc { + return func(cmd *cobra.Command, args []string) error { + if err := godotenv.Load(stringz.DefaultEmpty(envfilePath, ".env")); err != nil { + return err + } + return SyncViperPreRunE(prefix)(cmd, args) + } +} + // CobraRunFunc is the signature of cobra.Command RunFuncs. type CobraRunFunc func(cmd *cobra.Command, args []string) error diff --git a/go.mod b/go.mod index 9941b1f..34fe32a 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,7 @@ go 1.18 require ( github.com/go-logr/logr v1.2.3 + github.com/joho/godotenv v1.5.1 github.com/jzelinskie/stringz v0.0.1 github.com/mattn/go-isatty v0.0.16 github.com/rs/zerolog v1.28.0 diff --git a/go.sum b/go.sum index 3b48dc2..d45d177 100644 --- a/go.sum +++ b/go.sum @@ -158,6 +158,8 @@ github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1: github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= github.com/jstemmer/go-junit-report v0.0.0-20190106144839-af01ea7f8024/go.mod h1:6v2b51hI/fHJwM22ozAgKL4VKDeJcHhJFhtBdhmNjmU= github.com/jstemmer/go-junit-report v0.9.1/go.mod h1:Brl9GWCQeLvo8nXZwPNNblvFj/XSXhF0NWZEnDohbsk= github.com/jzelinskie/stringz v0.0.1 h1:IahR+y8ct2nyj7B6i8UtFsGFj4ex1SX27iKFYsAheLk=