From 6912771c399dd9f4781205f2a47c6484e8e1baea Mon Sep 17 00:00:00 2001 From: Chris Lane Date: Thu, 30 Jan 2020 18:19:43 -0500 Subject: [PATCH] chore: refactors `config.Paths` Refactors the reading of multiple envvars out of `config.Paths` in order to facilitate cleaner unit-testing. --- cmd/cheat/main.go | 10 +++++++++- internal/config/paths.go | 19 +++++++++---------- 2 files changed, 18 insertions(+), 11 deletions(-) diff --git a/cmd/cheat/main.go b/cmd/cheat/main.go index 76b9a39..864bbc3 100755 --- a/cmd/cheat/main.go +++ b/cmd/cheat/main.go @@ -6,6 +6,7 @@ import ( "fmt" "os" "runtime" + "strings" "github.com/docopt/docopt-go" @@ -31,8 +32,15 @@ func main() { os.Exit(0) } + // read the envvars into a map of strings + envvars := map[string]string{} + for _, e := range os.Environ() { + pair := strings.SplitN(e, "=", 2) + envvars[pair[0]] = pair[1] + } + // load the os-specifc paths at which the config file may be located - confpaths, err := config.Paths(runtime.GOOS) + confpaths, err := config.Paths(runtime.GOOS, envvars) if err != nil { fmt.Fprintf(os.Stderr, "failed to load config: %v\n", err) os.Exit(1) diff --git a/internal/config/paths.go b/internal/config/paths.go index ab08916..ab246f8 100644 --- a/internal/config/paths.go +++ b/internal/config/paths.go @@ -2,7 +2,6 @@ package config import ( "fmt" - "os" "path" "github.com/mitchellh/go-homedir" @@ -10,13 +9,13 @@ import ( // Paths returns config file paths that are appropriate for the operating // system -func Paths(sys string) ([]string, error) { +func Paths(sys string, envvars map[string]string) ([]string, error) { - // if CHEAT_CONFIG_PATH is set, return it - if os.Getenv("CHEAT_CONFIG_PATH") != "" { + // if CHEAT_CONFIG_PATH is set, expand ~ and return it + if confpath, ok := envvars["CHEAT_CONFIG_PATH"]; ok { // expand ~ - expanded, err := homedir.Expand(os.Getenv("CHEAT_CONFIG_PATH")) + expanded, err := homedir.Expand(confpath) if err != nil { return []string{}, fmt.Errorf("failed to expand ~: %v", err) } @@ -27,14 +26,14 @@ func Paths(sys string) ([]string, error) { switch sys { case "darwin", "linux", "freebsd": return []string{ - path.Join(os.Getenv("XDG_CONFIG_HOME"), "/cheat/conf.yml"), - path.Join(os.Getenv("HOME"), ".config/cheat/conf.yml"), - path.Join(os.Getenv("HOME"), ".cheat/conf.yml"), + path.Join(envvars["XDG_CONFIG_HOME"], "/cheat/conf.yml"), + path.Join(envvars["HOME"], ".config/cheat/conf.yml"), + path.Join(envvars["HOME"], ".cheat/conf.yml"), }, nil case "windows": return []string{ - fmt.Sprintf("%s/cheat/conf.yml", os.Getenv("APPDATA")), - fmt.Sprintf("%s/cheat/conf.yml", os.Getenv("PROGRAMDATA")), + fmt.Sprintf("%s/cheat/conf.yml", envvars["APPDATA"]), + fmt.Sprintf("%s/cheat/conf.yml", envvars["PROGRAMDATA"]), }, nil default: return []string{}, fmt.Errorf("unsupported os: %s", sys)