WIP: Overhaul for 4.0.0

This commit is contained in:
kku
2024-12-18 14:16:37 +01:00
parent 5e479ddc79
commit 95d04308bd
32 changed files with 718 additions and 688 deletions

View File

@@ -1,8 +1,9 @@
from os import listdir
from pathlib import Path
from typing import Any, Dict, Union
from typing import Any, Dict, Union, List
from libbot import sync
from ...utils.config import config_get
from ...utils.json import json_read
class BotLocale:
@@ -18,19 +19,15 @@ class BotLocale:
elif not isinstance(locales_root, Path):
raise TypeError("'locales_root' must be a valid path or path-like object")
files_locales: list = listdir(locales_root)
files_locales: List[str] = listdir(locales_root)
valid_locales: list = [
".".join(entry.split(".")[:-1]) for entry in files_locales
]
valid_locales: List[str] = [".".join(entry.split(".")[:-1]) for entry in files_locales]
self.default: str = (
sync.config_get("locale") if default_locale is None else default_locale
)
self.locales: dict = {}
self.default: str = config_get("locale") if default_locale is None else default_locale
self.locales: Dict[str, Any] = {}
for lc in valid_locales:
self.locales[lc] = sync.json_read(Path(f"{locales_root}/{lc}.json"))
for locale in valid_locales:
self.locales[locale] = json_read(Path(f"{locales_root}/{locale}.json"))
def _(self, key: str, *args: str, locale: Union[str, None] = None) -> Any:
"""Get value of locale string
@@ -43,19 +40,21 @@ class BotLocale:
### Returns:
* `Any`: Value of provided locale key. Is usually `str`, `dict` or `list`
"""
if locale is None:
locale = self.default
locale: str = self.default
try:
this_dict = self.locales[locale]
this_dict: Dict[str, Any] = self.locales[locale]
except KeyError:
try:
this_dict = self.locales[self.default]
this_dict: Dict[str, Any] = self.locales[self.default]
except KeyError:
return f'⚠️ Locale in config is invalid: could not get "{key}" in {args} from locale "{locale}"'
return (
f'⚠️ Locale in config is invalid: could not get "{key}" in {args} from locale "{locale}"'
)
this_key: Dict[str, Any] = this_dict
this_key = this_dict
for dict_key in args:
this_key = this_key[dict_key]
@@ -74,16 +73,16 @@ class BotLocale:
### Returns:
* `list`: List of values in all locales
"""
output: List[str] = []
output = []
for name, lc in self.locales.items():
for name, locale in self.locales.items():
try:
this_dict = lc
this_dict: Dict[str, Any] = locale
except KeyError:
continue
this_key = this_dict
this_key: Dict[str, Any] = this_dict
for dict_key in args:
this_key = this_key[dict_key]
@@ -104,16 +103,16 @@ class BotLocale:
### Returns:
* `Dict[str, Any]`: Locale is a key and it's value from locale file is a value
"""
output: Dict[str, Any] = {}
output = {}
for name, lc in self.locales.items():
for name, locale in self.locales.items():
try:
this_dict = lc
this_dict: Dict[str, Any] = locale
except KeyError:
continue
this_key = this_dict
this_key: Dict[str, Any] = this_dict
for dict_key in args:
this_key = this_key[dict_key]