diff --git a/util/home.go b/util/home.go index 93c99d6ff..681df04c2 100644 --- a/util/home.go +++ b/util/home.go @@ -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 @@ -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 diff --git a/util/home_test.go b/util/home_test.go index ea0ac56f6..bc3cf0120 100644 --- a/util/home_test.go +++ b/util/home_test.go @@ -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 {