babelplugin.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # ext/babelplugin.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. """gettext message extraction via Babel: https://pypi.org/project/Babel/"""
  7. from babel.messages.extract import extract_python
  8. from mako.ext.extract import MessageExtractor
  9. class BabelMakoExtractor(MessageExtractor):
  10. def __init__(self, keywords, comment_tags, options):
  11. self.keywords = keywords
  12. self.options = options
  13. self.config = {
  14. "comment-tags": " ".join(comment_tags),
  15. "encoding": options.get(
  16. "input_encoding", options.get("encoding", None)
  17. ),
  18. }
  19. super().__init__()
  20. def __call__(self, fileobj):
  21. return self.process_file(fileobj)
  22. def process_python(self, code, code_lineno, translator_strings):
  23. comment_tags = self.config["comment-tags"]
  24. for (
  25. lineno,
  26. funcname,
  27. messages,
  28. python_translator_comments,
  29. ) in extract_python(code, self.keywords, comment_tags, self.options):
  30. yield (
  31. code_lineno + (lineno - 1),
  32. funcname,
  33. messages,
  34. translator_strings + python_translator_comments,
  35. )
  36. def extract(fileobj, keywords, comment_tags, options):
  37. """Extract messages from Mako templates.
  38. :param fileobj: the file-like object the messages should be extracted from
  39. :param keywords: a list of keywords (i.e. function names) that should be
  40. recognized as translation functions
  41. :param comment_tags: a list of translator tags to search for and include
  42. in the results
  43. :param options: a dictionary of additional options (optional)
  44. :return: an iterator over ``(lineno, funcname, message, comments)`` tuples
  45. :rtype: ``iterator``
  46. """
  47. extractor = BabelMakoExtractor(keywords, comment_tags, options)
  48. yield from extractor(fileobj)