From ab3d714727411de5711a9c5e3562fb6e0f70cefb Mon Sep 17 00:00:00 2001 From: profitroll Date: Fri, 26 May 2023 15:52:10 +0200 Subject: [PATCH] Added in_every_locale() to i18n --- libbot/i18n/__init__.py | 37 +++++++++++++++++++++++++++++++++++- libbot/i18n/sync/__init__.py | 37 +++++++++++++++++++++++++++++++++++- 2 files changed, 72 insertions(+), 2 deletions(-) diff --git a/libbot/i18n/__init__.py b/libbot/i18n/__init__.py index 5066a0d..04353c1 100644 --- a/libbot/i18n/__init__.py +++ b/libbot/i18n/__init__.py @@ -1,6 +1,6 @@ from os import listdir from pathlib import Path -from typing import Any +from typing import Any, Dict from libbot import config_get, json_read, sync @@ -76,3 +76,38 @@ async def in_all_locales(key: str, *args: str) -> list: continue return output + + +async def in_every_locale(key: str, *args: str) -> Dict[str, Any]: + """Get value of the provided key and path in every available locale with locale tag + + ### Args: + * key (`str`): The last key of the locale's keys path. + * *args (`list`): Path to key like: `dict[args][key]`. + + ### Returns: + * `Dict[str, Any]`: Locale is a key and it's value from locale file is a value + """ + + output = {} + files_locales = listdir(await config_get("locale", "locations")) + + valid_locales = [".".join(entry.split(".")[:-1]) for entry in files_locales] + for lc in valid_locales: + try: + this_dict = await json_read( + Path(f'{await 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[lc] = this_key[key] + except KeyError: + continue + + return output diff --git a/libbot/i18n/sync/__init__.py b/libbot/i18n/sync/__init__.py index e215f6e..bdd031f 100644 --- a/libbot/i18n/sync/__init__.py +++ b/libbot/i18n/sync/__init__.py @@ -1,6 +1,6 @@ from os import listdir from pathlib import Path -from typing import Any +from typing import Any, Dict from libbot import sync from libbot.sync import config_get, json_read @@ -75,3 +75,38 @@ def in_all_locales(key: str, *args: str) -> list: continue return output + + +def in_every_locale(key: str, *args: str) -> Dict[str, Any]: + """Get value of the provided key and path in every available locale with locale tag + + ### Args: + * key (`str`): The last key of the locale's keys path. + * *args (`list`): Path to key like: `dict[args][key]`. + + ### Returns: + * `Dict[str, Any]`: Locale is a key and it's value from locale file is a value + """ + + 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[lc] = this_key[key] + except KeyError: + continue + + return output