Skip to content

Commit b791567

Browse files
authored
Merge pull request #13 from MetalBlueberry/master
memfs: ReadDir sorted by filename
2 parents d7a8afc + 66bd067 commit b791567

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

memfs/memory.go

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"io"
88
"os"
99
"path/filepath"
10+
"sort"
1011
"strings"
1112
"time"
1213

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

121+
type ByName []os.FileInfo
122+
123+
func (a ByName) Len() int { return len(a) }
124+
func (a ByName) Less(i, j int) bool { return a[i].Name() < a[j].Name() }
125+
func (a ByName) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
126+
120127
func (fs *Memory) ReadDir(path string) ([]os.FileInfo, error) {
121128
if f, has := fs.s.Get(path); has {
122129
if target, isLink := fs.resolveLink(path, f); isLink {
@@ -130,6 +137,8 @@ func (fs *Memory) ReadDir(path string) ([]os.FileInfo, error) {
130137
entries = append(entries, fi)
131138
}
132139

140+
sort.Sort(ByName(entries))
141+
133142
return entries, nil
134143
}
135144

memfs/memory_test.go

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,3 +44,27 @@ func (s *MemorySuite) TestNegativeOffsets(c *C) {
4444
_, err = f.Write(buf)
4545
c.Assert(err, ErrorMatches, "writeat negative: negative offset")
4646
}
47+
48+
func (s *MemorySuite) TestOrder(c *C) {
49+
var err error
50+
51+
files := []string{
52+
"a",
53+
"b",
54+
"c",
55+
}
56+
for _, f := range files {
57+
_, err = s.FS.Create(f)
58+
c.Assert(err, IsNil)
59+
}
60+
61+
attemps := 30
62+
for n := 0; n < attemps; n++ {
63+
actual, err := s.FS.ReadDir("")
64+
c.Assert(err, IsNil)
65+
66+
for i, f := range files {
67+
c.Assert(actual[i].Name(), Equals, f)
68+
}
69+
}
70+
}

0 commit comments

Comments
 (0)