Skip to content

Commit 3d9b579

Browse files
committed
memfs: more portable file handling; test relative RemoveAll
* test: add test passing a relative path to RemoveAll. * memfs: simplify isInDir code using path package.
1 parent 88d08ca commit 3d9b579

File tree

2 files changed

+39
-8
lines changed

2 files changed

+39
-8
lines changed

memfs/memory.go

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"fmt"
77
"io"
88
"os"
9+
"path"
910
"path/filepath"
1011
"strings"
1112
"time"
@@ -392,15 +393,18 @@ func isWriteOnly(flag int) bool {
392393
return flag&os.O_WRONLY != 0
393394
}
394395

395-
func isInDir(dir, path string) bool {
396-
p, err := filepath.Rel(dir, path)
397-
if err != nil {
398-
return false
399-
}
396+
func isInDir(dir, other string) bool {
397+
dir = path.Clean(dir)
398+
dir = toTrailingSlash(dir)
399+
other = path.Clean(other)
400+
401+
return strings.HasPrefix(other, dir)
402+
}
400403

401-
if p == "." || p == ".." {
402-
return false
404+
func toTrailingSlash(p string) string {
405+
if strings.HasSuffix(p, "/") {
406+
return p
403407
}
404408

405-
return !strings.HasPrefix(p, "../")
409+
return p + "/"
406410
}

test/fs_suite.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,3 +542,30 @@ func (s *FilesystemSuite) TestRemoveAll(c *C) {
542542
c.Assert(os.IsNotExist(err), Equals, true, comment)
543543
}
544544
}
545+
546+
func (s *FilesystemSuite) TestRemoveAllRelative(c *C) {
547+
fnames := []string{
548+
"foo/1",
549+
"foo/2",
550+
"foo/bar/1",
551+
"foo/bar/2",
552+
"foo/bar/baz/1",
553+
"foo/bar/baz/qux/1",
554+
"foo/bar/baz/qux/2",
555+
"foo/bar/baz/qux/3",
556+
}
557+
558+
for _, fname := range fnames {
559+
f, err := s.Fs.Create(fname)
560+
c.Assert(err, IsNil)
561+
c.Assert(f.Close(), IsNil)
562+
}
563+
564+
c.Assert(RemoveAll(s.Fs, "foo/bar/.."), IsNil)
565+
566+
for _, fname := range fnames {
567+
_, err := s.Fs.Stat(fname)
568+
comment := Commentf("not removed: %s %s", fname, err)
569+
c.Assert(os.IsNotExist(err), Equals, true, comment)
570+
}
571+
}

0 commit comments

Comments
 (0)