Skip to content

Commit

Permalink
Merge pull request #13 from MetalBlueberry/master
Browse files Browse the repository at this point in the history
memfs: ReadDir sorted by filename
  • Loading branch information
mcuadros committed Mar 10, 2021
2 parents d7a8afc + 66bd067 commit b791567
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
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
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 b791567

Please sign in to comment.