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