-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathi18n.py
94 lines (72 loc) · 2.61 KB
/
i18n.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import codecs
import os
from os import path
I18N_PATH = "i18n"
DEFAULT_LANG = "en"
class I18n:
def __init__(self, langcode=None, path=None):
if path is None:
path = I18N_PATH
if langcode is None:
langcode = DEFAULT_LANG
self.translations = {}
import os
for file in os.listdir(I18N_PATH):
if file.endswith(".i18n"):
fname = file.split(".")
self.translations[fname[0]] = Translation(fname[0], file, path)
self.checkvalidlanguage(langcode)
self._langcode = langcode
def get(self, str, langcode=None):
if langcode is None:
langcode = self._langcode
self.checkvalidlanguage(langcode)
return self.translations[langcode].get(str)
def setlang(self, langcode):
self.checkvalidlanguage(langcode)
self._langcode = langcode
def checkvalidlanguage(self, langcode):
if langcode not in self.translations:
raise TranslationNotFoundException(langcode)
@property
def name(self):
if self._langcode is None:
return None
return self.translations[self._langcode].name
class Translation:
def __init__(self, code, file, path=None):
if path is None:
path = I18N_PATH
self.code = code
self.file = file
self.alltext = self.read_from_file(path)
try:
self.name = self.get("language")
except StringNotFoundException as e:
from totes import log
log.error(str(e))
self.name = "Unknown"
def read_from_file(self, path):
file = codecs.open(path + "/" + self.code + ".i18n", 'r',
encoding='utf8')
data = dict(line.split(":", 1) for line in file)
file.close()
return data
def get(self, text):
if text not in self.alltext:
raise StringNotFoundException(text, self)
return self.alltext[text].replace("\n", "").replace("\r", "").strip()
class TranslationException(Exception):
pass
class TranslationNotFoundException(TranslationException):
def __init__(self, code):
self.code = code
def __str__(self):
return "Translation not found: {}".format(self.code)
class StringNotFoundException(TranslationException):
def __init__(self, string, translation):
self.string = string
self.translation = translation
def __str__(self):
return "Could not find '{}' in translation {}".format(self.string,
self.translation.code)