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) + } +}