Просмотр исходного кода

Sort APIImages by most recent creation date.

Fixes #985.
David Calavera 12 лет назад
Родитель
Сommit
cd6aeaf979
3 измененных файлов с 68 добавлено и 0 удалено
  1. 2 0
      server.go
  2. 36 0
      sorter.go
  3. 30 0
      sorter_test.go

+ 2 - 0
server.go

@@ -241,6 +241,8 @@ func (srv *Server) Images(all bool, filter string) ([]APIImages, error) {
 			outs = append(outs, out)
 		}
 	}
+
+	sortImagesByCreation(outs)
 	return outs, nil
 }
 

+ 36 - 0
sorter.go

@@ -0,0 +1,36 @@
+package docker
+
+import "sort"
+
+type imageSorter struct {
+	images []APIImages
+	by     func(i1, i2 *APIImages) bool // Closure used in the Less method.
+}
+
+// Len is part of sort.Interface.
+func (s *imageSorter) Len() int {
+	return len(s.images)
+}
+
+// Swap is part of sort.Interface.
+func (s *imageSorter) Swap(i, j int) {
+	s.images[i], s.images[j] = s.images[j], s.images[i]
+}
+
+// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.
+func (s *imageSorter) Less(i, j int) bool {
+	return s.by(&s.images[i], &s.images[j])
+}
+
+// Sort []ApiImages by most recent creation date.
+func sortImagesByCreation(images []APIImages) {
+	creation := func(i1, i2 *APIImages) bool {
+		return i1.Created > i2.Created
+	}
+
+	sorter := &imageSorter{
+		images: images,
+		by:     creation}
+
+	sort.Sort(sorter)
+}

+ 30 - 0
sorter_test.go

@@ -0,0 +1,30 @@
+package docker
+
+import (
+	"testing"
+)
+
+func TestServerListOrderedImages(t *testing.T) {
+	runtime := mkRuntime(t)
+	defer nuke(runtime)
+
+	archive, err := fakeTar()
+	if err != nil {
+		t.Fatal(err)
+	}
+	_, err = runtime.graph.Create(archive, nil, "Testing", "", nil)
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	srv := &Server{runtime: runtime}
+
+	images, err := srv.Images(true, "")
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	if images[0].Created < images[1].Created {
+		t.Error("Expected []APIImges to be ordered by most recent creation date.")
+	}
+}