Skip to content

Commit

Permalink
util: fix TempDir and TempFile on non-root filesystems
Browse files Browse the repository at this point in the history
  • Loading branch information
mcuadros committed May 2, 2021
1 parent af7e4ac commit 3bf3fe5
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 4 deletions.
14 changes: 11 additions & 3 deletions util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,8 @@ func nextSuffix() string {
// to remove the file when no longer needed.
func TempFile(fs billy.Basic, dir, prefix string) (f billy.File, err error) {
// This implementation is based on stdlib ioutil.TempFile.

if dir == "" {
dir = os.TempDir()
dir = getTempDir(fs)
}

nconflict := 0
Expand Down Expand Up @@ -179,7 +178,7 @@ func TempDir(fs billy.Dir, dir, prefix string) (name string, err error) {
// This implementation is based on stdlib ioutil.TempDir

if dir == "" {
dir = os.TempDir()
dir = getTempDir(fs.(billy.Basic))
}

nconflict := 0
Expand Down Expand Up @@ -207,6 +206,15 @@ func TempDir(fs billy.Dir, dir, prefix string) (name string, err error) {
return
}

func getTempDir(fs billy.Basic) string {
ch, ok := fs.(billy.Chroot)
if !ok || ch.Root() == "" || ch.Root() == "/" || ch.Root() == string(filepath.Separator) {
return os.TempDir()
}

return ".tmp"
}

type underlying interface {
Underlying() billy.Basic
}
Expand Down
29 changes: 28 additions & 1 deletion util/util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func TestTempFile(t *testing.T) {
}
}

func TestTempDir(t *testing.T) {
func TestTempDir_WithDir(t *testing.T) {
fs := memfs.New()

dir := os.TempDir()
Expand Down Expand Up @@ -62,3 +62,30 @@ func TestReadFile(t *testing.T) {
}

}

func TestTempDir(t *testing.T) {
fs := memfs.New()
f, err := util.TempDir(fs, "", "")
if err != nil {
t.Fatal(err)
}

_, err = filepath.Rel(os.TempDir(), f)
if err != nil {
t.Errorf(`TempDir(fs, "", "") = %s, should be relative to os.TempDir if root filesystem`, f)
}
}

func TestTempDir_WithNonRoot(t *testing.T) {
fs := memfs.New()
fs, _ = fs.Chroot("foo")
f, err := util.TempDir(fs, "", "")
if err != nil {
t.Fatal(err)
}

_, err = filepath.Rel(os.TempDir(), f)
if err == nil {
t.Errorf(`TempDir(fs, "", "") = %s, should not be relative to os.TempDir on not root filesystem`, f)
}
}

0 comments on commit 3bf3fe5

Please sign in to comment.