-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.py
61 lines (52 loc) · 2.11 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from json import loads, JSONDecodeError
from os import sep
from traceback import print_exc
from typing import Any, Dict, List, Union
def jsonLoad(filename) -> Union[Dict, List, str]:
"""Loads arg1 as json and returns its contents"""
with open(filename, "r", encoding='utf8') as file:
try:
output = loads(file.read())
except JSONDecodeError:
print(f"Could not load json file {filename}: file seems to be incorrect!\n{print_exc()}", flush=True)
raise
except FileNotFoundError:
print(f"Could not load json file {filename}: file does not seem to exist!\n{print_exc()}", flush=True)
raise
file.close()
return output
def configGet(key: str, *args: str) -> Any:
"""Get value of the config key
### Args:
* key (str): The last key of the keys path.
* *args (str): Path to key like: dict[args][key].
### Returns:
* any: Value of provided key
"""
this_dict = jsonLoad("config.json")
this_key = this_dict
for dict_key in args:
this_key = this_key[dict_key] # type: ignore
return this_key[key] # type: ignore
def locale(key: str, *args: str, locale_val=configGet("locale")) -> str:
"""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_val (str): Locale to looked up in. Defaults to config's locale value.
### Returns:
* str: Value of provided locale key
"""
if locale_val is None:
locale_val = configGet("locale")
try:
this_dict = jsonLoad(f'locale{sep}{locale_val}.json')
except FileNotFoundError:
return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale_val}"'
this_key = this_dict
for dict_key in args:
this_key = this_key[dict_key] # type: ignore
try:
return this_key[key] # type: ignore
except KeyError:
return f'⚠️ Locale in config is invalid: could not get "{key}" in {str(args)} from locale "{locale_val}"'