pkg/fileutil: sort filenames during ReadDir

release-2.0
Jonathan Boulle 2014-12-18 16:36:11 -08:00
parent 1d859790e5
commit 1ec98cb795
3 changed files with 32 additions and 4 deletions

View File

@ -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
}

View File

@ -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)
}
}

View File

@ -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