feat: Load language file in lang/ instead of the ini file.

This commit is contained in:
Terry Geng
2020-07-11 11:01:33 +08:00
parent e84607b8e8
commit 9e2e09e5fd
12 changed files with 123 additions and 217 deletions

View File

@ -1,24 +1,45 @@
import json
import variables as var
lang_dict = {}
def tr(option, *argv, **kwargs):
def load_lang(lang):
global lang_dict
with open(f"lang/{lang}", "r") as f:
lang_dict = json.load(f)
def tr_cli(option, *argv, **kwargs):
try:
string = var.config.get("strings", option)
string = lang_dict['cli'][option]
except KeyError:
raise KeyError("Missed strings in configuration file: '{string}'. ".format(string=option)
+ "Please restore you configuration file back to default if necessary.")
raise KeyError("Missed strings in language file: '{string}'. ".format(string=option))
return _tr(string, *argv, **kwargs)
def tr_web(option, *argv, **kwargs):
try:
string = lang_dict['web'][option]
except KeyError:
raise KeyError("Missed strings in language file: '{string}'. ".format(string=option))
return _tr(string, *argv, **kwargs)
def _tr(string, *argv, **kwargs):
if argv or kwargs:
try:
formatted = string.format(*argv, **kwargs)
return formatted
except KeyError as e:
raise KeyError(
"Missed/Unexpected placeholder {{{placeholder}}} in string '{string}'. ".format(placeholder=str(e).strip("'"), string=option)
+ "Please restore you configuration file back to default if necessary.")
"Missed/Unexpected placeholder {{{placeholder}}} in string "
"'{string}'. ".format(placeholder=str(e).strip("'"),
string=string))
except TypeError:
raise KeyError(
"Missed placeholder in string '{string}'. ".format(string=option)
+ "Please restore you configuration file back to default if necessary.")
"Missed placeholder in string '{string}'. ".format(string=string))
else:
return string
@ -28,5 +49,4 @@ def commands(command):
string = var.config.get("commands", command)
return string
except KeyError:
raise KeyError("Missed command in configuration file: '{string}'. ".format(string=command)
+ "Please restore you configuration file back to default if necessary.")
raise KeyError("Missed command in configuration file: '{string}'. ".format(string=command))