From 324f6288c6056aed88862b51dfd0b4e934adfc3e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?M=C3=A1ximo=20Cuadros?= Date: Mon, 3 May 2021 00:55:10 +0200 Subject: [PATCH] util: fix TempDir and TempFile on non-root filesystems --- util/util.go | 14 +++++++++++--- util/util_test.go | 29 ++++++++++++++++++++++++++++- 2 files changed, 39 insertions(+), 4 deletions(-) diff --git a/util/util.go b/util/util.go index dcddb18..9d1a82f 100644 --- a/util/util.go +++ b/util/util.go @@ -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 @@ -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 @@ -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() == "/" { + return os.TempDir() + } + + return ".tmp" +} + type underlying interface { Underlying() billy.Basic } diff --git a/util/util_test.go b/util/util_test.go index 8fd2f8b..a3c73e1 100644 --- a/util/util_test.go +++ b/util/util_test.go @@ -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() @@ -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) + } +}