-
Notifications
You must be signed in to change notification settings - Fork 22
/
render_templates_py3.py
207 lines (180 loc) · 7.1 KB
/
render_templates_py3.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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
"""Renders GreenAddress templates."""
import argparse
import errno
import gettext
import glob
import os
from babel.messages.pofile import read_po
from babel.messages.mofile import write_mo
import gettext_finder_py3 as gettext_finder
TEMPLATES = {
'wallet.html': 'wallet/wallet.html',
'wallet/partials/*.html': 'wallet/partials/*.html',
'wallet/partials/signuplogin/*.html':
'wallet/partials/signuplogin/*.html',
}
try:
# Used internally by GreenAddress for website deployment.
# (Not useful for Cordova and Chrome apps, hence the optional import.)
import render_templates_deployment
except ImportError:
render_templates_deployment = None
_js_escapes = {
ord('\\'): '\\u005C',
ord('\''): '\\u0027',
ord('"'): '\\u0022',
ord('>'): '\\u003E',
ord('<'): '\\u003C',
ord('&'): '\\u0026',
ord('='): '\\u003D',
ord('-'): '\\u002D',
ord(';'): '\\u003B',
ord('\u2028'): '\\u2028',
ord('\u2029'): '\\u2029'
}
def escapejs(txt):
return txt.translate(_js_escapes)
class TemplatesRenderer(object):
def __init__(self, hostname, outdir, cdvapp, multi_asset, electron, network):
self.hostname = hostname
self.outdir = outdir
self.cdvapp = cdvapp
self.multi_asset = multi_asset
self.electron = electron
self.network = network
self.env = gettext_finder.jinja_env
self.trs = {}
for lang in gettext_finder.GETTEXT_LANGUAGES:
self.trs[lang] = gettext.translation(
'django', 'locale', [lang], fallback=True
)
if not isinstance(self.trs[lang], gettext.GNUTranslations):
print("Translation file for %s not found." % lang)
def process_template(self, template, lang, output):
tr = self.trs[lang]
def to_unicode(s):
if isinstance(s, str):
return s
else:
return s.decode('utf-8')
ugettext = lambda m: tr.gettext(to_unicode(m.replace('\n', '')))
def ungettext(s, p, n):
tr.ungettext(
# new lines in html are only for word wrapping, so skip them
to_unicode(s.replace('\n', '')),
to_unicode(p.replace('\n', '')),
n
)
self.env.install_gettext_callables(ugettext, ungettext, newstyle=True)
template = self.env.get_template(template)
kwargs = {
'HOSTNAME': self.hostname or 'localhost',
'LANG': lang,
'BASE_URL': '..' if (self.cdvapp or self.electron) else '',
'STATIC_URL': '../static' if (self.cdvapp or self.electron) else '/static',
'BITCOIN_NETWORK': self.network if self.electron else '',
'DEVELOPMENT': True,
'PATH_NO_LANG': output,
'MULTIASSET': self.multi_asset,
'cdvapp': self.cdvapp,
'crapp': not (self.cdvapp or self.electron),
'electronapp': self.electron,
'WEBWALLET_MODE': 'FULL'
}
out = template.render(**kwargs)
try:
os.makedirs(os.path.dirname(
os.path.join(self.outdir, lang, output)
))
except OSError as e:
if e.errno != errno.EEXIST:
raise
with open(os.path.join(self.outdir, lang, output), 'wb+') as f:
f.write(out.encode('utf-8'))
def generate_js_catalog(self, lang):
tr = gettext.translation('djangojs', 'locale', [lang], fallback=True)
s = """
function get_catalog(globals) {
globals.i18n_catalog = {\n"""
entries = []
plurals = {}
for key, val in list(tr._catalog.items()):
if not key:
continue
if isinstance(key, tuple):
if key[0] in plurals:
plurals[key[0]][key[1]] = val
else:
plurals[key[0]] = {key[1]: val}
else:
entries.append('"%s": "%s"' % (escapejs(key), escapejs(val)))
for key, val in list(plurals.items()):
sd = "{\n"
sds = []
for sk, sv in list(val.items()):
sds.append(" %s: '%s'" % (sk, escapejs(sv)))
sd += ",\n".join(sds) + "}"
entries.append('"%s": %s' % (escapejs(key), sd))
s += ",\n".join(entries)
s += "\n};}"
with open(
os.path.join(self.outdir, lang, 'i18n_catalog.js'), 'wb'
) as f:
f.write(s.encode('utf-8'))
def compile_domain(domain):
for locale in gettext_finder.GETTEXT_LANGUAGES:
popath = os.path.join('locale', locale, "LC_MESSAGES", domain + ".po")
mopath = os.path.join('locale', locale, "LC_MESSAGES", domain + ".mo")
with open(mopath, 'wb') as mo_f, open(popath, encoding="utf-8") as po_f:
write_mo(mo_f, read_po(po_f))
def main():
parser = argparse.ArgumentParser(description='Renders templates.')
parser.add_argument('outdir', metavar='OUTDIR',
help='The output directory')
parser.add_argument('--hostname', '-n',
help="Optional hostname of deployment (not used for Cordova/crx)")
parser.add_argument('--cordova', '-a', action='store_true',
help="Build HTML for Cordova project")
parser.add_argument('--electron', '-e', action='store_true',
help="Build HTML for Electron project")
parser.add_argument('--multiasset', '-m', action='store_true',
help="Build HTML for MultiAsset functionality")
parser.add_argument('--network', '-o', type=str, default="",
help="Optional app bitcoin network")
# multi_asset
if render_templates_deployment:
TEMPLATES.update(render_templates_deployment.TEMPLATES)
gettext_finder.TEMPLATE_SEARCH_PATH.extend(
render_templates_deployment.TEMPLATE_SEARCH_PATH)
args = parser.parse_args()
gettext_finder.start() # regenerate *.po
compile_domain('django')
compile_domain('djangojs')
renderer = TemplatesRenderer(
hostname=args.hostname,
outdir=args.outdir,
cdvapp=args.cordova,
multi_asset=args.multiasset,
electron=args.electron,
network=args.network
)
for output, templates in TEMPLATES.items():
if output.endswith('*.html'):
for path in gettext_finder.TEMPLATE_SEARCH_PATH:
for fname in glob.glob(os.path.join(path, templates)):
fname = os.path.relpath(fname, path)
# jinja expects the template name to be '/' separated, even on Windows
fname = fname.replace("\\", '/')
for lang in gettext_finder.GETTEXT_LANGUAGES:
renderer.process_template(
fname,
lang,
output.replace('*.html', os.path.basename(fname))
)
else:
for lang in gettext_finder.GETTEXT_LANGUAGES:
renderer.process_template(templates, lang, output)
for lang in gettext_finder.GETTEXT_LANGUAGES:
renderer.generate_js_catalog(lang)
if __name__ == '__main__':
main()