linguaplugin.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # ext/linguaplugin.py
  2. # Copyright 2006-2025 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. import contextlib
  7. import io
  8. from lingua.extractors import Extractor
  9. from lingua.extractors import get_extractor
  10. from lingua.extractors import Message
  11. from mako.ext.extract import MessageExtractor
  12. class LinguaMakoExtractor(Extractor, MessageExtractor):
  13. """Mako templates"""
  14. use_bytes = False
  15. extensions = [".mako"]
  16. default_config = {"encoding": "utf-8", "comment-tags": ""}
  17. def __call__(self, filename, options, fileobj=None):
  18. self.options = options
  19. self.filename = filename
  20. self.python_extractor = get_extractor("x.py")
  21. if fileobj is None:
  22. ctx = open(filename, "r")
  23. else:
  24. ctx = contextlib.nullcontext(fileobj)
  25. with ctx as file_:
  26. yield from self.process_file(file_)
  27. def process_python(self, code, code_lineno, translator_strings):
  28. source = code.getvalue().strip()
  29. if source.endswith(":"):
  30. if source in ("try:", "else:") or source.startswith("except"):
  31. source = "" # Ignore try/except and else
  32. elif source.startswith("elif"):
  33. source = source[2:] # Replace "elif" with "if"
  34. source += "pass"
  35. code = io.StringIO(source)
  36. for msg in self.python_extractor(
  37. self.filename, self.options, code, code_lineno - 1
  38. ):
  39. if translator_strings:
  40. msg = Message(
  41. msg.msgctxt,
  42. msg.msgid,
  43. msg.msgid_plural,
  44. msg.flags,
  45. " ".join(translator_strings + [msg.comment]),
  46. msg.tcomment,
  47. msg.location,
  48. )
  49. yield msg