shithub: hugo

Download patch

ref: 7d5c9fbf44ad9f2fd5baed405f79f2b132dd9178
parent: c6c2c689d602cf9d0a9bdf016e3a51a54030b072
author: Robert Basic <[email protected]>
date: Fri Apr 1 16:17:16 EDT 2016

Make ByCount sort consistently

When two or more taxonomies have the same number of pages,
sort them by name to have consistent ByCount sorting of
taxonomies.

Fixes #1930

--- a/hugolib/taxonomy.go
+++ b/hugolib/taxonomy.go
@@ -96,9 +96,16 @@
 }
 
 // ByCount returns an ordered taxonomy sorted by # of pages per key.
+// If taxonomies have the same # of pages, sort them alphabetical
 func (i Taxonomy) ByCount() OrderedTaxonomy {
 	count := func(i1, i2 *OrderedTaxonomyEntry) bool {
-		return len(i1.WeightedPages) > len(i2.WeightedPages)
+		li1 := len(i1.WeightedPages)
+		li2 := len(i2.WeightedPages)
+
+		if li1 == li2 {
+			return i1.Name < i2.Name
+		}
+		return li1 > li2
 	}
 
 	ia := i.TaxonomyArray()
--- a/hugolib/taxonomy_test.go
+++ b/hugolib/taxonomy_test.go
@@ -16,6 +16,8 @@
 import (
 	"strings"
 	"testing"
+
+	"github.com/spf13/viper"
 )
 
 func TestSitePossibleTaxonomies(t *testing.T) {
@@ -27,5 +29,31 @@
 		if !compareStringSlice(taxonomies, []string{"categories", "tags"}) {
 			t.Fatalf("possible taxonomies do not match [tags categories].  Got: %s", taxonomies)
 		}
+	}
+}
+
+func TestByCountOrderOfTaxonomies(t *testing.T) {
+	viper.Reset()
+	defer viper.Reset()
+
+	taxonomies := make(map[string]string)
+
+	taxonomies["tag"] = "tags"
+	taxonomies["category"] = "categories"
+
+	viper.Set("taxonomies", taxonomies)
+
+	site := new(Site)
+	page, _ := NewPageFrom(strings.NewReader(pageYamlWithTaxonomiesA), "path/to/page")
+	site.Pages = append(site.Pages, page)
+	site.assembleTaxonomies()
+
+	st := make([]string, 0)
+	for _, t := range site.Taxonomies["tags"].ByCount() {
+		st = append(st, t.Name)
+	}
+
+	if !compareStringSlice(st, []string{"a", "b", "c"}) {
+		t.Fatalf("ordered taxonomies do not match [a, b, c].  Got: %s", st)
 	}
 }