Add option to sort base on certain locale. (#1818)

* Add support for localized sorting

* Switch go-locale module; Use collate option for natural sorting

* Doc and error message improvement

* Simplify predicated checking of localized sorting.

* Improve error handling of `set locale` command
This commit is contained in:
陆离 authored and GitHub committed 2024-11-02 00:12:21 +11:00
1 parent 4079aead14
commit 3f63bc980f
8 files changed
+189 -19

No files matched your search

+51
View File
@@ -6,6 +6,8 @@ import (
"strings"
"testing"
"time"
"golang.org/x/text/collate"
)
func TestIsRoot(t *testing.T) {
@@ -335,3 +337,52 @@ func TestGetFileExtension(t *testing.T) {
})
}
}
func TestLocaleNaturalLess(t *testing.T) {
tests := []struct {
s1 string
s2 string
exp bool
}{
// preserving behavior of `naturalLess`
{"foo", "bar", false},
{"bar", "baz", true},
{"foo", "123", false},
{"foo1", "foobar", true},
{"foo1", "foo10", true},
{"foo2", "foo10", true},
{"foo1", "foo10bar", true},
{"foo2", "foo10bar", true},
{"foo1bar", "foo10bar", true},
{"foo2bar", "foo10bar", true},
{"foo1bar", "foo10", true},
{"foo2bar", "foo10", true},
// locale sort
{"你好", "他好", true}, // \u4F60\u597D, \u4ED6\u597D
{"到这", "到那", false}, // \u5230\u8FD9, \u5230\u90A3
{"你说", "什么", true}, // \u4f60\u8bf4, \u4ec0\u4e48
{"你好", "World", false}, // \u4F60\u597D, \u57\u6f\u72\u6c\u64
{"甲1", "甲乙", true},
{"甲1", "甲10", true},
{"甲2", "甲10", true},
{"甲1", "甲10乙", true},
{"甲2", "甲10乙", true},
{"甲1乙", "甲10乙", true},
{"甲2乙", "甲10乙", true},
{"甲1乙", "甲10", true},
{"甲2乙", "甲10", true},
}
localeStr := "zh-CN"
collator, err := makeCollator(localeStr, collate.Numeric)
if err != nil {
t.Fatalf("failed to create collator for %q: %s", localeStr, err)
}
for _, test := range tests {
if got := collator.CompareString(test.s1, test.s2) < 0; got != test.exp {
t.Errorf("at input '%s' and '%s' expected '%t' but got '%t'", test.s1, test.s2, test.exp, got)
}
}
}