فهرست منبع

pkg/fileutil: sort filenames during ReadDir

Jonathan Boulle 11 سال پیش
والد
کامیت
1ec98cb795
3فایلهای تغییر یافته به همراه32 افزوده شده و 4 حذف شده
  1. 3 1
      pkg/fileutil/fileutil.go
  2. 29 0
      pkg/fileutil/fileutil_test.go
  3. 0 3
      wal/wal.go

+ 3 - 1
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
 }

+ 29 - 0
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)
+	}
+}

+ 0 - 3
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