added support for translator comments if extracted via babel.
Before adoption: this commit came in with the history the project adopted, so no landing records it.
--HG-- branch : trunk
authored by Armin Ronacher · committed by Armin Ronacher · parent ac7adf2 · Browse files · 3 files·+72 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+72 added−2 removed
- tests:+17 added−0 removed
- other:+55 added−2 removed
Provenance
- Commit
531578d- Tree
2500862- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
ac7adf2
3 files changed+72 added−2 removed
modified:jinja2/ext.py+54 added-2 removed
365 unmodified lines366 * ``function`` is the name of the ``gettext`` function used (if the367 string was extracted from embedded Python code), and368 * ``message`` is the string itself (a ``unicode`` object, or a tuple369 of ``unicode`` objects for functions with multiple string arguments).370+371+ This extraction function operates on the AST and is because of that unable372+ to extract any comments. For comment support you have to use the babel373+ extraction interface or extract comments yourself.374 """375 for node in node.find_all(nodes.Call):376 if not isinstance(node.node, nodes.Name) or \377 node.node.name not in gettext_functions:25 unmodified lines403 strings = tuple(strings)404 yield node.lineno, node.node.name, strings405 406 407+class _CommentFinder(object):408+ """Helper class to find comments in a token stream. Can only409+ find comments for gettext calls forwards. Once the comment410+ from line 4 is found, a comment for line 1 will not return a411+ usable value.412+ """413+414+ def __init__(self, tokens, comment_tags):415+ self.tokens = tokens416+ self.comment_tags = comment_tags417+ self.offset = 0418+ self.last_lineno = 0419+420+ def find_backwards(self, offset):421+ try:422+ for _, token_type, token_value in \423+ reversed(self.tokens[self.offset:offset]):424+ if token_type in ('comment', 'linecomment'):425+ try:426+ prefix, comment = token_value.split(None, 1)427+ except ValueError:428+ continue429+ if prefix in self.comment_tags:430+ return [comment.rstrip()]431+ return []432+ finally:433+ self.offset = offset434+435+ def find_comments(self, lineno):436+ if not self.comment_tags or self.last_lineno > lineno:437+ return []438+ for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset:]):439+ if token_lineno > lineno:440+ return self.find_backwards(self.offset + idx)441+ return self.find_backwards(len(self.tokens))442+443+444 def babel_extract(fileobj, keywords, comment_tags, options):445 """Babel extraction method for Jinja templates.446 447+ .. versionchanged:: 2.3448+ Basic support for translation comments was added. If `comment_tags`449+ is now set to a list of keywords for extraction, the extractor will450+ try to find the best preceeding comment that begins with one of the451+ keywords. For best results, make sure to not have more than one452+ gettext call in one line of code and the matching comment in the453+ same line or the line before.454+455 :param fileobj: the file-like object the messages should be extracted from456 :param keywords: a list of keywords (i.e. function names) that should be457 recognized as translation functions458 :param comment_tags: a list of translator tags to search for and include410- in the results. (Unused)459+ in the results.460 :param options: a dictionary of additional options (optional)461 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.462 (comments will be empty currently)463 """28 unmodified lines492 493 source = fileobj.read().decode(options.get('encoding', 'utf-8'))494 try:495 node = environment.parse(source)496+ tokens = list(environment.lex(environment.preprocess(source)))497 except TemplateSyntaxError, e:498 # skip templates with syntax errors499 return500+501+ finder = _CommentFinder(tokens, comment_tags)502 for lineno, func, message in extract_from_ast(node, keywords):451- yield lineno, func, message, []503+ yield lineno, func, message, finder.find_comments(lineno)504 505 506 #: nicer import names507 i18n = InternationalizationExtension2 unmodified linesmodified:tests/test_i18n.py+17 added
93 unmodified lines94 (2, 'gettext', u'Hello World', []),95 (3, 'gettext', u'Hello World', []),96 (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])97 ]98+99+100+def test_comment_extract():101+ from jinja2.ext import babel_extract102+ from StringIO import StringIO103+ source = StringIO('''104+ {# trans first #}105+ {{ gettext('Hello World') }}106+ {% trans %}Hello World{% endtrans %}{# trans second #}107+ {#: third #}108+ {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}109+ ''')110+ assert list(babel_extract(source, ('gettext', 'ngettext', '_'), ['trans', ':'], {})) == [111+ (3, 'gettext', u'Hello World', ['first']),112+ (4, 'gettext', u'Hello World', ['second']),113+ (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), ['third'])114+ ]modified:CHANGES+1 added
16 unmodified lines17 - greatly improved error message reporting (#339)18 - implicit tuple expressions can no longer be totally empty.19 This change makes ``{% if %}...{% endif %}`` a syntax error20 now. (#364)21+- added support for translator comments if extracted via babel.22 23 Version 2.2.124 -------------25 (bugfix release, released on September 14th 2009)114 unmodified lines