Skip to content

Commit

Permalink
Fix environment variable expansion in absPathify
Browse files Browse the repository at this point in the history
- Don't expand user home directory for variable names that simply have a
  HOME prefix;
- Support expansion of variables not followed by the path separator.
  • Loading branch information
biochimia authored and sagikazarmark committed Jul 31, 2020
1 parent 13494e8 commit ce53404
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 2 deletions.
14 changes: 12 additions & 2 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,13 +91,23 @@ func insensitiviseMap(m map[string]interface{}) {
func absPathify(inPath string) string {
jww.INFO.Println("Trying to resolve absolute path to", inPath)

if strings.HasPrefix(inPath, "$HOME") {
if strings.HasPrefix(inPath, "$HOME") &&
(len(inPath) == 5 || inPath[5] == os.PathSeparator) {
inPath = userHomeDir() + inPath[5:]
}

if strings.HasPrefix(inPath, "$") {
end := strings.Index(inPath, string(os.PathSeparator))
inPath = os.Getenv(inPath[1:end]) + inPath[end:]

var value, suffix string
if end == -1 {
value = os.Getenv(inPath[1:])
} else {
value = os.Getenv(inPath[1:end])
suffix = inPath[end:]
}

inPath = value + suffix
}

if filepath.IsAbs(inPath) {
Expand Down
37 changes: 37 additions & 0 deletions util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
package viper

import (
"os"
"path/filepath"
"reflect"
"testing"
)
Expand Down Expand Up @@ -52,3 +54,38 @@ func TestCopyAndInsensitiviseMap(t *testing.T) {
t.Fatal("Input map changed")
}
}

func TestAbsPathify(t *testing.T) {
home := userHomeDir()
homer := filepath.Join(home, "homer")
wd, _ := os.Getwd()

os.Setenv("HOMER_ABSOLUTE_PATH", homer)
os.Setenv("VAR_WITH_RELATIVE_PATH", "relative")

tests := []struct {
input string
output string
}{
{"", wd},
{"sub", filepath.Join(wd, "sub")},
{"./", wd},
{"./sub", filepath.Join(wd, "sub")},
{"$HOME", home},
{"$HOME/", home},
{"$HOME/sub", filepath.Join(home, "sub")},
{"$HOMER_ABSOLUTE_PATH", homer},
{"$HOMER_ABSOLUTE_PATH/", homer},
{"$HOMER_ABSOLUTE_PATH/sub", filepath.Join(homer, "sub")},
{"$VAR_WITH_RELATIVE_PATH", filepath.Join(wd, "relative")},
{"$VAR_WITH_RELATIVE_PATH/", filepath.Join(wd, "relative")},
{"$VAR_WITH_RELATIVE_PATH/sub", filepath.Join(wd, "relative", "sub")},
}

for _, test := range tests {
got := absPathify(test.input)
if got != test.output {
t.Errorf("Got %v\nexpected\n%q", got, test.output)
}
}
}

0 comments on commit ce53404

Please sign in to comment.