2016-04-21 08:48:33 +02:00
|
|
|
"""
|
|
|
|
The contents of this file are taken from
|
|
|
|
[Django-admin](https://github.com/niwinz/django-jinja/blob/master/django_jinja/management/commands/makemessages.py)
|
|
|
|
|
|
|
|
Jinja2's i18n functionality is not exactly the same as Django's.
|
|
|
|
In particular, the tags names and their syntax are different:
|
|
|
|
|
|
|
|
1. The Django ``trans`` tag is replaced by a _() global.
|
|
|
|
2. The Django ``blocktrans`` tag is called ``trans``.
|
|
|
|
|
|
|
|
(1) isn't an issue, since the whole ``makemessages`` process is based on
|
|
|
|
converting the template tags to ``_()`` calls. However, (2) means that
|
|
|
|
those Jinja2 ``trans`` tags will not be picked up by Django's
|
|
|
|
``makemessages`` command.
|
|
|
|
|
|
|
|
There aren't any nice solutions here. While Jinja2's i18n extension does
|
|
|
|
come with extraction capabilities built in, the code behind ``makemessages``
|
|
|
|
unfortunately isn't extensible, so we can:
|
|
|
|
|
|
|
|
* Duplicate the command + code behind it.
|
|
|
|
* Offer a separate command for Jinja2 extraction.
|
|
|
|
* Try to get Django to offer hooks into makemessages().
|
|
|
|
* Monkey-patch.
|
|
|
|
|
|
|
|
We are currently doing that last thing. It turns out there we are lucky
|
|
|
|
for once: It's simply a matter of extending two regular expressions.
|
|
|
|
Credit for the approach goes to:
|
|
|
|
http://stackoverflow.com/questions/2090717/getting-translation-strings-for-jinja2-templates-integrated-with-django-1-x
|
|
|
|
|
|
|
|
"""
|
2016-05-13 12:44:03 +02:00
|
|
|
from __future__ import absolute_import
|
2016-04-21 08:48:33 +02:00
|
|
|
|
2017-08-07 21:19:59 +02:00
|
|
|
from typing import Any, Dict, Iterable, Mapping, Text
|
2016-06-04 16:52:18 +02:00
|
|
|
|
|
|
|
from argparse import ArgumentParser
|
2016-05-13 12:44:03 +02:00
|
|
|
import os
|
2016-04-21 08:48:33 +02:00
|
|
|
import re
|
2016-05-13 12:44:03 +02:00
|
|
|
import glob
|
|
|
|
import json
|
|
|
|
from six.moves import zip
|
|
|
|
|
2017-06-02 08:02:34 +02:00
|
|
|
import django
|
2016-04-21 08:48:33 +02:00
|
|
|
from django.core.management.commands import makemessages
|
|
|
|
from django.template.base import BLOCK_TAG_START, BLOCK_TAG_END
|
2016-06-13 09:52:10 +02:00
|
|
|
from django.conf import settings
|
2017-07-10 07:17:42 +02:00
|
|
|
from django.utils.translation import template
|
2016-04-21 08:48:33 +02:00
|
|
|
|
2017-04-10 11:19:43 +02:00
|
|
|
from zerver.lib.str_utils import force_text
|
|
|
|
|
2016-07-30 05:00:36 +02:00
|
|
|
strip_whitespace_right = re.compile(u"(%s-?\\s*(trans|pluralize).*?-%s)\\s+" % (BLOCK_TAG_START, BLOCK_TAG_END), re.U)
|
2016-08-13 16:55:28 +02:00
|
|
|
strip_whitespace_left = re.compile(u"\\s+(%s-\\s*(endtrans|pluralize).*?-?%s)" % (
|
|
|
|
BLOCK_TAG_START, BLOCK_TAG_END), re.U)
|
2016-04-21 08:48:33 +02:00
|
|
|
|
2017-03-27 23:25:43 +02:00
|
|
|
regexes = ['{{#tr .*?}}([\s\S]*?){{/tr}}', # '.' doesn't match '\n' by default
|
2017-06-24 00:45:29 +02:00
|
|
|
'{{\s*t "(.*?)"\W*}}',
|
|
|
|
"{{\s*t '(.*?)'\W*}}",
|
2016-07-14 14:20:08 +02:00
|
|
|
"i18n\.t\('([^\']*?)'\)",
|
|
|
|
"i18n\.t\('(.*?)',.*?[^,]\)",
|
|
|
|
'i18n\.t\("([^\"]*?)"\)',
|
|
|
|
'i18n\.t\("(.*?)",.*?[^,]\)',
|
2016-05-13 12:44:03 +02:00
|
|
|
]
|
|
|
|
|
|
|
|
frontend_compiled_regexes = [re.compile(regex) for regex in regexes]
|
2016-10-10 09:31:00 +02:00
|
|
|
multiline_js_comment = re.compile("/\*.*?\*/", re.DOTALL)
|
|
|
|
singleline_js_comment = re.compile("//.*?\n")
|
2016-05-13 12:44:03 +02:00
|
|
|
|
2016-04-21 08:48:33 +02:00
|
|
|
def strip_whitespaces(src):
|
2016-12-08 05:06:51 +01:00
|
|
|
# type: (Text) -> Text
|
2016-07-30 05:00:36 +02:00
|
|
|
src = strip_whitespace_left.sub(u'\\1', src)
|
|
|
|
src = strip_whitespace_right.sub(u'\\1', src)
|
2016-04-21 08:48:33 +02:00
|
|
|
return src
|
|
|
|
|
|
|
|
class Command(makemessages.Command):
|
|
|
|
|
2016-05-13 12:44:03 +02:00
|
|
|
def add_arguments(self, parser):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: (ArgumentParser) -> None
|
2016-05-13 12:44:03 +02:00
|
|
|
super(Command, self).add_arguments(parser)
|
|
|
|
parser.add_argument('--frontend-source', type=str,
|
|
|
|
default='static/templates',
|
|
|
|
help='Name of the Handlebars template directory')
|
|
|
|
parser.add_argument('--frontend-output', type=str,
|
|
|
|
default='static/locale',
|
|
|
|
help='Name of the frontend messages output directory')
|
|
|
|
parser.add_argument('--frontend-namespace', type=str,
|
|
|
|
default='translations.json',
|
|
|
|
help='Namespace of the frontend locale file')
|
|
|
|
|
2016-04-21 08:48:33 +02:00
|
|
|
def handle(self, *args, **options):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: (*Any, **Any) -> None
|
2016-05-13 12:44:03 +02:00
|
|
|
self.handle_django_locales(*args, **options)
|
|
|
|
self.handle_frontend_locales(*args, **options)
|
|
|
|
|
|
|
|
def handle_frontend_locales(self, *args, **options):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: (*Any, **Any) -> None
|
2016-05-13 12:44:03 +02:00
|
|
|
self.frontend_source = options.get('frontend_source')
|
|
|
|
self.frontend_output = options.get('frontend_output')
|
|
|
|
self.frontend_namespace = options.get('frontend_namespace')
|
|
|
|
self.frontend_locale = options.get('locale')
|
|
|
|
self.frontend_exclude = options.get('exclude')
|
|
|
|
self.frontend_all = options.get('all')
|
|
|
|
|
|
|
|
translation_strings = self.get_translation_strings()
|
|
|
|
self.write_translation_strings(translation_strings)
|
|
|
|
|
|
|
|
def handle_django_locales(self, *args, **options):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: (*Any, **Any) -> None
|
2017-07-10 07:17:42 +02:00
|
|
|
old_endblock_re = template.endblock_re
|
|
|
|
old_block_re = template.block_re
|
|
|
|
old_constant_re = template.constant_re
|
|
|
|
|
|
|
|
old_templatize = template.templatize
|
2016-04-21 08:48:33 +02:00
|
|
|
# Extend the regular expressions that are used to detect
|
|
|
|
# translation blocks with an "OR jinja-syntax" clause.
|
2017-07-10 07:17:42 +02:00
|
|
|
template.endblock_re = re.compile(
|
|
|
|
template.endblock_re.pattern + '|' + r"""^-?\s*endtrans\s*-?$""")
|
|
|
|
template.block_re = re.compile(
|
|
|
|
template.block_re.pattern + '|' + r"""^-?\s*trans(?:\s+(?!'|")(?=.*?=.*?)|\s*-?$)""")
|
|
|
|
template.plural_re = re.compile(
|
|
|
|
template.plural_re.pattern + '|' + r"""^-?\s*pluralize(?:\s+.+|-?$)""")
|
|
|
|
template.constant_re = re.compile(r"""_\(((?:".*?")|(?:'.*?')).*\)""")
|
2017-06-02 08:02:34 +02:00
|
|
|
|
|
|
|
def my_templatize(src, *args, **kwargs):
|
|
|
|
# type: (Text, *Any, **Any) -> Text
|
2016-04-21 08:48:33 +02:00
|
|
|
new_src = strip_whitespaces(src)
|
2017-06-02 08:02:34 +02:00
|
|
|
return old_templatize(new_src, *args, **kwargs)
|
2016-04-21 08:48:33 +02:00
|
|
|
|
2017-07-10 07:17:42 +02:00
|
|
|
template.templatize = my_templatize
|
2016-04-21 08:48:33 +02:00
|
|
|
|
|
|
|
try:
|
2016-10-10 10:53:02 +02:00
|
|
|
ignore_patterns = options.get('ignore_patterns', [])
|
|
|
|
ignore_patterns.append('docs/*')
|
|
|
|
options['ignore_patterns'] = ignore_patterns
|
2016-04-21 08:48:33 +02:00
|
|
|
super(Command, self).handle(*args, **options)
|
|
|
|
finally:
|
2017-07-10 07:17:42 +02:00
|
|
|
template.endblock_re = old_endblock_re
|
|
|
|
template.block_re = old_block_re
|
|
|
|
template.templatize = old_templatize
|
|
|
|
template.constant_re = old_constant_re
|
2016-05-13 12:44:03 +02:00
|
|
|
|
|
|
|
def extract_strings(self, data):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: (str) -> Dict[str, str]
|
2016-10-10 09:31:00 +02:00
|
|
|
data = self.ignore_javascript_comments(data)
|
2017-05-31 23:44:59 +02:00
|
|
|
translation_strings = {} # type: Dict[str, str]
|
2016-05-13 12:44:03 +02:00
|
|
|
for regex in frontend_compiled_regexes:
|
|
|
|
for match in regex.findall(data):
|
2017-03-27 23:25:43 +02:00
|
|
|
match = match.strip()
|
|
|
|
match = ' '.join(line.strip() for line in match.splitlines())
|
|
|
|
match = match.replace('\n', '\\n')
|
2016-05-13 12:44:03 +02:00
|
|
|
translation_strings[match] = ""
|
|
|
|
|
|
|
|
return translation_strings
|
|
|
|
|
2016-10-10 09:31:00 +02:00
|
|
|
def ignore_javascript_comments(self, data):
|
|
|
|
# type: (str) -> str
|
|
|
|
|
|
|
|
# Removes multi line comments.
|
2017-03-30 19:50:38 +02:00
|
|
|
data = multiline_js_comment.sub('', data)
|
2016-10-10 09:31:00 +02:00
|
|
|
# Removes single line (//) comments.
|
2017-03-30 19:50:38 +02:00
|
|
|
data = singleline_js_comment.sub('', data)
|
2016-10-10 09:31:00 +02:00
|
|
|
return data
|
|
|
|
|
2016-05-13 12:44:03 +02:00
|
|
|
def get_translation_strings(self):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: () -> Dict[str, str]
|
2017-05-31 23:44:59 +02:00
|
|
|
translation_strings = {} # type: Dict[str, str]
|
2016-05-13 12:44:03 +02:00
|
|
|
dirname = self.get_template_dir()
|
|
|
|
|
2016-10-05 01:36:26 +02:00
|
|
|
for dirpath, dirnames, filenames in os.walk(dirname):
|
|
|
|
for filename in [f for f in filenames if f.endswith(".handlebars")]:
|
2017-04-05 09:23:35 +02:00
|
|
|
if filename.startswith('.'):
|
|
|
|
continue
|
2016-10-05 01:36:26 +02:00
|
|
|
with open(os.path.join(dirpath, filename), 'r') as reader:
|
2016-05-13 12:44:03 +02:00
|
|
|
data = reader.read()
|
|
|
|
translation_strings.update(self.extract_strings(data))
|
|
|
|
|
2016-06-13 09:52:10 +02:00
|
|
|
dirname = os.path.join(settings.DEPLOY_ROOT, 'static/js')
|
|
|
|
for filename in os.listdir(dirname):
|
2017-04-05 09:23:35 +02:00
|
|
|
if filename.endswith('.js') and not filename.startswith('.'):
|
2016-06-13 09:52:10 +02:00
|
|
|
with open(os.path.join(dirname, filename)) as reader:
|
|
|
|
data = reader.read()
|
|
|
|
translation_strings.update(self.extract_strings(data))
|
|
|
|
|
2016-05-13 12:44:03 +02:00
|
|
|
return translation_strings
|
|
|
|
|
|
|
|
def get_template_dir(self):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: () -> str
|
2016-05-13 12:44:03 +02:00
|
|
|
return self.frontend_source
|
|
|
|
|
|
|
|
def get_namespace(self):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: () -> str
|
2016-05-13 12:44:03 +02:00
|
|
|
return self.frontend_namespace
|
|
|
|
|
|
|
|
def get_locales(self):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: () -> Iterable[str]
|
2016-05-13 12:44:03 +02:00
|
|
|
locale = self.frontend_locale
|
|
|
|
exclude = self.frontend_exclude
|
|
|
|
process_all = self.frontend_all
|
|
|
|
|
|
|
|
paths = glob.glob('%s/*' % self.default_locale_path,)
|
2016-05-23 16:34:48 +02:00
|
|
|
all_locales = [os.path.basename(path) for path in paths if os.path.isdir(path)]
|
2016-05-13 12:44:03 +02:00
|
|
|
|
|
|
|
# Account for excluded locales
|
|
|
|
if process_all:
|
2016-05-23 16:34:48 +02:00
|
|
|
return all_locales
|
2016-05-13 12:44:03 +02:00
|
|
|
else:
|
|
|
|
locales = locale or all_locales
|
2016-05-23 16:34:48 +02:00
|
|
|
return set(locales) - set(exclude)
|
2016-05-13 12:44:03 +02:00
|
|
|
|
|
|
|
def get_base_path(self):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: () -> str
|
2016-05-13 12:44:03 +02:00
|
|
|
return self.frontend_output
|
|
|
|
|
|
|
|
def get_output_paths(self):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: () -> Iterable[str]
|
2016-05-13 12:44:03 +02:00
|
|
|
base_path = self.get_base_path()
|
|
|
|
locales = self.get_locales()
|
|
|
|
for path in [os.path.join(base_path, locale) for locale in locales]:
|
|
|
|
if not os.path.exists(path):
|
|
|
|
os.makedirs(path)
|
|
|
|
|
|
|
|
yield os.path.join(path, self.get_namespace())
|
|
|
|
|
|
|
|
def get_new_strings(self, old_strings, translation_strings):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: (Mapping[str, str], Iterable[str]) -> Dict[str, str]
|
2016-05-13 12:44:03 +02:00
|
|
|
"""
|
|
|
|
Missing strings are removed, new strings are added and already
|
|
|
|
translated strings are not touched.
|
|
|
|
"""
|
2017-05-31 23:44:59 +02:00
|
|
|
new_strings = {} # Dict[str, str]
|
2016-05-13 12:44:03 +02:00
|
|
|
for k in translation_strings:
|
2016-06-09 12:17:45 +02:00
|
|
|
k = k.replace('\\n', '\n')
|
2016-05-13 12:44:03 +02:00
|
|
|
new_strings[k] = old_strings.get(k, k)
|
|
|
|
|
2016-07-08 12:06:08 +02:00
|
|
|
plurals = {k: v for k, v in old_strings.items() if k.endswith('_plural')}
|
|
|
|
for plural_key, value in plurals.items():
|
|
|
|
components = plural_key.split('_')
|
|
|
|
singular_key = '_'.join(components[:-1])
|
|
|
|
if singular_key in new_strings:
|
|
|
|
new_strings[plural_key] = value
|
|
|
|
|
2016-05-13 12:44:03 +02:00
|
|
|
return new_strings
|
|
|
|
|
|
|
|
def write_translation_strings(self, translation_strings):
|
2016-06-04 16:52:18 +02:00
|
|
|
# type: (Iterable[str]) -> None
|
2016-05-13 12:44:03 +02:00
|
|
|
for locale, output_path in zip(self.get_locales(), self.get_output_paths()):
|
|
|
|
self.stdout.write("[frontend] processing locale {}".format(locale))
|
|
|
|
try:
|
|
|
|
with open(output_path, 'r') as reader:
|
|
|
|
old_strings = json.load(reader)
|
|
|
|
except (IOError, ValueError):
|
|
|
|
old_strings = {}
|
|
|
|
|
2017-04-10 11:19:43 +02:00
|
|
|
new_strings = {
|
|
|
|
force_text(k): v
|
|
|
|
for k, v in self.get_new_strings(old_strings,
|
|
|
|
translation_strings).items()
|
|
|
|
}
|
2016-05-13 12:44:03 +02:00
|
|
|
with open(output_path, 'w') as writer:
|
2017-03-03 08:14:32 +01:00
|
|
|
json.dump(new_strings, writer, indent=2, sort_keys=True)
|