tpl/collections: Make sort stable

Fixes #9865
This commit is contained in:
Bjørn Erik Pedersen 2022-05-08 18:37:14 +02:00
parent 855e5869c6
commit 860c51c314
2 changed files with 32 additions and 2 deletions

View file

@ -43,3 +43,33 @@ baseURL = 'http://example.com/'
[foo foo foo] [foo foo foo]
`) `)
} }
// Issue 9865
func TestSortStable(t *testing.T) {
t.Parallel()
files := `
-- config.toml --
-- layouts/index.html --
{{ $values := slice (dict "a" 1 "b" 2) (dict "a" 3 "b" 1) (dict "a" 2 "b" 0) (dict "a" 1 "b" 0) (dict "a" 3 "b" 1) (dict "a" 2 "b" 2) (dict "a" 2 "b" 1) (dict "a" 0 "b" 3) (dict "a" 3 "b" 3) (dict "a" 0 "b" 0) (dict "a" 0 "b" 0) (dict "a" 2 "b" 0) (dict "a" 1 "b" 2) (dict "a" 1 "b" 1) (dict "a" 3 "b" 0) (dict "a" 2 "b" 0) (dict "a" 3 "b" 0) (dict "a" 3 "b" 0) (dict "a" 3 "b" 0) (dict "a" 3 "b" 1) }}
Asc: {{ sort (sort $values "b" "asc") "a" "asc" }}
Desc: {{ sort (sort $values "b" "desc") "a" "desc" }}
`
for i := 0; i < 4; i++ {
b := hugolib.NewIntegrationTestBuilder(
hugolib.IntegrationTestConfig{
T: t,
TxtarString: files,
},
).Build()
b.AssertFileContent("public/index.html", `
Asc: [map[a:0 b:0] map[a:0 b:0] map[a:0 b:3] map[a:1 b:0] map[a:1 b:1] map[a:1 b:2] map[a:1 b:2] map[a:2 b:0] map[a:2 b:0] map[a:2 b:0] map[a:2 b:1] map[a:2 b:2] map[a:3 b:0] map[a:3 b:0] map[a:3 b:0] map[a:3 b:0] map[a:3 b:1] map[a:3 b:1] map[a:3 b:1] map[a:3 b:3]]
Desc: [map[a:3 b:3] map[a:3 b:1] map[a:3 b:1] map[a:3 b:1] map[a:3 b:0] map[a:3 b:0] map[a:3 b:0] map[a:3 b:0] map[a:2 b:2] map[a:2 b:1] map[a:2 b:0] map[a:2 b:0] map[a:2 b:0] map[a:1 b:2] map[a:1 b:2] map[a:1 b:1] map[a:1 b:0] map[a:0 b:3] map[a:0 b:0] map[a:0 b:0]]
`)
}
}

View file

@ -177,9 +177,9 @@ func (p pairList) Less(i, j int) bool {
// sorts a pairList and returns a slice of sorted values // sorts a pairList and returns a slice of sorted values
func (p pairList) sort() any { func (p pairList) sort() any {
if p.SortAsc { if p.SortAsc {
sort.Sort(p) sort.Stable(p)
} else { } else {
sort.Sort(sort.Reverse(p)) sort.Stable(sort.Reverse(p))
} }
sorted := reflect.MakeSlice(p.SliceType, len(p.Pairs), len(p.Pairs)) sorted := reflect.MakeSlice(p.SliceType, len(p.Pairs), len(p.Pairs))
for i, v := range p.Pairs { for i, v := range p.Pairs {