mirror of
https://github.com/go-gitea/gitea.git
synced 2026-08-24 05:19:50 +00:00
84b67d50a6
### Description
`NaturalSortCompare` (`modules/base/natural_sort.go`) compares two
numeric run parts by **raw string length**:
```go
if len(part1) != len(part2) {
return len(part1) - len(part2)
}
```
"Longer digit string = larger number" only holds without leading zeros.
With zero-padded numbers the comparison inverts:
- `file0001` vs `file2` → claims `file0001 > file2`, but `1 < 2`
- `a08` vs `a9` → claims `a08 > a9`, but `8 < 9`
This affects any natural-ordered listing where zero-padded and shorter
unpadded numbers mix (branch/tag/file names, etc.).
### Fix
Strip leading zeros before comparing digit-count magnitude; on equal
magnitude fall back to collation, then to the original length so fewer
leading zeros sort first. Added a small `naturalSortTrimZeros` helper
(keeps one char so `"000"` → `"0"`).
Signed-off-by: Seonghyun Hong <s3onghyun.hong@gmail.com>
Signed-off-by: wxiaoguang <wxiaoguang@gmail.com>
Co-authored-by: silverwind <me@silverwind.io>
Co-authored-by: wxiaoguang <wxiaoguang@gmail.com>
49 lines
1.0 KiB
Go
49 lines
1.0 KiB
Go
// Copyright 2017 The Gitea Authors. All rights reserved.
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
package base
|
|
|
|
import (
|
|
"testing"
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
)
|
|
|
|
func TestNaturalSortLess(t *testing.T) {
|
|
testLess := func(s1, s2 string) {
|
|
assert.Negative(t, NaturalSortCompare(s1, s2), "s1<s2 should be true: s1=%q, s2=%q", s1, s2)
|
|
}
|
|
testEqual := func(s1, s2 string) {
|
|
assert.Zero(t, NaturalSortCompare(s1, s2), "s1<s2 should be false: s1=%q, s2=%q", s1, s2)
|
|
}
|
|
|
|
testEqual("", "")
|
|
testLess("", "a")
|
|
testLess("", "1")
|
|
|
|
testLess("v1.2", "v1.2.0")
|
|
testLess("v1.2.0", "v1.10.0")
|
|
testLess("v1.20.0", "v1.29.0")
|
|
testEqual("v1.20.0", "v1.20.0")
|
|
|
|
testLess("a", "A")
|
|
testLess("a", "B")
|
|
testLess("A", "b")
|
|
testLess("A", "ab")
|
|
|
|
testLess("abc", "bcd")
|
|
testLess("a-1-a", "a-1-b")
|
|
testLess("2", "12")
|
|
|
|
testLess("cafe", "café")
|
|
testLess("café", "caff")
|
|
|
|
testLess("A-2", "A-11")
|
|
testLess("0.txt", "1.txt")
|
|
|
|
testLess("file0001", "file2")
|
|
testLess("a8", "a08")
|
|
testLess("00", "1")
|
|
testLess("0", "00") // equal value, fewer leading zeros sorts first
|
|
}
|