fix: default i18n locale from system locale

This commit is contained in:
晴猫
2026-03-15 09:41:23 +09:00
parent 975939535c
commit 5eac9b3f31

View File

@@ -4,6 +4,7 @@ from pathlib import Path
from string import Formatter
import json
import locale
from .exceptions import (
DuplicateTranslationKeyError,
@@ -13,7 +14,7 @@ from .exceptions import (
)
_FORMATTER = Formatter()
DEFAULT_LOCALE = "zh-CN"
_FALLBACK_DEFAULT_LOCALE = "zh-CN"
PLURAL_CATEGORIES = {"zero", "one", "two", "few", "many", "other"}
TranslationValue = str | dict[str, str]
@@ -50,6 +51,27 @@ def normalize_locale(locale: str) -> str:
return "-".join(normalized_parts)
def _detect_default_locale() -> str:
try:
system_locale, _encoding = locale.getlocale()
except (TypeError, ValueError, locale.Error):
system_locale = None
if system_locale:
try:
normalized_locale = normalize_locale(system_locale)
except InvalidLocaleError:
normalized_locale = ""
if normalized_locale and (get_locales_root() / normalized_locale).is_dir():
return normalized_locale
return _FALLBACK_DEFAULT_LOCALE
DEFAULT_LOCALE = _detect_default_locale()
def to_babel_locale(locale: str) -> str:
return normalize_locale(locale).replace("-", "_")