Skip to content

Commit

Permalink
fix(utils): use strxfrm only if it works
Browse files Browse the repository at this point in the history
  • Loading branch information
nijel committed Feb 27, 2025
1 parent 6dcabb2 commit 16fe9b7
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
4 changes: 2 additions & 2 deletions weblate/trans/tests/test_sort.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@

class SortTest(TestCase):
def test_sort(self) -> None:
if not weblate.trans.util.LOCALE_SETUP:
self.skipTest("Could not set up locales")
if not weblate.trans.util.USE_STRXFRM:
self.skipTest("strxfrm not available")
result = weblate.trans.util.sort_choices(
((2, "zkouška"), (3, "zkouzka"), (1, "zkouaka"))
)
Expand Down
19 changes: 16 additions & 3 deletions weblate/trans/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
from weblate.trans.models import Project, Translation, Unit

PLURAL_SEPARATOR = "\x1e\x1e"
LOCALE_SETUP = True
USE_STRXFRM = False

PRIORITY_CHOICES = (
(60, gettext_lazy("Very high")),
Expand All @@ -56,7 +56,16 @@
try:
locale.setlocale(locale.LC_ALL, ("en_US", "UTF-8"))
except locale.Error:
LOCALE_SETUP = False
USE_STRXFRM = False
else:
try:
locale.strxfrm("zkouška")
except OSError:
# Crashes on macOS 15, see
# https://github.com/python/cpython/issues/130567
USE_STRXFRM = False
else:
USE_STRXFRM = True


def is_plural(text: str) -> bool:
Expand Down Expand Up @@ -273,7 +282,11 @@ def path_separator(path: str) -> str:

def sort_unicode(choices: list[T], key: Callable[[T], str]) -> list[T]:
"""Unicode aware sorting if available."""
return sorted(choices, key=lambda tup: locale.strxfrm(key(tup)))

def sort_strxfrm(item: T) -> str:
return locale.strxfrm(key(item))

return sorted(choices, key=sort_strxfrm if USE_STRXFRM else key)


def sort_choices(choices: list[tuple[str, str]]) -> list[tuple[str, str]]:
Expand Down

0 comments on commit 16fe9b7

Please sign in to comment.