Skip to content

Commit 324f628

Browse files
committed
util: fix TempDir and TempFile on non-root filesystems
1 parent af7e4ac commit 324f628

File tree

2 files changed

+39
-4
lines changed

2 files changed

+39
-4
lines changed

util/util.go

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,8 @@ func nextSuffix() string {
146146
// to remove the file when no longer needed.
147147
func TempFile(fs billy.Basic, dir, prefix string) (f billy.File, err error) {
148148
// This implementation is based on stdlib ioutil.TempFile.
149-
150149
if dir == "" {
151-
dir = os.TempDir()
150+
dir = getTempDir(fs)
152151
}
153152

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

181180
if dir == "" {
182-
dir = os.TempDir()
181+
dir = getTempDir(fs.(billy.Basic))
183182
}
184183

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

209+
func getTempDir(fs billy.Basic) string {
210+
ch, ok := fs.(billy.Chroot)
211+
if !ok || ch.Root() == "" || ch.Root() == "/" {
212+
return os.TempDir()
213+
}
214+
215+
return ".tmp"
216+
}
217+
210218
type underlying interface {
211219
Underlying() billy.Basic
212220
}

util/util_test.go

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ func TestTempFile(t *testing.T) {
2525
}
2626
}
2727

28-
func TestTempDir(t *testing.T) {
28+
func TestTempDir_WithDir(t *testing.T) {
2929
fs := memfs.New()
3030

3131
dir := os.TempDir()
@@ -62,3 +62,30 @@ func TestReadFile(t *testing.T) {
6262
}
6363

6464
}
65+
66+
func TestTempDir(t *testing.T) {
67+
fs := memfs.New()
68+
f, err := util.TempDir(fs, "", "")
69+
if err != nil {
70+
t.Fatal(err)
71+
}
72+
73+
_, err = filepath.Rel(os.TempDir(), f)
74+
if err != nil {
75+
t.Errorf(`TempDir(fs, "", "") = %s, should be relative to os.TempDir if root filesystem`, f)
76+
}
77+
}
78+
79+
func TestTempDir_WithNonRoot(t *testing.T) {
80+
fs := memfs.New()
81+
fs, _ = fs.Chroot("foo")
82+
f, err := util.TempDir(fs, "", "")
83+
if err != nil {
84+
t.Fatal(err)
85+
}
86+
87+
_, err = filepath.Rel(os.TempDir(), f)
88+
if err == nil {
89+
t.Errorf(`TempDir(fs, "", "") = %s, should not be relative to os.TempDir on not root filesystem`, f)
90+
}
91+
}

0 commit comments

Comments
 (0)