From b40d1fe9114370db86f1ea8cc0d758637a869974 Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 26 May 2023 13:02:18 +0200 Subject: [PATCH] Added sync i18n --- libbot/i18n/sync/__init__.py | 79 ++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 libbot/i18n/sync/__init__.py diff --git a/libbot/i18n/sync/__init__.py b/libbot/i18n/sync/__init__.py new file mode 100644 index 0000000..1fed415 --- /dev/null +++ b/libbot/i18n/sync/__init__.py @@ -0,0 +1,79 @@ +from os import listdir +from pathlib import Path +from typing import Any + +from libbot import sync +from libbot.sync import config_get, json_read + + +def _(key: str, *args: str, locale: str = sync.config_get("locale")) -> Any: + """Get value of locale string + + ### Args: + * key (`str`): The last key of the locale's keys path + * *args (`list`): Path to key like: `dict[args][key]` + * locale (`str`): Locale to looked up in. Defaults to config's `"locale"` value + + ### Returns: + * `Any`: Value of provided locale key. Is usually `str`, `dict` or `list` + """ + if locale is None: + locale = sync.config_get("locale") + + try: + this_dict = json_read( + Path(f'{config_get("locale", "locations")}/{locale}.json') + ) + except FileNotFoundError: + try: + this_dict = json_read( + Path( + f'{config_get("locale", "locations")}/{config_get("locale")}.json' + ) + ) + except FileNotFoundError: + return f'⚠️ Locale in config is invalid: could not get "{key}" in {args} from locale "{locale}"' + + this_key = this_dict + for dict_key in args: + this_key = this_key[dict_key] + + try: + return this_key[key] + except KeyError: + return f'⚠️ Locale in config is invalid: could not get "{key}" in {args} from locale "{locale}"' + + +def in_all_locales(key: str, *args: str) -> list: + """Get value of the provided key and path in all available locales + + ### Args: + * key (`str`): The last key of the locale's keys path. + * *args (`list`): Path to key like: `dict[args][key]`. + + ### Returns: + * `list`: List of values in all locales + """ + + output = [] + files_locales = listdir(config_get("locale", "locations")) + + valid_locales = [".".join(entry.split(".")[:-1]) for entry in files_locales] + for lc in valid_locales: + try: + this_dict = json_read( + Path(f'{config_get("locale", "locations")}/{lc}.json') + ) + except FileNotFoundError: + continue + + this_key = this_dict + for dict_key in args: + this_key = this_key[dict_key] + + try: + output.append(this_key[key]) + except KeyError: + continue + + return output