1# ext/linguaplugin.py
2# Copyright 2006-2019 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
7import io
8
9from lingua.extractors import Extractor
10from lingua.extractors import get_extractor
11from lingua.extractors import Message
12
13from mako import compat
14from mako.ext.extract import MessageExtractor
15
16
17class LinguaMakoExtractor(Extractor, MessageExtractor):
18
19    """Mako templates"""
20
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            fileobj = open(filename, "rb")
30        return self.process_file(fileobj)
31
32    def process_python(self, code, code_lineno, translator_strings):
33        source = code.getvalue().strip()
34        if source.endswith(compat.b(":")):
35            if source in (
36                compat.b("try:"),
37                compat.b("else:"),
38            ) or source.startswith(compat.b("except")):
39                source = compat.b("")  # Ignore try/except and else
40            elif source.startswith(compat.b("elif")):
41                source = source[2:]  # Replace "elif" with "if"
42            source += compat.b("pass")
43        code = io.BytesIO(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                    compat.u(" ").join(translator_strings + [msg.comment]),
54                    msg.tcomment,
55                    msg.location,
56                )
57            yield msg
58