From 7f5b583ff1789b39bf3d4f0f51cc456e2f77fcc4 Mon Sep 17 00:00:00 2001 From: spf13 Date: Wed, 25 Jun 2014 17:23:00 -0400 Subject: [PATCH] Handle $HOME and other environment variables in paths --- viper.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/viper.go b/viper.go index 737c0ff..e88dec9 100644 --- a/viper.go +++ b/viper.go @@ -14,6 +14,7 @@ import ( "os" "path" "path/filepath" + "runtime" "strings" "time" @@ -368,8 +369,29 @@ func stringInSlice(a string, list []string) bool { return false } +func userHomeDir() string { + if runtime.GOOS == "windows" { + home := os.Getenv("HOMEDRIVE") + os.Getenv("HOMEPATH") + if home == "" { + home = os.Getenv("USERPROFILE") + } + return home + } + return os.Getenv("HOME") +} + func absPathify(inPath string) string { jww.INFO.Println("Trying to resolve absolute path to", inPath) + + if strings.HasPrefix(inPath, "$HOME") { + inPath = userHomeDir() + inPath[5:] + } + + if strings.HasPrefix(inPath, "$") { + end := strings.Index(inPath, string(os.PathSeparator)) + inPath = os.Getenv(inPath[1:end]) + inPath[end:] + } + if filepath.IsAbs(inPath) { return filepath.Clean(inPath) }