rewrite: Update Babel.

New default locale resolution.
Added translation utilities for common tasks.
This commit is contained in:
2023-03-02 18:57:05 +02:00
parent b777bd33e4
commit 252e261a55
4 changed files with 28 additions and 3 deletions

View File

@@ -1,5 +1,7 @@
from .translator import SOURCE_LOCALE, LeoBabel, LocalBabel, LazyStr, ctx_locale, ctx_translator from .translator import SOURCE_LOCALE, LeoBabel, LocalBabel, LazyStr, ctx_locale, ctx_translator
babel = LocalBabel('babel')
async def setup(bot): async def setup(bot):
from .cog import BabelCog from .cog import BabelCog

View File

@@ -19,8 +19,8 @@ from settings.groups import SettingGroup
from core.data import CoreData from core.data import CoreData
from .translator import ctx_locale, ctx_translator, LocalBabel, SOURCE_LOCALE from .translator import ctx_locale, ctx_translator, LocalBabel, SOURCE_LOCALE
from . import babel
babel = LocalBabel('babel')
_ = babel._ _ = babel._
_p = babel._p _p = babel._p

View File

@@ -39,6 +39,9 @@ class LeoBabel(Translator):
self.supported_domains = {dom for dom in stripped if dom} self.supported_domains = {dom for dom in stripped if dom}
async def load(self): async def load(self):
self._load()
def _load(self):
""" """
Initialise the gettext translators for the supported_locales. Initialise the gettext translators for the supported_locales.
""" """
@@ -75,7 +78,7 @@ class LeoBabel(Translator):
def t(self, lazystr, locale=None): def t(self, lazystr, locale=None):
domain = lazystr.domain domain = lazystr.domain
translator = self.get_translator(locale or lazystr.locale, domain) translator = self.get_translator(locale or lazystr.locale or ctx_locale.get(), domain)
return lazystr._translate_with(translator) return lazystr._translate_with(translator)
async def translate(self, string: locale_str, locale: Locale, context): async def translate(self, string: locale_str, locale: Locale, context):
@@ -130,7 +133,7 @@ class LazyStr(locale_str):
self.method = method self.method = method
self.args = args self.args = args
self.domain = domain self.domain = domain
self.locale = locale or ctx_locale.get() self.locale = locale
@property @property
def message(self): def message(self):

20
src/babel/utils.py Normal file
View File

@@ -0,0 +1,20 @@
from .translator import ctx_translator
from . import babel
_, _p, _np = babel._, babel._p, babel._np
MONTHS = _p(
'utils|months',
"January,February,March,April,May,June,July,August,September,October,November,December"
)
SHORT_MONTHS = _p(
'utils|short_months',
"Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
)
def local_month(month, short=False):
string = MONTHS if not short else SHORT_MONTHS
return ctx_translator.get().t(string).split(',')[month-1]