From 66bd06748c953a4d46cedee71ca6386e11f6898e Mon Sep 17 00:00:00 2001 From: "Perez Domingo, Victor" Date: Sun, 17 Jan 2021 14:41:40 +0100 Subject: [PATCH] Fix #12, MemFS ReadDir sorted by filename --- memfs/memory.go | 9 +++++++++ memfs/memory_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/memfs/memory.go b/memfs/memory.go index d4ac056..6054d22 100644 --- a/memfs/memory.go +++ b/memfs/memory.go @@ -7,6 +7,7 @@ import ( "io" "os" "path/filepath" + "sort" "strings" "time" @@ -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 { @@ -130,6 +137,8 @@ func (fs *Memory) ReadDir(path string) ([]os.FileInfo, error) { entries = append(entries, fi) } + sort.Sort(ByName(entries)) + return entries, nil } diff --git a/memfs/memory_test.go b/memfs/memory_test.go index 1ec74b8..95edcc9 100644 --- a/memfs/memory_test.go +++ b/memfs/memory_test.go @@ -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) + } + } +}