util: Expanding home directory should preserve trailing slash

Because we consider slashes as a directory identifier when needed.
This commit is contained in:
James Shubin
2024-09-26 12:29:43 -04:00
parent 6419f931ee
commit 13fc711657
2 changed files with 13 additions and 5 deletions

View File

@@ -39,14 +39,19 @@ import (
"github.com/purpleidea/mgmt/util/errwrap" "github.com/purpleidea/mgmt/util/errwrap"
) )
// ExpandHome does an expansion of ~/ or ~james/ into user's home dir value. // ExpandHome does an expansion of ~/ or ~james/ into user's home dir value. If
// the input path ends in a slash, the result does too.
func ExpandHome(p string) (string, error) { func ExpandHome(p string) (string, error) {
suffix := "" // If it the input ends with a slash, so should the output.
if strings.HasSuffix(p, "/") {
suffix = "/"
}
if strings.HasPrefix(p, "~/") { if strings.HasPrefix(p, "~/") {
usr, err := user.Current() usr, err := user.Current()
if err != nil { if err != nil {
return p, fmt.Errorf("can't expand ~ into home directory") return p, fmt.Errorf("can't expand ~ into home directory")
} }
return path.Join(usr.HomeDir, p[len("~/"):]), nil return path.Join(usr.HomeDir, p[len("~/"):]) + suffix, nil
} }
// check if provided path is in format ~username and keep track of provided username // check if provided path is in format ~username and keep track of provided username
@@ -60,7 +65,7 @@ func ExpandHome(p string) (string, error) {
if err != nil { if err != nil {
return p, fmt.Errorf("can't expand %s into home directory", match[0]) return p, fmt.Errorf("can't expand %s into home directory", match[0])
} }
return path.Join(usr.HomeDir, p[len(match[0]):]), nil return path.Join(usr.HomeDir, p[len(match[0]):]) + suffix, nil
} }
return p, nil return p, nil

View File

@@ -42,11 +42,14 @@ func TestExpandHome(t *testing.T) {
path string path string
expanded string expanded string
}{ }{
// If it the input ends with a slash, so should the output.
{"/some/random/path", "/some/random/path"}, {"/some/random/path", "/some/random/path"},
{"~/", usr.HomeDir}, {"~/", usr.HomeDir + "/"},
{"~/some/path", usr.HomeDir + "/some/path"}, {"~/some/path", usr.HomeDir + "/some/path"},
{"~" + usr.Username + "/", usr.HomeDir}, {"~/some/path/", usr.HomeDir + "/some/path/"},
{"~" + usr.Username + "/", usr.HomeDir + "/"},
{"~" + usr.Username + "/some/path", usr.HomeDir + "/some/path"}, {"~" + usr.Username + "/some/path", usr.HomeDir + "/some/path"},
{"~" + usr.Username + "/some/path/", usr.HomeDir + "/some/path/"},
} }
for _, test := range expandHomeTests { for _, test := range expandHomeTests {