Skip to content

Commit

Permalink
Do not rewrite ~ (#2496)
Browse files Browse the repository at this point in the history
* Do not rewrite ~

Fixes #2083

RELEASE_NOTES=[ENHANCEMENT] Do not rewrite ~.

Signed-off-by: Dominik Schulz <dominik.schulz@gauner.org>

* Honor GOPASS_HOMEDIR

Signed-off-by: Dominik Schulz <dominik.schulz@gauner.org>

Signed-off-by: Dominik Schulz <dominik.schulz@gauner.org>
  • Loading branch information
dominikschulz authored Dec 28, 2022
1 parent f63c2d1 commit 1ba67f7
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 21 deletions.
15 changes: 5 additions & 10 deletions pkg/fsutil/fsutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"io"
"math/rand"
"os"
"os/user"
"path/filepath"
"regexp"
"strings"
Expand All @@ -26,20 +25,16 @@ func CleanFilename(in string) string {

// CleanPath resolves common aliases in a path and cleans it as much as possible.
func CleanPath(path string) string {
// http://stackoverflow.com/questions/17609732/expand-tilde-to-home-directory
// TODO(GH-2083): We should consider if we really want to rewrite ~
// 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.
if len(path) > 1 && path[:2] == "~/" {
usr, _ := user.Current()
dir := usr.HomeDir

if hd := os.Getenv("GOPASS_HOMEDIR"); hd != "" {
dir = hd
return filepath.Clean(hd + path[2:])
}

path = strings.Replace(path, "~/", dir+"/", 1)
}

if p, err := filepath.Abs(path); err == nil {
if p, err := filepath.Abs(path); err == nil && !strings.HasPrefix(path, "~") {
return p
}

Expand Down
23 changes: 12 additions & 11 deletions pkg/fsutil/fsutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,9 @@ import (
"crypto/rand"
"io/ioutil"
"os"
"os/user"
"path/filepath"
"runtime"
"strings"
"testing"

"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -34,21 +35,21 @@ func TestCleanPath(t *testing.T) {
"/home/user/../bob/.password-store": "/home/bob/.password-store",
"/home/user//.password-store": "/home/user/.password-store",
tempdir + "/foo.gpg": tempdir + "/foo.gpg",
}

usr, err := user.Current()
if err == nil {
hd := usr.HomeDir
if gph := os.Getenv("GOPASS_HOMEDIR"); gph != "" {
hd = gph
}

m["~/.password-store"] = hd + "/.password-store"
"~/.password-store": "~/.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
}
// filepath.Abs turns /home/bob into C:\home\bob on Windows
absOut, err := filepath.Abs(out)
assert.NoError(t, err)
Expand Down

0 comments on commit 1ba67f7

Please sign in to comment.