diff --git a/pkg/fileutil/fileutil.go b/pkg/fileutil/fileutil.go index d807e6c1b..246249dad 100644 --- a/pkg/fileutil/fileutil.go +++ b/pkg/fileutil/fileutil.go @@ -20,6 +20,7 @@ import ( "io/ioutil" "os" "path" + "sort" ) const ( @@ -36,7 +37,7 @@ func IsDirWriteable(dir string) error { return os.Remove(f) } -// ReadDir returns the filenames in the given directory. +// ReadDir returns the filenames in the given directory in sorted order. func ReadDir(dirpath string) ([]string, error) { dir, err := os.Open(dirpath) if err != nil { @@ -47,5 +48,6 @@ func ReadDir(dirpath string) ([]string, error) { if err != nil { return nil, err } + sort.Strings(names) return names, nil } diff --git a/pkg/fileutil/fileutil_test.go b/pkg/fileutil/fileutil_test.go index 6add5fdc4..bb6d4e5e7 100644 --- a/pkg/fileutil/fileutil_test.go +++ b/pkg/fileutil/fileutil_test.go @@ -19,6 +19,8 @@ package fileutil import ( "io/ioutil" "os" + "path/filepath" + "reflect" "testing" ) @@ -27,6 +29,7 @@ func TestIsDirWriteable(t *testing.T) { if err != nil { t.Fatalf("unexpected ioutil.TempDir error: %v", err) } + defer os.RemoveAll(tmpdir) if err := IsDirWriteable(tmpdir); err != nil { t.Fatalf("unexpected IsDirWriteable error: %v", err) } @@ -37,3 +40,29 @@ func TestIsDirWriteable(t *testing.T) { t.Fatalf("expected IsDirWriteable to error") } } + +func TestReadDir(t *testing.T) { + tmpdir, err := ioutil.TempDir("", "") + defer os.RemoveAll(tmpdir) + if err != nil { + t.Fatalf("unexpected ioutil.TempDir error: %v", err) + } + files := []string{"def", "abc", "xyz", "ghi"} + for _, f := range files { + fh, err := os.Create(filepath.Join(tmpdir, f)) + if err != nil { + t.Fatalf("error creating file: %v", err) + } + if err := fh.Close(); err != nil { + t.Fatalf("error closing file: %v", err) + } + } + fs, err := ReadDir(tmpdir) + if err != nil { + t.Fatalf("error calling ReadDir: %v", err) + } + wfs := []string{"abc", "def", "ghi", "xyz"} + if !reflect.DeepEqual(fs, wfs) { + t.Fatalf("ReadDir: got %v, want %v", fs, wfs) + } +} diff --git a/wal/wal.go b/wal/wal.go index 47fc491d1..35d3cbae4 100644 --- a/wal/wal.go +++ b/wal/wal.go @@ -25,7 +25,6 @@ import ( "os" "path" "reflect" - "sort" "github.com/coreos/etcd/pkg/fileutil" "github.com/coreos/etcd/pkg/pbutil" @@ -143,8 +142,6 @@ func openAtIndex(dirpath string, index uint64, all bool) (*WAL, error) { return nil, ErrFileNotFound } - sort.Sort(sort.StringSlice(names)) - nameIndex, ok := searchIndex(names, index) if !ok || !isValidSeq(names[nameIndex:]) { return nil, ErrFileNotFound