babelplugin.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. # ext/babelplugin.py
  2. # Copyright (C) 2006-2016 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: http://babel.edgewall.org/"""
  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': u' '.join(comment_tags),
  15. 'encoding': options.get('input_encoding',
  16. options.get('encoding', None)),
  17. }
  18. super(BabelMakoExtractor, self).__init__()
  19. def __call__(self, fileobj):
  20. return self.process_file(fileobj)
  21. def process_python(self, code, code_lineno, translator_strings):
  22. comment_tags = self.config['comment-tags']
  23. for lineno, funcname, messages, python_translator_comments \
  24. in extract_python(code,
  25. self.keywords, comment_tags, self.options):
  26. yield (code_lineno + (lineno - 1), funcname, messages,
  27. translator_strings + python_translator_comments)
  28. def extract(fileobj, keywords, comment_tags, options):
  29. """Extract messages from Mako templates.
  30. :param fileobj: the file-like object the messages should be extracted from
  31. :param keywords: a list of keywords (i.e. function names) that should be
  32. recognized as translation functions
  33. :param comment_tags: a list of translator tags to search for and include
  34. in the results
  35. :param options: a dictionary of additional options (optional)
  36. :return: an iterator over ``(lineno, funcname, message, comments)`` tuples
  37. :rtype: ``iterator``
  38. """
  39. extractor = BabelMakoExtractor(keywords, comment_tags, options)
  40. for message in extractor(fileobj):
  41. yield message