Skip to content

Commit

Permalink
memfs: more portable file handling; test relative RemoveAll
Browse files Browse the repository at this point in the history
* test: add test passing a relative path to RemoveAll.

* memfs: simplify isInDir code using path package.
  • Loading branch information
smola committed Feb 20, 2017
1 parent 88d08ca commit 3d9b579
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 8 deletions.
20 changes: 12 additions & 8 deletions memfs/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"io"
"os"
"path"
"path/filepath"
"strings"
"time"
Expand Down Expand Up @@ -392,15 +393,18 @@ func isWriteOnly(flag int) bool {
return flag&os.O_WRONLY != 0
}

func isInDir(dir, path string) bool {
p, err := filepath.Rel(dir, path)
if err != nil {
return false
}
func isInDir(dir, other string) bool {
dir = path.Clean(dir)
dir = toTrailingSlash(dir)
other = path.Clean(other)

return strings.HasPrefix(other, dir)
}

if p == "." || p == ".." {
return false
func toTrailingSlash(p string) string {
if strings.HasSuffix(p, "/") {
return p
}

return !strings.HasPrefix(p, "../")
return p + "/"
}
27 changes: 27 additions & 0 deletions test/fs_suite.go
Original file line number Diff line number Diff line change
Expand Up @@ -542,3 +542,30 @@ func (s *FilesystemSuite) TestRemoveAll(c *C) {
c.Assert(os.IsNotExist(err), Equals, true, comment)
}
}

func (s *FilesystemSuite) TestRemoveAllRelative(c *C) {
fnames := []string{
"foo/1",
"foo/2",
"foo/bar/1",
"foo/bar/2",
"foo/bar/baz/1",
"foo/bar/baz/qux/1",
"foo/bar/baz/qux/2",
"foo/bar/baz/qux/3",
}

for _, fname := range fnames {
f, err := s.Fs.Create(fname)
c.Assert(err, IsNil)
c.Assert(f.Close(), IsNil)
}

c.Assert(RemoveAll(s.Fs, "foo/bar/.."), IsNil)

for _, fname := range fnames {
_, err := s.Fs.Stat(fname)
comment := Commentf("not removed: %s %s", fname, err)
c.Assert(os.IsNotExist(err), Equals, true, comment)
}
}

0 comments on commit 3d9b579

Please sign in to comment.