Skip to content

Commit

Permalink
Fix #12, MemFS ReadDir sorted by filename
Browse files Browse the repository at this point in the history
  • Loading branch information
Perez Domingo, Victor committed Jan 17, 2021
1 parent d7a8afc commit 66bd067
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
9 changes: 9 additions & 0 deletions memfs/memory.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"io"
"os"
"path/filepath"
"sort"
"strings"
"time"

Expand Down Expand Up @@ -117,6 +118,12 @@ func (fs *Memory) Lstat(filename string) (os.FileInfo, error) {
return f.Stat()
}

type ByName []os.FileInfo

func (a ByName) Len() int { return len(a) }
func (a ByName) Less(i, j int) bool { return a[i].Name() < a[j].Name() }
func (a ByName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }

func (fs *Memory) ReadDir(path string) ([]os.FileInfo, error) {
if f, has := fs.s.Get(path); has {
if target, isLink := fs.resolveLink(path, f); isLink {
Expand All @@ -130,6 +137,8 @@ func (fs *Memory) ReadDir(path string) ([]os.FileInfo, error) {
entries = append(entries, fi)
}

sort.Sort(ByName(entries))

return entries, nil
}

Expand Down
24 changes: 24 additions & 0 deletions memfs/memory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,27 @@ func (s *MemorySuite) TestNegativeOffsets(c *C) {
_, err = f.Write(buf)
c.Assert(err, ErrorMatches, "writeat negative: negative offset")
}

func (s *MemorySuite) TestOrder(c *C) {
var err error

files := []string{
"a",
"b",
"c",
}
for _, f := range files {
_, err = s.FS.Create(f)
c.Assert(err, IsNil)
}

attemps := 30
for n := 0; n < attemps; n++ {
actual, err := s.FS.ReadDir("")
c.Assert(err, IsNil)

for i, f := range files {
c.Assert(actual[i].Name(), Equals, f)
}
}
}

0 comments on commit 66bd067

Please sign in to comment.