Skip to content

Commit

Permalink
util: Expanding home directory should preserve trailing slash
Browse files Browse the repository at this point in the history
Because we consider slashes as a directory identifier when needed.
  • Loading branch information
purpleidea committed Sep 26, 2024
1 parent 6419f93 commit 13fc711
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 5 deletions.
11 changes: 8 additions & 3 deletions util/home.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,19 @@ import (
"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) {
suffix := "" // If it the input ends with a slash, so should the output.
if strings.HasSuffix(p, "/") {
suffix = "/"
}
if strings.HasPrefix(p, "~/") {
usr, err := user.Current()
if err != nil {
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
Expand All @@ -60,7 +65,7 @@ func ExpandHome(p string) (string, error) {
if err != nil {
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
Expand Down
7 changes: 5 additions & 2 deletions util/home_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,14 @@ func TestExpandHome(t *testing.T) {
path string
expanded string
}{
// If it the input ends with a slash, so should the output.
{"/some/random/path", "/some/random/path"},
{"~/", usr.HomeDir},
{"~/", usr.HomeDir + "/"},
{"~/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/"},
}

for _, test := range expandHomeTests {
Expand Down

0 comments on commit 13fc711

Please sign in to comment.