Skip to content

Commit ce53404

Browse files
biochimiasagikazarmark
authored andcommitted
Fix environment variable expansion in absPathify
- 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.
1 parent 13494e8 commit ce53404

File tree

2 files changed

+49
-2
lines changed

2 files changed

+49
-2
lines changed

util.go

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -91,13 +91,23 @@ func insensitiviseMap(m map[string]interface{}) {
9191
func absPathify(inPath string) string {
9292
jww.INFO.Println("Trying to resolve absolute path to", inPath)
9393

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

9899
if strings.HasPrefix(inPath, "$") {
99100
end := strings.Index(inPath, string(os.PathSeparator))
100-
inPath = os.Getenv(inPath[1:end]) + inPath[end:]
101+
102+
var value, suffix string
103+
if end == -1 {
104+
value = os.Getenv(inPath[1:])
105+
} else {
106+
value = os.Getenv(inPath[1:end])
107+
suffix = inPath[end:]
108+
}
109+
110+
inPath = value + suffix
101111
}
102112

103113
if filepath.IsAbs(inPath) {

util_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
package viper
1212

1313
import (
14+
"os"
15+
"path/filepath"
1416
"reflect"
1517
"testing"
1618
)
@@ -52,3 +54,38 @@ func TestCopyAndInsensitiviseMap(t *testing.T) {
5254
t.Fatal("Input map changed")
5355
}
5456
}
57+
58+
func TestAbsPathify(t *testing.T) {
59+
home := userHomeDir()
60+
homer := filepath.Join(home, "homer")
61+
wd, _ := os.Getwd()
62+
63+
os.Setenv("HOMER_ABSOLUTE_PATH", homer)
64+
os.Setenv("VAR_WITH_RELATIVE_PATH", "relative")
65+
66+
tests := []struct {
67+
input string
68+
output string
69+
}{
70+
{"", wd},
71+
{"sub", filepath.Join(wd, "sub")},
72+
{"./", wd},
73+
{"./sub", filepath.Join(wd, "sub")},
74+
{"$HOME", home},
75+
{"$HOME/", home},
76+
{"$HOME/sub", filepath.Join(home, "sub")},
77+
{"$HOMER_ABSOLUTE_PATH", homer},
78+
{"$HOMER_ABSOLUTE_PATH/", homer},
79+
{"$HOMER_ABSOLUTE_PATH/sub", filepath.Join(homer, "sub")},
80+
{"$VAR_WITH_RELATIVE_PATH", filepath.Join(wd, "relative")},
81+
{"$VAR_WITH_RELATIVE_PATH/", filepath.Join(wd, "relative")},
82+
{"$VAR_WITH_RELATIVE_PATH/sub", filepath.Join(wd, "relative", "sub")},
83+
}
84+
85+
for _, test := range tests {
86+
got := absPathify(test.input)
87+
if got != test.output {
88+
t.Errorf("Got %v\nexpected\n%q", got, test.output)
89+
}
90+
}
91+
}

0 commit comments

Comments
 (0)