linguaplugin.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. import io
  2. from lingua.extractors import Extractor
  3. from lingua.extractors import Message
  4. from lingua.extractors import get_extractor
  5. from mako.ext.extract import MessageExtractor
  6. from mako import compat
  7. class LinguaMakoExtractor(Extractor, MessageExtractor):
  8. '''Mako templates'''
  9. extensions = ['.mako']
  10. default_config = {
  11. 'encoding': 'utf-8',
  12. 'comment-tags': '',
  13. }
  14. def __call__(self, filename, options, fileobj=None):
  15. self.options = options
  16. self.filename = filename
  17. self.python_extractor = get_extractor('x.py')
  18. if fileobj is None:
  19. fileobj = open(filename, 'rb')
  20. return self.process_file(fileobj)
  21. def process_python(self, code, code_lineno, translator_strings):
  22. source = code.getvalue().strip()
  23. if source.endswith(compat.b(':')):
  24. if source in (compat.b('try:'), compat.b('else:')) or source.startswith(compat.b('except')):
  25. source = compat.b('') # Ignore try/except and else
  26. elif source.startswith(compat.b('elif')):
  27. source = source[2:] # Replace "elif" with "if"
  28. source += compat.b('pass')
  29. code = io.BytesIO(source)
  30. for msg in self.python_extractor(
  31. self.filename, self.options, code, code_lineno -1):
  32. if translator_strings:
  33. msg = Message(msg.msgctxt, msg.msgid, msg.msgid_plural,
  34. msg.flags,
  35. compat.u(' ').join(
  36. translator_strings + [msg.comment]),
  37. msg.tcomment, msg.location)
  38. yield msg