You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

627 lines
24 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2.ext
  4. ~~~~~~~~~~
  5. Jinja extensions allow to add custom tags similar to the way django custom
  6. tags work. By default two example extensions exist: an i18n and a cache
  7. extension.
  8. :copyright: (c) 2017 by the Jinja Team.
  9. :license: BSD.
  10. """
  11. import re
  12. from jinja2 import nodes
  13. from jinja2.defaults import BLOCK_START_STRING, \
  14. BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \
  15. COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \
  16. LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \
  17. KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS
  18. from jinja2.environment import Environment
  19. from jinja2.runtime import concat
  20. from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError
  21. from jinja2.utils import contextfunction, import_string, Markup
  22. from jinja2._compat import with_metaclass, string_types, iteritems
  23. # the only real useful gettext functions for a Jinja template. Note
  24. # that ugettext must be assigned to gettext as Jinja doesn't support
  25. # non unicode strings.
  26. GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')
  27. class ExtensionRegistry(type):
  28. """Gives the extension an unique identifier."""
  29. def __new__(cls, name, bases, d):
  30. rv = type.__new__(cls, name, bases, d)
  31. rv.identifier = rv.__module__ + '.' + rv.__name__
  32. return rv
  33. class Extension(with_metaclass(ExtensionRegistry, object)):
  34. """Extensions can be used to add extra functionality to the Jinja template
  35. system at the parser level. Custom extensions are bound to an environment
  36. but may not store environment specific data on `self`. The reason for
  37. this is that an extension can be bound to another environment (for
  38. overlays) by creating a copy and reassigning the `environment` attribute.
  39. As extensions are created by the environment they cannot accept any
  40. arguments for configuration. One may want to work around that by using
  41. a factory function, but that is not possible as extensions are identified
  42. by their import name. The correct way to configure the extension is
  43. storing the configuration values on the environment. Because this way the
  44. environment ends up acting as central configuration storage the
  45. attributes may clash which is why extensions have to ensure that the names
  46. they choose for configuration are not too generic. ``prefix`` for example
  47. is a terrible name, ``fragment_cache_prefix`` on the other hand is a good
  48. name as includes the name of the extension (fragment cache).
  49. """
  50. #: if this extension parses this is the list of tags it's listening to.
  51. tags = set()
  52. #: the priority of that extension. This is especially useful for
  53. #: extensions that preprocess values. A lower value means higher
  54. #: priority.
  55. #:
  56. #: .. versionadded:: 2.4
  57. priority = 100
  58. def __init__(self, environment):
  59. self.environment = environment
  60. def bind(self, environment):
  61. """Create a copy of this extension bound to another environment."""
  62. rv = object.__new__(self.__class__)
  63. rv.__dict__.update(self.__dict__)
  64. rv.environment = environment
  65. return rv
  66. def preprocess(self, source, name, filename=None):
  67. """This method is called before the actual lexing and can be used to
  68. preprocess the source. The `filename` is optional. The return value
  69. must be the preprocessed source.
  70. """
  71. return source
  72. def filter_stream(self, stream):
  73. """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used
  74. to filter tokens returned. This method has to return an iterable of
  75. :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a
  76. :class:`~jinja2.lexer.TokenStream`.
  77. In the `ext` folder of the Jinja2 source distribution there is a file
  78. called `inlinegettext.py` which implements a filter that utilizes this
  79. method.
  80. """
  81. return stream
  82. def parse(self, parser):
  83. """If any of the :attr:`tags` matched this method is called with the
  84. parser as first argument. The token the parser stream is pointing at
  85. is the name token that matched. This method has to return one or a
  86. list of multiple nodes.
  87. """
  88. raise NotImplementedError()
  89. def attr(self, name, lineno=None):
  90. """Return an attribute node for the current extension. This is useful
  91. to pass constants on extensions to generated template code.
  92. ::
  93. self.attr('_my_attribute', lineno=lineno)
  94. """
  95. return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)
  96. def call_method(self, name, args=None, kwargs=None, dyn_args=None,
  97. dyn_kwargs=None, lineno=None):
  98. """Call a method of the extension. This is a shortcut for
  99. :meth:`attr` + :class:`jinja2.nodes.Call`.
  100. """
  101. if args is None:
  102. args = []
  103. if kwargs is None:
  104. kwargs = []
  105. return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,
  106. dyn_args, dyn_kwargs, lineno=lineno)
  107. @contextfunction
  108. def _gettext_alias(__context, *args, **kwargs):
  109. return __context.call(__context.resolve('gettext'), *args, **kwargs)
  110. def _make_new_gettext(func):
  111. @contextfunction
  112. def gettext(__context, __string, **variables):
  113. rv = __context.call(func, __string)
  114. if __context.eval_ctx.autoescape:
  115. rv = Markup(rv)
  116. return rv % variables
  117. return gettext
  118. def _make_new_ngettext(func):
  119. @contextfunction
  120. def ngettext(__context, __singular, __plural, __num, **variables):
  121. variables.setdefault('num', __num)
  122. rv = __context.call(func, __singular, __plural, __num)
  123. if __context.eval_ctx.autoescape:
  124. rv = Markup(rv)
  125. return rv % variables
  126. return ngettext
  127. class InternationalizationExtension(Extension):
  128. """This extension adds gettext support to Jinja2."""
  129. tags = set(['trans'])
  130. # TODO: the i18n extension is currently reevaluating values in a few
  131. # situations. Take this example:
  132. # {% trans count=something() %}{{ count }} foo{% pluralize
  133. # %}{{ count }} fooss{% endtrans %}
  134. # something is called twice here. One time for the gettext value and
  135. # the other time for the n-parameter of the ngettext function.
  136. def __init__(self, environment):
  137. Extension.__init__(self, environment)
  138. environment.globals['_'] = _gettext_alias
  139. environment.extend(
  140. install_gettext_translations=self._install,
  141. install_null_translations=self._install_null,
  142. install_gettext_callables=self._install_callables,
  143. uninstall_gettext_translations=self._uninstall,
  144. extract_translations=self._extract,
  145. newstyle_gettext=False
  146. )
  147. def _install(self, translations, newstyle=None):
  148. gettext = getattr(translations, 'ugettext', None)
  149. if gettext is None:
  150. gettext = translations.gettext
  151. ngettext = getattr(translations, 'ungettext', None)
  152. if ngettext is None:
  153. ngettext = translations.ngettext
  154. self._install_callables(gettext, ngettext, newstyle)
  155. def _install_null(self, newstyle=None):
  156. self._install_callables(
  157. lambda x: x,
  158. lambda s, p, n: (n != 1 and (p,) or (s,))[0],
  159. newstyle
  160. )
  161. def _install_callables(self, gettext, ngettext, newstyle=None):
  162. if newstyle is not None:
  163. self.environment.newstyle_gettext = newstyle
  164. if self.environment.newstyle_gettext:
  165. gettext = _make_new_gettext(gettext)
  166. ngettext = _make_new_ngettext(ngettext)
  167. self.environment.globals.update(
  168. gettext=gettext,
  169. ngettext=ngettext
  170. )
  171. def _uninstall(self, translations):
  172. for key in 'gettext', 'ngettext':
  173. self.environment.globals.pop(key, None)
  174. def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):
  175. if isinstance(source, string_types):
  176. source = self.environment.parse(source)
  177. return extract_from_ast(source, gettext_functions)
  178. def parse(self, parser):
  179. """Parse a translatable tag."""
  180. lineno = next(parser.stream).lineno
  181. num_called_num = False
  182. # find all the variables referenced. Additionally a variable can be
  183. # defined in the body of the trans block too, but this is checked at
  184. # a later state.
  185. plural_expr = None
  186. plural_expr_assignment = None
  187. variables = {}
  188. trimmed = None
  189. while parser.stream.current.type != 'block_end':
  190. if variables:
  191. parser.stream.expect('comma')
  192. # skip colon for python compatibility
  193. if parser.stream.skip_if('colon'):
  194. break
  195. name = parser.stream.expect('name')
  196. if name.value in variables:
  197. parser.fail('translatable variable %r defined twice.' %
  198. name.value, name.lineno,
  199. exc=TemplateAssertionError)
  200. # expressions
  201. if parser.stream.current.type == 'assign':
  202. next(parser.stream)
  203. variables[name.value] = var = parser.parse_expression()
  204. elif trimmed is None and name.value in ('trimmed', 'notrimmed'):
  205. trimmed = name.value == 'trimmed'
  206. continue
  207. else:
  208. variables[name.value] = var = nodes.Name(name.value, 'load')
  209. if plural_expr is None:
  210. if isinstance(var, nodes.Call):
  211. plural_expr = nodes.Name('_trans', 'load')
  212. variables[name.value] = plural_expr
  213. plural_expr_assignment = nodes.Assign(
  214. nodes.Name('_trans', 'store'), var)
  215. else:
  216. plural_expr = var
  217. num_called_num = name.value == 'num'
  218. parser.stream.expect('block_end')
  219. plural = None
  220. have_plural = False
  221. referenced = set()
  222. # now parse until endtrans or pluralize
  223. singular_names, singular = self._parse_block(parser, True)
  224. if singular_names:
  225. referenced.update(singular_names)
  226. if plural_expr is None:
  227. plural_expr = nodes.Name(singular_names[0], 'load')
  228. num_called_num = singular_names[0] == 'num'
  229. # if we have a pluralize block, we parse that too
  230. if parser.stream.current.test('name:pluralize'):
  231. have_plural = True
  232. next(parser.stream)
  233. if parser.stream.current.type != 'block_end':
  234. name = parser.stream.expect('name')
  235. if name.value not in variables:
  236. parser.fail('unknown variable %r for pluralization' %
  237. name.value, name.lineno,
  238. exc=TemplateAssertionError)
  239. plural_expr = variables[name.value]
  240. num_called_num = name.value == 'num'
  241. parser.stream.expect('block_end')
  242. plural_names, plural = self._parse_block(parser, False)
  243. next(parser.stream)
  244. referenced.update(plural_names)
  245. else:
  246. next(parser.stream)
  247. # register free names as simple name expressions
  248. for var in referenced:
  249. if var not in variables:
  250. variables[var] = nodes.Name(var, 'load')
  251. if not have_plural:
  252. plural_expr = None
  253. elif plural_expr is None:
  254. parser.fail('pluralize without variables', lineno)
  255. if trimmed is None:
  256. trimmed = self.environment.policies['ext.i18n.trimmed']
  257. if trimmed:
  258. singular = self._trim_whitespace(singular)
  259. if plural:
  260. plural = self._trim_whitespace(plural)
  261. node = self._make_node(singular, plural, variables, plural_expr,
  262. bool(referenced),
  263. num_called_num and have_plural)
  264. node.set_lineno(lineno)
  265. if plural_expr_assignment is not None:
  266. return [plural_expr_assignment, node]
  267. else:
  268. return node
  269. def _trim_whitespace(self, string, _ws_re=re.compile(r'\s*\n\s*')):
  270. return _ws_re.sub(' ', string.strip())
  271. def _parse_block(self, parser, allow_pluralize):
  272. """Parse until the next block tag with a given name."""
  273. referenced = []
  274. buf = []
  275. while 1:
  276. if parser.stream.current.type == 'data':
  277. buf.append(parser.stream.current.value.replace('%', '%%'))
  278. next(parser.stream)
  279. elif parser.stream.current.type == 'variable_begin':
  280. next(parser.stream)
  281. name = parser.stream.expect('name').value
  282. referenced.append(name)
  283. buf.append('%%(%s)s' % name)
  284. parser.stream.expect('variable_end')
  285. elif parser.stream.current.type == 'block_begin':
  286. next(parser.stream)
  287. if parser.stream.current.test('name:endtrans'):
  288. break
  289. elif parser.stream.current.test('name:pluralize'):
  290. if allow_pluralize:
  291. break
  292. parser.fail('a translatable section can have only one '
  293. 'pluralize section')
  294. parser.fail('control structures in translatable sections are '
  295. 'not allowed')
  296. elif parser.stream.eos:
  297. parser.fail('unclosed translation block')
  298. else:
  299. assert False, 'internal parser error'
  300. return referenced, concat(buf)
  301. def _make_node(self, singular, plural, variables, plural_expr,
  302. vars_referenced, num_called_num):
  303. """Generates a useful node from the data provided."""
  304. # no variables referenced? no need to escape for old style
  305. # gettext invocations only if there are vars.
  306. if not vars_referenced and not self.environment.newstyle_gettext:
  307. singular = singular.replace('%%', '%')
  308. if plural:
  309. plural = plural.replace('%%', '%')
  310. # singular only:
  311. if plural_expr is None:
  312. gettext = nodes.Name('gettext', 'load')
  313. node = nodes.Call(gettext, [nodes.Const(singular)],
  314. [], None, None)
  315. # singular and plural
  316. else:
  317. ngettext = nodes.Name('ngettext', 'load')
  318. node = nodes.Call(ngettext, [
  319. nodes.Const(singular),
  320. nodes.Const(plural),
  321. plural_expr
  322. ], [], None, None)
  323. # in case newstyle gettext is used, the method is powerful
  324. # enough to handle the variable expansion and autoescape
  325. # handling itself
  326. if self.environment.newstyle_gettext:
  327. for key, value in iteritems(variables):
  328. # the function adds that later anyways in case num was
  329. # called num, so just skip it.
  330. if num_called_num and key == 'num':
  331. continue
  332. node.kwargs.append(nodes.Keyword(key, value))
  333. # otherwise do that here
  334. else:
  335. # mark the return value as safe if we are in an
  336. # environment with autoescaping turned on
  337. node = nodes.MarkSafeIfAutoescape(node)
  338. if variables:
  339. node = nodes.Mod(node, nodes.Dict([
  340. nodes.Pair(nodes.Const(key), value)
  341. for key, value in variables.items()
  342. ]))
  343. return nodes.Output([node])
  344. class ExprStmtExtension(Extension):
  345. """Adds a `do` tag to Jinja2 that works like the print statement just
  346. that it doesn't print the return value.
  347. """
  348. tags = set(['do'])
  349. def parse(self, parser):
  350. node = nodes.ExprStmt(lineno=next(parser.stream).lineno)
  351. node.node = parser.parse_tuple()
  352. return node
  353. class LoopControlExtension(Extension):
  354. """Adds break and continue to the template engine."""
  355. tags = set(['break', 'continue'])
  356. def parse(self, parser):
  357. token = next(parser.stream)
  358. if token.value == 'break':
  359. return nodes.Break(lineno=token.lineno)
  360. return nodes.Continue(lineno=token.lineno)
  361. class WithExtension(Extension):
  362. pass
  363. class AutoEscapeExtension(Extension):
  364. pass
  365. def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,
  366. babel_style=True):
  367. """Extract localizable strings from the given template node. Per
  368. default this function returns matches in babel style that means non string
  369. parameters as well as keyword arguments are returned as `None`. This
  370. allows Babel to figure out what you really meant if you are using
  371. gettext functions that allow keyword arguments for placeholder expansion.
  372. If you don't want that behavior set the `babel_style` parameter to `False`
  373. which causes only strings to be returned and parameters are always stored
  374. in tuples. As a consequence invalid gettext calls (calls without a single
  375. string parameter or string parameters after non-string parameters) are
  376. skipped.
  377. This example explains the behavior:
  378. >>> from jinja2 import Environment
  379. >>> env = Environment()
  380. >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')
  381. >>> list(extract_from_ast(node))
  382. [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]
  383. >>> list(extract_from_ast(node, babel_style=False))
  384. [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]
  385. For every string found this function yields a ``(lineno, function,
  386. message)`` tuple, where:
  387. * ``lineno`` is the number of the line on which the string was found,
  388. * ``function`` is the name of the ``gettext`` function used (if the
  389. string was extracted from embedded Python code), and
  390. * ``message`` is the string itself (a ``unicode`` object, or a tuple
  391. of ``unicode`` objects for functions with multiple string arguments).
  392. This extraction function operates on the AST and is because of that unable
  393. to extract any comments. For comment support you have to use the babel
  394. extraction interface or extract comments yourself.
  395. """
  396. for node in node.find_all(nodes.Call):
  397. if not isinstance(node.node, nodes.Name) or \
  398. node.node.name not in gettext_functions:
  399. continue
  400. strings = []
  401. for arg in node.args:
  402. if isinstance(arg, nodes.Const) and \
  403. isinstance(arg.value, string_types):
  404. strings.append(arg.value)
  405. else:
  406. strings.append(None)
  407. for arg in node.kwargs:
  408. strings.append(None)
  409. if node.dyn_args is not None:
  410. strings.append(None)
  411. if node.dyn_kwargs is not None:
  412. strings.append(None)
  413. if not babel_style:
  414. strings = tuple(x for x in strings if x is not None)
  415. if not strings:
  416. continue
  417. else:
  418. if len(strings) == 1:
  419. strings = strings[0]
  420. else:
  421. strings = tuple(strings)
  422. yield node.lineno, node.node.name, strings
  423. class _CommentFinder(object):
  424. """Helper class to find comments in a token stream. Can only
  425. find comments for gettext calls forwards. Once the comment
  426. from line 4 is found, a comment for line 1 will not return a
  427. usable value.
  428. """
  429. def __init__(self, tokens, comment_tags):
  430. self.tokens = tokens
  431. self.comment_tags = comment_tags
  432. self.offset = 0
  433. self.last_lineno = 0
  434. def find_backwards(self, offset):
  435. try:
  436. for _, token_type, token_value in \
  437. reversed(self.tokens[self.offset:offset]):
  438. if token_type in ('comment', 'linecomment'):
  439. try:
  440. prefix, comment = token_value.split(None, 1)
  441. except ValueError:
  442. continue
  443. if prefix in self.comment_tags:
  444. return [comment.rstrip()]
  445. return []
  446. finally:
  447. self.offset = offset
  448. def find_comments(self, lineno):
  449. if not self.comment_tags or self.last_lineno > lineno:
  450. return []
  451. for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset:]):
  452. if token_lineno > lineno:
  453. return self.find_backwards(self.offset + idx)
  454. return self.find_backwards(len(self.tokens))
  455. def babel_extract(fileobj, keywords, comment_tags, options):
  456. """Babel extraction method for Jinja templates.
  457. .. versionchanged:: 2.3
  458. Basic support for translation comments was added. If `comment_tags`
  459. is now set to a list of keywords for extraction, the extractor will
  460. try to find the best preceeding comment that begins with one of the
  461. keywords. For best results, make sure to not have more than one
  462. gettext call in one line of code and the matching comment in the
  463. same line or the line before.
  464. .. versionchanged:: 2.5.1
  465. The `newstyle_gettext` flag can be set to `True` to enable newstyle
  466. gettext calls.
  467. .. versionchanged:: 2.7
  468. A `silent` option can now be provided. If set to `False` template
  469. syntax errors are propagated instead of being ignored.
  470. :param fileobj: the file-like object the messages should be extracted from
  471. :param keywords: a list of keywords (i.e. function names) that should be
  472. recognized as translation functions
  473. :param comment_tags: a list of translator tags to search for and include
  474. in the results.
  475. :param options: a dictionary of additional options (optional)
  476. :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.
  477. (comments will be empty currently)
  478. """
  479. extensions = set()
  480. for extension in options.get('extensions', '').split(','):
  481. extension = extension.strip()
  482. if not extension:
  483. continue
  484. extensions.add(import_string(extension))
  485. if InternationalizationExtension not in extensions:
  486. extensions.add(InternationalizationExtension)
  487. def getbool(options, key, default=False):
  488. return options.get(key, str(default)).lower() in \
  489. ('1', 'on', 'yes', 'true')
  490. silent = getbool(options, 'silent', True)
  491. environment = Environment(
  492. options.get('block_start_string', BLOCK_START_STRING),
  493. options.get('block_end_string', BLOCK_END_STRING),
  494. options.get('variable_start_string', VARIABLE_START_STRING),
  495. options.get('variable_end_string', VARIABLE_END_STRING),
  496. options.get('comment_start_string', COMMENT_START_STRING),
  497. options.get('comment_end_string', COMMENT_END_STRING),
  498. options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,
  499. options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,
  500. getbool(options, 'trim_blocks', TRIM_BLOCKS),
  501. getbool(options, 'lstrip_blocks', LSTRIP_BLOCKS),
  502. NEWLINE_SEQUENCE,
  503. getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE),
  504. frozenset(extensions),
  505. cache_size=0,
  506. auto_reload=False
  507. )
  508. if getbool(options, 'trimmed'):
  509. environment.policies['ext.i18n.trimmed'] = True
  510. if getbool(options, 'newstyle_gettext'):
  511. environment.newstyle_gettext = True
  512. source = fileobj.read().decode(options.get('encoding', 'utf-8'))
  513. try:
  514. node = environment.parse(source)
  515. tokens = list(environment.lex(environment.preprocess(source)))
  516. except TemplateSyntaxError as e:
  517. if not silent:
  518. raise
  519. # skip templates with syntax errors
  520. return
  521. finder = _CommentFinder(tokens, comment_tags)
  522. for lineno, func, message in extract_from_ast(node, keywords):
  523. yield lineno, func, message, finder.find_comments(lineno)
  524. #: nicer import names
  525. i18n = InternationalizationExtension
  526. do = ExprStmtExtension
  527. loopcontrols = LoopControlExtension
  528. with_ = WithExtension
  529. autoescape = AutoEscapeExtension