Skip to content

Commit

Permalink
[BUGFIX] Replace ~ with user homedir if $GOPASS_HOMEDIR is not set (#…
Browse files Browse the repository at this point in the history
…2961)

Replace `~` with user home directory if `$GOPASS_HOMEDIR` is not set, does not replace `~` if neither are set.

Fixes #2916

Signed-off-by: Callum Andrew <contact@candrew.net>
  • Loading branch information
Callum Andrew authored Oct 7, 2024
1 parent 61f23ff commit 9797b87
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 9 deletions.
10 changes: 7 additions & 3 deletions pkg/fsutil/fsutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,17 @@ func ExpandHomedir(path string) string {

// CleanPath resolves common aliases in a path and cleans it as much as possible.
func CleanPath(path string) string {
// Only replace ~ if GOPASS_HOMEDIR is set. In that case we do expect any reference
// to the users homedir to be replaced by the value of GOPASS_HOMEDIR. This is mainly
// for testing and experiments. In all other cases we do want to leave ~ as-is.
// Replace ~ with GOPASS_HOMEDIR if set (mainly for testing and experiments),
// otherwise replace ~ with user's homedir if set. We expect any reference
// to the user's homedir to be replaced with one of these two values.
if len(path) > 1 && path[:2] == "~/" {
if hd := os.Getenv("GOPASS_HOMEDIR"); hd != "" {
return filepath.Clean(hd + path[2:])
}

if home, err := os.UserHomeDir(); err == nil {
return filepath.Clean(home + path[1:])
}
}

if p, err := filepath.Abs(path); err == nil && !strings.HasPrefix(path, "~") {
Expand Down
12 changes: 6 additions & 6 deletions pkg/fsutil/fsutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"crypto/rand"
"os"
"path/filepath"
"runtime"
"strings"
"testing"

Expand All @@ -30,22 +29,23 @@ func TestCleanPath(t *testing.T) {
tempdir := t.TempDir()
t.Setenv("GOPASS_HOMEDIR", "")

home, err := os.UserHomeDir()
if err != nil {
home = "~"
}

m := map[string]string{
".": "",
"/home/user/../bob/.password-store": "/home/bob/.password-store",
"/home/user//.password-store": "/home/user/.password-store",
tempdir + "/foo.gpg": tempdir + "/foo.gpg",
"~/.password-store": "~/.password-store",
"~/.password-store": home + "/.password-store",
}

for in, out := range m {
got := CleanPath(in)

if strings.HasPrefix(out, "~") {
// skip these tests on windows
if runtime.GOOS == "windows" {
continue
}
assert.Equal(t, out, got)

continue
Expand Down

0 comments on commit 9797b87

Please sign in to comment.