Merge branch '3.1.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 7f8fb54, 36f9885 · Browse files · 9 files·+69 added−26 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+69 added−26 removed
- tests:+19 added−0 removed
- other:+50 added−26 removed
Provenance
- Commit
3fd91e4- Tree
1d76305- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
7f8fb54- Parent 2
36f9885
9 files changed+69 added−26 removed
modified:.github/workflows/publish.yaml+4 added-7 removed
56 unmodified lines57585960616263646364656666676768697056 unmodified lines # Wait for approval before attempting to upload to PyPI. This allows reviewing the # files in the draft release. environment: 'publish' runs-on: ubuntu-latest permissions: id-token: write steps: - uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # Try uploading to Test PyPI first, in case something fails. - uses: pypa/gh-action-pypi-publish@b7f401de30cb6434a1e19f805ff006643653240e - uses: pypa/gh-action-pypi-publish@2f6f737ca5f74c637829c0f5c3acd0e29ea5e8bf with: repository_url: https://test.pypi.org/legacy/ packages_dir: artifact/ packages-dir: artifact/ - uses: pypa/gh-action-pypi-publish@b7f401de30cb6434a1e19f805ff006643653240e with: packages_dir: artifact/modified:src/jinja2/compiler.py+2 added-2 removed
1404 unmodified lines1405 finalize = None1406 1407 if pass_arg is None:1408 1409- def finalize(value: t.Any) -> t.Any:1409+ def finalize(value: t.Any) -> t.Any: # noqa: F8111410 return default(env_finalize(value))1411 1412 else:1413 src = f"{src}{pass_arg}, "1414 1415 if pass_arg == "environment":1416 1417- def finalize(value: t.Any) -> t.Any:1417+ def finalize(value: t.Any) -> t.Any: # noqa: F8111418 return default(env_finalize(self.environment, value))1419 1420 self._finalize = self._FinalizeInfo(finalize, src)1421 return self._finalize535 unmodified linesmodified:src/jinja2/ext.py+13 added-3 removed
493 unmodified lines494 buf.append(f"%({name})s")495 parser.stream.expect("variable_end")496 elif parser.stream.current.type == "block_begin":497 next(parser.stream)498+ block_name = (499+ parser.stream.current.value498- if parser.stream.current.test("name:endtrans"):500+ if parser.stream.current.type == "name"501+ else None502+ )503+ if block_name == "endtrans":504 break500- elif parser.stream.current.test("name:pluralize"):505+ elif block_name == "pluralize":506 if allow_pluralize:507 break508 parser.fail(509 "a translatable section can have only one pluralize section"510 )511+ elif block_name == "trans":512+ parser.fail(513+ "trans blocks can't be nested; did you mean `endtrans`?"514+ )515 parser.fail(507- "control structures in translatable sections are not allowed"516+ f"control structures in translatable sections are not allowed; "517+ f"saw `{block_name}`"518 )519 elif parser.stream.eos:520 parser.fail("unclosed translation block")521 else:348 unmodified linesmodified:src/jinja2/filters.py+21 added-7 removed
246 unmodified lines247 248 yield from value.items()249 250 251+_space_re = re.compile(r"\s", flags=re.ASCII)252+253+254 @pass_eval_context255 def do_xmlattr(256 eval_ctx: "EvalContext", d: t.Mapping[str, t.Any], autospace: bool = True257 ) -> str:258 """Create an SGML/XML attribute string based on the items in a dict.256- All values that are neither `none` nor `undefined` are automatically257- escaped:259 260+ If any key contains a space, this fails with a ``ValueError``. Values that261+ are neither ``none`` nor ``undefined`` are automatically escaped.262+263 .. sourcecode:: html+jinja264 265 <ul{{ {'class': 'my_list', 'missing': none,266 'id': 'list-%d'|format(variable)}|xmlattr }}>9 unmodified lines276 </ul>277 278 As you can see it automatically prepends a space in front of the item279 if the filter returned something unless the second parameter is false.280+281+ .. versionchanged:: 3.1.3282+ Keys with spaces are not allowed.283 """277- rv = " ".join(278- f'{escape(key)}="{escape(value)}"'279- for key, value in d.items()280- if value is not None and not isinstance(value, Undefined)281- )284+ items = []285 286+ for key, value in d.items():287+ if value is None or isinstance(value, Undefined):288+ continue289+290+ if _space_re.search(key) is not None:291+ raise ValueError(f"Spaces are not allowed in attributes: '{key}'")292+293+ items.append(f'{escape(key)}="{escape(value)}"')294+295+ rv = " ".join(items)296+297 if autospace and rv:298 rv = " " + rv299 300 if eval_ctx.autoescape:1558 unmodified linesmodified:src/jinja2/parser.py+1 added-1 removed
857 unmodified lines858 args.append(None)859 else:860 args.append(None)861 862- return nodes.Slice(lineno=lineno, *args)862+ return nodes.Slice(lineno=lineno, *args) # noqa: B026863 864 def parse_call_args(865 self,866 ) -> t.Tuple[175 unmodified linesmodified:tests/test_ext.py+13 added
5 unmodified lines6 from jinja2 import DictLoader7 from jinja2 import Environment8 from jinja2 import nodes9 from jinja2 import pass_context10+from jinja2 import TemplateSyntaxError11 from jinja2.exceptions import TemplateAssertionError12 from jinja2.ext import Extension13 from jinja2.lexer import count_newlines14 from jinja2.lexer import Token453 unmodified lines468 (2, "pgettext", ("babel", "Hello World"), []),469 (3, "npgettext", ("babel", "%(users)s user", "%(users)s users", None), []),470 ]471 472+ def test_nested_trans_error(self):473+ s = "{% trans %}foo{% trans %}{% endtrans %}"474+ with pytest.raises(TemplateSyntaxError) as excinfo:475+ i18n_env.from_string(s)476+ assert "trans blocks can't be nested" in str(excinfo.value)477 478+ def test_trans_block_error(self):479+ s = "{% trans %}foo{% wibble bar %}{% endwibble %}{% endtrans %}"480+ with pytest.raises(TemplateSyntaxError) as excinfo:481+ i18n_env.from_string(s)482+ assert "saw `wibble`" in str(excinfo.value)483+484+485 class TestScope:486 def test_basic_scope_behavior(self):487 # This is what the old with statement compiled down to488 class ScopeExt(Extension):251 unmodified linesmodified:tests/test_filters.py+6 added
472 unmodified lines473 assert 'foo="42"' in out474 assert 'bar="23"' in out475 assert 'blub:blub="<?>"' in out476 477+ def test_xmlattr_key_with_spaces(self, env):478+ with pytest.raises(ValueError, match="Spaces are not allowed"):479+ env.from_string(480+ "{{ {'src=1 onerror=alert(1)': 'my_class'}|xmlattr }}"481+ ).render()482+483 def test_sort1(self, env):484 tmpl = env.from_string("{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}")485 assert tmpl.render() == "[1, 2, 3]|[3, 2, 1]"486 395 unmodified linesmodified:.pre-commit-config.yaml+5 added-5 removed
123456678910111112131415161617181920202122232425262728292930313233ci: autoupdate_branch: "3.1.x" autoupdate_schedule: monthlyrepos: - repo: https://github.com/asottile/pyupgrade rev: v3.7.0 rev: v3.15.0 hooks: - id: pyupgrade args: ["--py37-plus"] - repo: https://github.com/asottile/reorder-python-imports rev: v3.10.0 rev: v3.12.0 hooks: - id: reorder-python-imports args: ["--application-directories", "src"] - repo: https://github.com/psf/black rev: 23.3.0 rev: 23.12.1 hooks: - id: black - repo: https://github.com/PyCQA/flake8 rev: 6.0.0 rev: 7.0.0 hooks: - id: flake8 additional_dependencies: [flake8-bugbear] - repo: https://github.com/peterdemin/pip-compile-multi rev: v2.6.3 hooks: - id: pip-compile-multi-verify - repo: https://github.com/pre-commit/pre-commit-hooks rev: v4.4.0 rev: v4.5.0 hooks: - id: fix-byte-order-marker - id: trailing-whitespace - id: end-of-file-fixermodified:CHANGES.rst+4 added-1 removed
11 unmodified lines12 13 Version 3.1.314 -------------15 16-Unreleased16+Released 2024-01-1017 18 - Fix compiler error when checking if required blocks in parent templates are19 empty. :pr:`1858`20+- ``xmlattr`` filter does not allow keys with spaces. GHSA-h5c8-rqwp-cp9521+- Make error messages stemming from invalid nesting of ``{% trans %}`` blocks22+ more helpful. :pr:`1918`23 24 25 Version 3.1.226 -------------971 unmodified lines