Skip to content

Commit

Permalink
feat: config: add ParseFlagsAndLoadDotEnv(), DotEnvOpts{}
Browse files Browse the repository at this point in the history
  • Loading branch information
grokify committed Mar 17, 2024
1 parent 8fe5617 commit ff25601
Showing 1 changed file with 17 additions and 40 deletions.
57 changes: 17 additions & 40 deletions config/dotenv.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (

"github.com/grokify/mogo/os/osutil"
"github.com/grokify/mogo/type/slicesutil"
flags "github.com/jessevdk/go-flags"
"github.com/joho/godotenv"
)

Expand Down Expand Up @@ -52,46 +53,6 @@ func LoadDotEnv(paths []string, n int) ([]string, error) {
return loaded, nil
}

/*
func LoadEnvDefaults() error {
envPathsSet := []string{}
for _, defaultPath := range DefaultPaths() {
exists, err := osutil.Exists(defaultPath)
if err == nil && exists {
envPathsSet = append(envPathsSet, defaultPath)
}
}
if len(envPathsSet) > 0 {
return godotenv.Load(envPathsSet...)
}
return godotenv.Load()
}
func LoadDotEnv(paths ...string) ([]string, error) {
return LoadDotEnvSkipEmptyInfo(paths...)
}
func LoadDotEnvSkipEmpty(paths ...string) error {
_, err := LoadDotEnvSkipEmptyInfo(paths...)
return err
}
func LoadDotEnvFirst(paths ...string) error {
if len(paths) == 0 {
paths = DefaultPaths()
}
envPaths := osutil.FilenamesFilterSizeGTZero(paths...)
if len(envPaths) > 0 {
return godotenv.Load(envPaths[0])
}
return nil
}
*/

// GetDotEnvVal retrieves a single var from a `.env` file path
func GetDotEnvVal(envPath, varName string) (string, error) {
cmd := fmt.Sprintf("grep %s '%s' | rev | cut -d= -f1 | rev", varName, envPath)
Expand Down Expand Up @@ -148,3 +109,19 @@ func checkEnvPathsPrioritized(fixedPath, envPath string) (string, error) {
}
return thisDirPath, nil
}

type DotEnvOpts interface {
DotEnvFilename() string
}

func ParseFlagsAndLoadDotEnv(opts DotEnvOpts) error {
_, err := flags.Parse(opts)
if err != nil {
return err
}
if envFilename := opts.DotEnvFilename(); envFilename != "" {
_, err := LoadDotEnv([]string{envFilename}, 1)
return err
}
return nil
}

0 comments on commit ff25601

Please sign in to comment.