Skip to content

fix(base): correct natural sort of numbers with leading zeros#38163

Open
s3onghyun wants to merge 1 commit into
go-gitea:mainfrom
s3onghyun:fix-natural-sort-leading-zeros
Open

fix(base): correct natural sort of numbers with leading zeros#38163
s3onghyun wants to merge 1 commit into
go-gitea:mainfrom
s3onghyun:fix-natural-sort-leading-zeros

Conversation

@s3onghyun

Copy link
Copy Markdown
Contributor

Description

NaturalSortCompare (modules/base/natural_sort.go) compares two numeric run parts by raw string length:

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").

Testing

Added cases to TestNaturalSortLess (natural_sort_test.go): file0001 < file2, a08 < a9, 00 < 1, etc. Five cases fail against the original code, all pass after; go test ./modules/base/ green.

NaturalSortCompare compared numeric runs by raw byte length, which only
reflects magnitude when there are no leading zeros. So 'file0001' sorted
after 'file2' and 'a08' after 'a9'. Strip leading zeros before comparing
digit count, then fall back to collation and original length.

Signed-off-by: Seonghyun Hong <s3onghyun.hong@gmail.com>
@GiteaBot GiteaBot added the lgtm/need 2 This PR needs two approvals by maintainers to be considered for merging. label Jun 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

lgtm/need 2 This PR needs two approvals by maintainers to be considered for merging. type/bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants