Merge branch '2.11.x'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parents 91eb39b, 9ec465b · Browse files · 5 files·+127 added−33 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+127 added−33 removed
- tests:+103 added−0 removed
- other:+24 added−33 removed
Provenance
- Commit
da81281- Tree
88b1e7e- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
91eb39b- Parent 2
9ec465b
5 files changed+127 added−33 removed
modified:src/jinja2/lexer.py+8 added-5 removed
635 unmodified lines636 source_length = len(source)637 balancing_stack = []638 lstrip_unless_re = self.lstrip_unless_re639 newlines_stripped = 0640+ line_starting = True641 642 while 1:643 # tokenizer loop644 for regex, tokens, new_state in statetokens:41 unmodified lines686 and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)687 ):688 # The start of text between the last newline and the tag.689 l_pos = text.rfind("\n") + 1690+ if l_pos > 0 or line_starting:691+ # If there's only whitespace between the newline and the692+ # tag, strip it.693+ if not lstrip_unless_re.search(text, l_pos):694+ groups = (text[:l_pos],) + groups[1:]695 690- # If there's only whitespace between the newline and the691- # tag, strip it.692- if not lstrip_unless_re.search(text, l_pos):693- groups = (text[:l_pos],) + groups[1:]694-696 for idx, token in enumerate(tokens):697 # failure group698 if token.__class__ is Failure:699 raise token(lineno, filename)47 unmodified lines747 if data or tokens not in ignore_if_empty:748 yield lineno, tokens, data749 lineno += data.count("\n")750 751+ line_starting = m.group()[-1:] == "\n"752+753 # fetch new position into new variable so that we can check754 # if there is a internal parsing error which would result755 # in an infinite loop756 pos2 = m.end()41 unmodified linesmodified:src/jinja2/nativetypes.py+7 added-25 removed
1-import types1 from ast import literal_eval2 from itertools import chain3 from itertools import islice4 3 unmodified lines8 from .environment import Environment9 from .environment import Template10 11 13-def native_concat(nodes, preserve_quotes=True):12+def native_concat(nodes):13 """Return a native Python type from the list of compiled nodes. If14 the result is a single node, its value is returned. Otherwise, the15 nodes are concatenated as strings. If the result can be parsed with16 :func:`ast.literal_eval`, the parsed value is returned. Otherwise,17 the string is returned.18 19 :param nodes: Iterable of nodes to concatenate.21- :param preserve_quotes: Whether to re-wrap literal strings with22- quotes, to preserve quotes around expressions for later parsing.23- Should be ``False`` in :meth:`NativeEnvironment.render`.20 """21 head = list(islice(nodes, 2))22 23 if not head:1 unmodified line25 26 if len(head) == 1:27 raw = head[0]28 else:33- if isinstance(nodes, types.GeneratorType):34- nodes = chain(head, nodes)35- raw = "".join([str(v) for v in nodes])29+ raw = "".join([str(v) for v in chain(head, nodes)])30 31 try:38- literal = literal_eval(raw)32+ return literal_eval(raw)33 except (ValueError, SyntaxError, MemoryError):34 return raw35 42- # If literal_eval returned a string, re-wrap with the original43- # quote character to avoid dropping quotes between expression nodes.44- # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should45- # be ('a', 'b').46- if preserve_quotes and isinstance(literal, str):47- quote = raw[0]48- return f"{quote}{literal}{quote}"36 50- return literal51-52-37 class NativeCodeGenerator(CodeGenerator):38 """A code generator which renders Python types by not adding55- ``str()`` around output nodes, and using :func:`native_concat`56- to convert complex strings back to Python types if possible.39+ ``str()`` around output nodes.40 """41 42 @staticmethod43 def _default_finalize(value):44 return value45 46 def _output_const_repr(self, group):64- return repr(native_concat(group))47+ return repr("".join([str(v) for v in group]))48 49 def _output_child_to_const(self, node, frame, finalize):50 const = node.as_const(frame.eval_ctx)51 30 unmodified lines82 with :func:`ast.literal_eval`, the parsed value is returned.83 Otherwise, the string is returned.84 """85 vars = dict(*args, **kwargs)86+87 try:104- return native_concat(105- self.root_render_func(self.new_context(vars)), preserve_quotes=False106- )88+ return native_concat(self.root_render_func(self.new_context(vars)))89 except Exception:90 return self.environment.handle_exception()91 92 1 unmodified linemodified:tests/test_lexnparse.py+92 added
711 unmodified lines712 <%endfor%>"""713 )714 assert tmpl.render(seq=range(5)) == "".join(f"{x}\n" for x in range(5))715 716+ def test_lstrip_blocks_outside_with_new_line(self):717+ env = Environment(lstrip_blocks=True, trim_blocks=False)718+ tmpl = env.from_string(719+ " {% if kvs %}(\n"720+ " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"721+ " ){% endif %}"722+ )723+ out = tmpl.render(kvs=[("a", 1), ("b", 2)])724+ assert out == "(\na=1 b=2 \n )"725+726+ def test_lstrip_trim_blocks_outside_with_new_line(self):727+ env = Environment(lstrip_blocks=True, trim_blocks=True)728+ tmpl = env.from_string(729+ " {% if kvs %}(\n"730+ " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"731+ " ){% endif %}"732+ )733+ out = tmpl.render(kvs=[("a", 1), ("b", 2)])734+ assert out == "(\na=1 b=2 )"735+736+ def test_lstrip_blocks_inside_with_new_line(self):737+ env = Environment(lstrip_blocks=True, trim_blocks=False)738+ tmpl = env.from_string(739+ " ({% if kvs %}\n"740+ " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"741+ " {% endif %})"742+ )743+ out = tmpl.render(kvs=[("a", 1), ("b", 2)])744+ assert out == " (\na=1 b=2 \n)"745+746+ def test_lstrip_trim_blocks_inside_with_new_line(self):747+ env = Environment(lstrip_blocks=True, trim_blocks=True)748+ tmpl = env.from_string(749+ " ({% if kvs %}\n"750+ " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"751+ " {% endif %})"752+ )753+ out = tmpl.render(kvs=[("a", 1), ("b", 2)])754+ assert out == " (a=1 b=2 )"755+756+ def test_lstrip_blocks_without_new_line(self):757+ env = Environment(lstrip_blocks=True, trim_blocks=False)758+ tmpl = env.from_string(759+ " {% if kvs %}"760+ " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}"761+ " {% endif %}"762+ )763+ out = tmpl.render(kvs=[("a", 1), ("b", 2)])764+ assert out == " a=1 b=2 "765+766+ def test_lstrip_trim_blocks_without_new_line(self):767+ env = Environment(lstrip_blocks=True, trim_blocks=True)768+ tmpl = env.from_string(769+ " {% if kvs %}"770+ " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}"771+ " {% endif %}"772+ )773+ out = tmpl.render(kvs=[("a", 1), ("b", 2)])774+ assert out == " a=1 b=2 "775+776+ def test_lstrip_blocks_consume_after_without_new_line(self):777+ env = Environment(lstrip_blocks=True, trim_blocks=False)778+ tmpl = env.from_string(779+ " {% if kvs -%}"780+ " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor -%}"781+ " {% endif -%}"782+ )783+ out = tmpl.render(kvs=[("a", 1), ("b", 2)])784+ assert out == "a=1 b=2 "785+786+ def test_lstrip_trim_blocks_consume_before_without_new_line(self):787+ env = Environment(lstrip_blocks=False, trim_blocks=False)788+ tmpl = env.from_string(789+ " {%- if kvs %}"790+ " {%- for k, v in kvs %}{{ k }}={{ v }} {% endfor -%}"791+ " {%- endif %}"792+ )793+ out = tmpl.render(kvs=[("a", 1), ("b", 2)])794+ assert out == "a=1 b=2 "795+796+ def test_lstrip_trim_blocks_comment(self):797+ env = Environment(lstrip_blocks=True, trim_blocks=True)798+ tmpl = env.from_string(" {# 1 space #}\n {# 2 spaces #} {# 4 spaces #}")799+ out = tmpl.render()800+ assert out == " " * 4801+802+ def test_lstrip_trim_blocks_raw(self):803+ env = Environment(lstrip_blocks=True, trim_blocks=True)804+ tmpl = env.from_string("{{x}}\n{%- raw %} {% endraw -%}\n{{ y }}")805+ out = tmpl.render(x=1, y=2)806+ assert out == "1 2"807+808 def test_php_syntax_with_manual(self, env):809 env = Environment(810 "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True811 )94 unmodified linesmodified:tests/test_nativetypes.py+11 added
1+import math2+3 import pytest4 5 from jinja2.exceptions import UndefinedError6 from jinja2.nativetypes import NativeEnvironment127 unmodified lines134 result = t.render(host="localhost", user="Jinja")135 assert result == "--host='localhost' --user \"Jinja\""136 137 138+def test_no_intermediate_eval(env):139+ t = env.from_string("0.000{{ a }}")140+ result = t.render(a=7)141+ assert isinstance(result, float)142+ # If intermediate eval happened, 0.000 would render 0.0, then 7143+ # would be appended, resulting in 0.07.144+ assert math.isclose(result, 0.0007)145+146+147 def test_spontaneous_env():148 t = NativeTemplate("{{ true }}")149 assert isinstance(t.environment, NativeEnvironment)modified:CHANGES.rst+9 added-3 removed
11 unmodified lines12 - Use :pep:`451` API to load templates with13 :class:`~loaders.PackageLoader`. :issue:`1168`14 15 16-2.11.217-------16+Version 2.11.217+--------------18 19-Unreleased19+Released 2020-04-1320 21 - Fix a bug that caused callable objects with ``__getattr__``, like22 :class:`~unittest.mock.Mock` to be treated as a23 :func:`contextfunction`. :issue:`1145`13 unmodified lines37 - Fix line numbers in error messages when newlines are stripped.38 :pr:`1178`39 - The special ``namespace()`` assignment object in templates works in40 async environments. :issue:`1180`41+- Fix whitespace being removed before tags in the middle of lines when42+ ``lstrip_blocks`` is enabled. :issue:`1138`43+- :class:`~nativetypes.NativeEnvironment` doesn't evaluate44+ intermediate strings during rendering. This prevents early45+ evaluation which could change the value of an expression.46+ :issue:`1186`47 48 49 Version 2.11.150 --------------737 unmodified lines