| 1 |
# ext/linguaplugin.py |
| 2 |
# Copyright 2006-2022 the Mako authors and contributors <see AUTHORS file> |
| 3 |
# |
| 4 |
# This module is part of Mako and is released under |
| 5 |
# the MIT License: http://www.opensource.org/licenses/mit-license.php |
| 6 |
|
| 7 |
import contextlib |
| 8 |
import io |
| 9 |
|
| 10 |
from lingua.extractors import Extractor |
| 11 |
from lingua.extractors import get_extractor |
| 12 |
from lingua.extractors import Message |
| 13 |
|
| 14 |
from mako.ext.extract import MessageExtractor |
| 15 |
|
| 16 |
|
| 17 |
class LinguaMakoExtractor(Extractor, MessageExtractor): |
| 18 |
"""Mako templates""" |
| 19 |
|
| 20 |
use_bytes = False |
| 21 |
extensions = [".mako"] |
| 22 |
default_config = {"encoding": "utf-8", "comment-tags": ""} |
| 23 |
|
| 24 |
def __call__(self, filename, options, fileobj=None): |
| 25 |
self.options = options |
| 26 |
self.filename = filename |
| 27 |
self.python_extractor = get_extractor("x.py") |
| 28 |
if fileobj is None: |
| 29 |
ctx = open(filename, "r") |
| 30 |
else: |
| 31 |
ctx = contextlib.nullcontext(fileobj) |
| 32 |
with ctx as file_: |
| 33 |
yield from self.process_file(file_) |
| 34 |
|
| 35 |
def process_python(self, code, code_lineno, translator_strings): |
| 36 |
source = code.getvalue().strip() |
| 37 |
if source.endswith(":"): |
| 38 |
if source in ("try:", "else:") or source.startswith("except"): |
| 39 |
source = "" # Ignore try/except and else |
| 40 |
elif source.startswith("elif"): |
| 41 |
source = source[2:] # Replace "elif" with "if" |
| 42 |
source += "pass" |
| 43 |
code = io.StringIO(source) |
| 44 |
for msg in self.python_extractor( |
| 45 |
self.filename, self.options, code, code_lineno - 1 |
| 46 |
): |
| 47 |
if translator_strings: |
| 48 |
msg = Message( |
| 49 |
msg.msgctxt, |
| 50 |
msg.msgid, |
| 51 |
msg.msgid_plural, |
| 52 |
msg.flags, |
| 53 |
" ".join(translator_strings + [msg.comment]), |
| 54 |
msg.tcomment, |
| 55 |
msg.location, |
| 56 |
) |
| 57 |
yield msg |