Skip to content
Myr

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 3fd91e4, da3a9f0 · Browse files · 46 files+387 added−443 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

46 files+387 added−443 removed

  • tests:+12 added−16 removed
  • other:+375 added−427 removed

46 files+387 added−443 removed

added:.devcontainer/devcontainer.json+17 added
added:.devcontainer/on-create-command.sh+7 added
modified:.github/ISSUE_TEMPLATE/bug-report.md+2 added-2 removed
modified:.github/ISSUE_TEMPLATE/config.yml+5 added-8 removed
modified:.github/ISSUE_TEMPLATE/feature-request.md+3 added-3 removed
modified:.github/workflows/lock.yaml+7 added-9 removed
modified:.github/workflows/publish.yaml+19 added-13 removed
modified:.github/workflows/tests.yaml+30 added-23 removed
7 unmodified lines
8 - 'docs/**'9 - '*.md'10 - '*.rst'11 pull_request:12 branches:13 - main14 - '*.x'12 paths-ignore:13 - 'docs/**'14 - '*.md'15 - '*.rst'16jobs:17 tests:21 name: ${{ matrix.name }}22 runs-on: ${{ matrix.os }}18 name: ${{ matrix.name || matrix.python }}19 runs-on: ${{ matrix.os || 'ubuntu-latest' }}20 strategy:21 fail-fast: false22 matrix:23 include:27 - {name: Linux, python: '3.11', os: ubuntu-latest, tox: py311}28 - {name: Windows, python: '3.11', os: windows-latest, tox: py311}29 - {name: Mac, python: '3.11', os: macos-latest, tox: py311}30 - {name: '3.12-dev', python: '3.12-dev', os: ubuntu-latest, tox: py312}31 - {name: '3.10', python: '3.10', os: ubuntu-latest, tox: py310}32 - {name: '3.9', python: '3.9', os: ubuntu-latest, tox: py39}33 - {name: '3.8', python: '3.8', os: ubuntu-latest, tox: py38}34 - {name: '3.7', python: '3.7', os: ubuntu-latest, tox: py37}35 - {name: 'PyPy', python: 'pypy-3.10', os: ubuntu-latest, tox: pypy310}36 - {name: Typing, python: '3.11', os: ubuntu-latest, tox: typing}24 - {python: '3.12'}25 - {name: Windows, python: '3.12', os: windows-latest}26 - {name: Mac, python: '3.12', os: macos-latest}27 - {python: '3.11'}28 - {python: '3.10'}29 - {python: '3.9'}30 - {python: '3.8'}31 - {python: '3.7'}32 - {name: PyPy, python: 'pypy-3.10', tox: pypy310}33 steps:38 - uses: actions/checkout@f43a0e5ff2bd294095638e18286ca9a3d195674439 - uses: actions/setup-python@61a6322f88396a6271a6ee3565807d608ecaddd134 - uses: actions/checkout@9bb56186c3b09b4f86b1c65136769dd318469633 # v4.1.235 - uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.036 with:37 python-version: ${{ matrix.python }}42 cache: 'pip'43 cache-dependency-path: 'requirements/*.txt'38 allow-prereleases: true39 cache: pip40 cache-dependency-path: requirements*/*.txt41 - run: pip install tox42 - run: tox run -e ${{ matrix.tox || format('py{0}', matrix.python) }}43 typing:44 runs-on: ubuntu-latest45 steps:46 - uses: actions/checkout@9bb56186c3b09b4f86b1c65136769dd318469633 # v4.1.247 - uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.048 with:49 python-version: '3.x'50 cache: pip51 cache-dependency-path: requirements*/*.txt52 - name: cache mypy45 uses: actions/cache@88522ab9f39a2ea568f7027eddc7d8d8bc9d59c853 uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.254 with:55 path: ./.mypy_cache48 key: mypy|${{ matrix.python }}|${{ hashFiles('pyproject.toml') }}49 if: matrix.tox == 'typing'56 key: mypy|${{ hashFiles('pyproject.toml') }}57 - run: pip install tox51 - run: tox run -e ${{ matrix.tox }}58 - run: tox run -e typing
modified:.github/dependabot.yml+22 added-7 removed
1version: 22updates:3- package-ecosystem: "github-actions"4 directory: "/"5 schedule:6 interval: "monthly"7 day: "monday"8 time: "16:00"9 timezone: "UTC"3 - package-ecosystem: github-actions4 directory: /5 schedule:6 interval: monthly7 ignore:8 # slsa depends on upload/download v39 - dependency-name: actions/upload-artifact10 versions: '>= 4'11 - dependency-name: actions/download-artifact12 versions: '>= 4'13 groups:14 github-actions:15 patterns:16 - '*'17 - package-ecosystem: pip18 directory: /requirements/19 schedule:20 interval: monthly21 groups:22 python-requirements:23 patterns:24 - '*'
modified:.github/pull_request_template.md+15 added-16 removed
1<!--2Before opening a PR, open a ticket describing the issue or feature the PR will address. Follow the steps in CONTRIBUTING.rst.2Before opening a PR, open a ticket describing the issue or feature the3PR will address. An issue is not required for fixing typos in4documentation, or other simple non-code changes.54Replace this comment with a description of the change. Describe how it addresses the linked ticket.6Replace this comment with a description of the change. Describe how it7addresses the linked ticket.8-->910<!--8Link to relevant issues or previous PRs, one per line. Use "fixes" to automatically close an issue.11Link to relevant issues or previous PRs, one per line. Use "fixes" to12automatically close an issue.1314fixes #<issue number>15-->1611- fixes #<issue number>1217<!--14Ensure each step in CONTRIBUTING.rst is complete by adding an "x" to each box below.18Ensure each step in CONTRIBUTING.rst is complete, especially the following:1916If only docs were changed, these aren't relevant and can be removed.20- Add tests that demonstrate the correct behavior of the change. Tests21 should fail without the change.22- Add or update relevant docs, in the docs folder and in code.23- Add an entry in CHANGES.rst summarizing the change and linking to the issue.24- Add `.. versionchanged::` entries in any relevant code docs.25-->1819Checklist:2021- [ ] Add tests that demonstrate the correct behavior of the change. Tests should fail without the change.22- [ ] Add or update relevant docs, in the docs folder and in code.23- [ ] Add an entry in `CHANGES.rst` summarizing the change and linking to the issue.24- [ ] Add `.. versionchanged::` entries in any relevant code docs.25- [ ] Run `pre-commit` hooks and fix any issues.26- [ ] Run `pytest` and `tox`, no tests failed.
modified:docs/examples/inline_gettext_extension.py-1 removed
3 unmodified lines
4from jinja2.ext import Extension5from jinja2.lexer import count_newlines6from jinja2.lexer import Token788_outside_re = re.compile(r"\\?(gettext|_)\(")9_inside_re = re.compile(r"\\?[()]")1011
60 unmodified lines
modified:docs/conf.py+12 added-9 removed
8 unmodified lines
9release, version = get_version("Jinja2")1011# General --------------------------------------------------------------1213master_doc = "index"13default_role = "code"14extensions = [15 "sphinx.ext.autodoc",16 "sphinx.ext.extlinks",17 "sphinx.ext.intersphinx",17 "pallets_sphinx_themes",18 "sphinxcontrib.log_cabinet",19 "sphinx_issues",19 "pallets_sphinx_themes",20]21autodoc_member_order = "bysource"22autodoc_typehints = "description"22intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}23issues_github_path = "pallets/jinja"23autodoc_preserve_defaults = True24extlinks = {25 "issue": ("https://github.com/pallets/jinja/issues/%s", "#%s"),26 "pr": ("https://github.com/pallets/jinja/pull/%s", "#%s"),27}28intersphinx_mapping = {29 "python": ("https://docs.python.org/3/", None),30}3132# HTML -----------------------------------------------------------------3334html_theme = "jinja"
16 unmodified lines
51html_favicon = "_static/jinja-logo-sidebar.png"52html_logo = "_static/jinja-logo-sidebar.png"53html_title = f"Jinja Documentation ({version})"54html_show_sourcelink = False4849# LaTeX ----------------------------------------------------------------5051latex_documents = [(master_doc, f"Jinja-{version}.tex", html_title, author, "manual")]
modified:docs/license.rst+2 added-1 removed
1BSD-3-Clause License2====================34.. include:: ../LICENSE.rst4.. literalinclude:: ../LICENSE.txt5 :language: text
modified:requirements/dev.txt+1 added-1 removed
44 unmodified lines
45pyproject-api==1.5.246 # via tox47pyproject-hooks==1.0.048 # via build49pyyaml==6.049pyyaml==6.0.150 # via pre-commit51toposort==1.1052 # via pip-compile-multi53tox==4.6.3
11 unmodified lines
modified:src/jinja2/__init__.py+1 added
1"""Jinja is a template engine written in pure Python. It provides a2non-XML syntax that supports inline expressions and an optional3sandboxed environment.4"""56from .bccache import BytecodeCache as BytecodeCache7from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache8from .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache9from .environment import Environment as Environment
29 unmodified lines
modified:src/jinja2/bccache.py+6 added-4 removed
3 unmodified lines
45Situations where this is useful are often forking web applications that6are initialized on the first request.7"""89import errno10import fnmatch11import marshal12import os
7 unmodified lines
20from types import CodeType2122if t.TYPE_CHECKING:23 import typing_extensions as te2425 from .environment import Environment2627 class _MemcachedClient(te.Protocol):26 def get(self, key: str) -> bytes:27 ...28 def get(self, key: str) -> bytes: ...2929 def set(self, key: str, value: bytes, timeout: t.Optional[int] = None) -> None:30 ...30 def set(31 self, key: str, value: bytes, timeout: t.Optional[int] = None32 ) -> None: ...333435bc_version = 536# Magic bytes to identify Jinja bytecode cache files. Contains the
372 unmodified lines
modified:src/jinja2/compiler.py+14 added-10 removed
1"""Compiles nodes from the parser into Python code."""23import typing as t4from contextlib import contextmanager5from functools import update_wrapper6from io import StringIO
17 unmodified lines
24from .visitor import NodeVisitor2526if t.TYPE_CHECKING:27 import typing_extensions as te2829 from .environment import Environment3031F = t.TypeVar("F", bound=t.Callable[..., t.Any])32
28 unmodified lines
61def _make_binop(op: str) -> t.Callable[["CodeGenerator", nodes.BinExpr, "Frame"], None]:62 @optimizeconst63 def visitor(self: "CodeGenerator", node: nodes.BinExpr, frame: Frame) -> None:64 if (63 self.environment.sandboxed64 and op in self.environment.intercepted_binops # type: ignore65 self.environment.sandboxed and op in self.environment.intercepted_binops # type: ignore66 ):67 self.write(f"environment.call_binop(context, {op!r}, ")68 self.visit(node.left, frame)69 self.write(", ")
14 unmodified lines
84) -> t.Callable[["CodeGenerator", nodes.UnaryExpr, "Frame"], None]:85 @optimizeconst86 def visitor(self: "CodeGenerator", node: nodes.UnaryExpr, frame: Frame) -> None:87 if (87 self.environment.sandboxed88 and op in self.environment.intercepted_unops # type: ignore88 self.environment.sandboxed and op in self.environment.intercepted_unops # type: ignore89 ):90 self.write(f"environment.call_unop(context, {op!r}, ")91 self.visit(node.node, frame)92 else:
39 unmodified lines
132133 if type(value) in {tuple, list, set, frozenset}:134 return all(has_safe_repr(v) for v in value)135136 if type(value) is dict:136 if type(value) is dict: # noqa E721137 return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items())138139 return False140
409 unmodified lines
550551 for node in nodes:552 visitor.visit(node)553554 for id_map, names, dependency in (555 (self.filters, visitor.filters, "filters"),554 for id_map, names, dependency in (self.filters, visitor.filters, "filters"), (555 self.tests,556 visitor.tests,557 "tests",556 (557 self.tests,558 visitor.tests,559 "tests",560 ),561 ):562 for name in sorted(names):563 if name not in id_map:564 id_map[name] = self.temporary_identifier()
266 unmodified lines
831 ) -> None:832 assert frame is None, "no root frame allowed"833 eval_ctx = EvalContext(self.environment, self.name)834832 from .runtime import exported, async_exported835 from .runtime import async_exported836 from .runtime import exported837838 if self.environment.is_async:839 exported_names = sorted(exported + async_exported)840 else:
1120 unmodified lines
modified:src/jinja2/environment.py+24 added-16 removed
1"""Classes for managing templates and their runtime and compile time2options.3"""45import os6import typing7import typing as t8import weakref
11 unmodified lines
20from .defaults import BLOCK_END_STRING21from .defaults import BLOCK_START_STRING22from .defaults import COMMENT_END_STRING23from .defaults import COMMENT_START_STRING23from .defaults import DEFAULT_FILTERS24from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined]25from .defaults import DEFAULT_NAMESPACE26from .defaults import DEFAULT_POLICIES26from .defaults import DEFAULT_TESTS27from .defaults import DEFAULT_TESTS # type: ignore[attr-defined]28from .defaults import KEEP_TRAILING_NEWLINE29from .defaults import LINE_COMMENT_PREFIX30from .defaults import LINE_STATEMENT_PREFIX31from .defaults import LSTRIP_BLOCKS
23 unmodified lines
55from .utils import missing5657if t.TYPE_CHECKING:58 import typing_extensions as te5960 from .bccache import BytecodeCache61 from .ext import Extension62 from .loaders import BaseLoader63
36 unmodified lines
100 """Create an empty copy of the given cache."""101 if cache is None:102 return None103102 if type(cache) is dict:104 if type(cache) is dict: # noqa E721105 return {}106107 return LRUCache(cache.capacity) # type: ignore108
564 unmodified lines
673 for ext in self.iter_extensions():674 stream = ext.filter_stream(stream) # type: ignore675676 if not isinstance(stream, TokenStream):675 stream = TokenStream(stream, name, filename) # type: ignore677 stream = TokenStream(stream, name, filename) # type: ignore[unreachable]678679 return stream680681 def _generate(
32 unmodified lines
714 name: t.Optional[str] = None,715 filename: t.Optional[str] = None,716 raw: "te.Literal[False]" = False,717 defer_init: bool = False,716 ) -> CodeType:717 ...718 ) -> CodeType: ...719720 @typing.overload721 def compile(722 self,
1 unmodified line
724 name: t.Optional[str] = None,725 filename: t.Optional[str] = None,726 raw: "te.Literal[True]" = ...,727 defer_init: bool = False,727 ) -> str:728 ...728 ) -> str: ...729730 @internalcode731 def compile(732 self,
126 unmodified lines
859 with open(os.path.join(target, filename), "wb") as f:860 f.write(data.encode("utf8"))861862 if zip is not None:863 from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED863 from zipfile import ZIP_DEFLATED864 from zipfile import ZIP_STORED865 from zipfile import ZipFile866 from zipfile import ZipInfo867868 zip_file = ZipFile(869 target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]870 )
550 unmodified lines
1421 becomes unavailable in async mode.1422 """1423 ctx = self.new_context(vars, shared, locals)1424 return TemplateModule(1422 self, ctx, [x async for x in self.root_render_func(ctx)] # type: ignore1425 self,1426 ctx,1427 [x async for x in self.root_render_func(ctx)], # type: ignore1428 )14291430 @internalcode1431 def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule":
162 unmodified lines
1594 self.disable_buffering()15951596 def dump(1597 self,1593 fp: t.Union[str, t.IO[t.Any]],1598 fp: t.Union[str, t.IO[bytes]],1599 encoding: t.Optional[str] = None,1600 errors: t.Optional[str] = "strict",1601 ) -> None:1602 """Dump the complete stream into a file or file-like object.
9 unmodified lines
1612 if isinstance(fp, str):1613 if encoding is None:1614 encoding = "utf-8"16151611 fp = open(fp, "wb")1616 real_fp: t.IO[bytes] = open(fp, "wb")1617 close = True1618 else:1619 real_fp = fp16201621 try:1622 if encoding is not None:1623 iterable = (x.encode(encoding, errors) for x in self) # type: ignore1624 else:1625 iterable = self # type: ignore16261619 if hasattr(fp, "writelines"):1620 fp.writelines(iterable)1627 if hasattr(real_fp, "writelines"):1628 real_fp.writelines(iterable)1629 else:1630 for item in iterable:1623 fp.write(item)1631 real_fp.write(item)1632 finally:1633 if close:1626 fp.close()1634 real_fp.close()16351636 def disable_buffering(self) -> None:1637 """Disable the output buffering."""1638 self._next = partial(next, self._gen)
39 unmodified lines
modified:src/jinja2/ext.py+10 added-9 removed
1"""Extension API for adding custom tags and behavior."""23import pprint4import re5import typing as t6
11 unmodified lines
18from .utils import pass_context1920if t.TYPE_CHECKING:21 import typing_extensions as te2223 from .lexer import Token24 from .lexer import TokenStream25 from .parser import Parser2627 class _TranslationsBasic(te.Protocol):26 def gettext(self, message: str) -> str:27 ...28 def gettext(self, message: str) -> str: ...2930 def ngettext(self, singular: str, plural: str, n: int) -> str:31 pass3233 class _TranslationsContext(_TranslationsBasic):33 def pgettext(self, context: str, message: str) -> str:34 ...34 def pgettext(self, context: str, message: str) -> str: ...3536 def npgettext(self, context: str, singular: str, plural: str, n: int) -> str:37 ...36 def npgettext(37 self, context: str, singular: str, plural: str, n: int38 ) -> str: ...3940 _SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]4142
175 unmodified lines
218 return pgettext219220221def _make_new_npgettext(221 func: t.Callable[[str, str, str, int], str]222 func: t.Callable[[str, str, str, int], str],223) -> t.Callable[..., str]:224 @pass_context225 def npgettext(226 __context: Context,
67 unmodified lines
294 # Python < 3.8295 pgettext = translations.pgettext296 else:297297 def pgettext(c: str, s: str) -> str:298 def pgettext(c: str, s: str) -> str: # type: ignore[misc]299 return s300301 if hasattr(translations, "npgettext"):302 npgettext = translations.npgettext303 else:304304 def npgettext(c: str, s: str, p: str, n: int) -> str:305 def npgettext(c: str, s: str, p: str, n: int) -> str: # type: ignore[misc]306 return s if n == 1 else p307308 self._install_callables(309 gettext=translations.gettext,
561 unmodified lines
modified:src/jinja2/filters.py+10 added-14 removed
1"""Built-in template filters used with the ``|`` operator."""23import math4import random5import re6import typing
21 unmodified lines
28from .utils import urlize2930if t.TYPE_CHECKING:31 import typing_extensions as te3233 from .environment import Environment34 from .nodes import EvalContext35 from .runtime import Context36 from .sandbox import SandboxedEnvironment # noqa: F401
86 unmodified lines
123 return attrgetter124125126def _prepare_attribute_parts(125 attr: t.Optional[t.Union[str, int]]127 attr: t.Optional[t.Union[str, int]],128) -> t.List[t.Union[str, int]]:129 if attr is None:130 return []131
11 unmodified lines
143 return escape(str(value))144145146def do_urlencode(145 value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]]147 value: t.Union[str, t.Mapping[str, t.Any], t.Iterable[t.Tuple[str, t.Any]]],148) -> str:149 """Quote data for use in a URL path or query using UTF-8.150151 Basic wrapper around :func:`urllib.parse.quote` when given a
1205 unmodified lines
1357 return str(value)135813591360@typing.overload1359def do_reverse(value: str) -> str:1360 ...1361def do_reverse(value: str) -> str: ...136213631364@typing.overload1364def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]":1365 ...1365def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...136613671368def do_reverse(value: t.Union[str, t.Iterable[V]]) -> t.Union[str, t.Iterable[V]]:1369 """Reverse the object or return an iterator that iterates over it the other
50 unmodified lines
1420 value: t.Iterable[t.Any],1421 name: str,1422 *args: t.Any,1423 **kwargs: t.Any,1424) -> t.Iterable[t.Any]:1425 ...1424) -> t.Iterable[t.Any]: ...142514261427@typing.overload1428def sync_do_map(
1 unmodified line
1430 value: t.Iterable[t.Any],1431 *,1432 attribute: str = ...,1433 default: t.Optional[t.Any] = None,1435) -> t.Iterable[t.Any]:1436 ...1434) -> t.Iterable[t.Any]: ...143514361437@pass_context1438def sync_do_map(
51 unmodified lines
1490 value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],1491 name: str,1492 *args: t.Any,1493 **kwargs: t.Any,1496) -> t.Iterable[t.Any]:1497 ...1494) -> t.Iterable[t.Any]: ...149514961497@typing.overload1498def do_map(
1 unmodified line
1500 value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],1501 *,1502 attribute: str = ...,1503 default: t.Optional[t.Any] = None,1507) -> t.Iterable[t.Any]:1508 ...1504) -> t.Iterable[t.Any]: ...150515061507@async_variant(sync_do_map) # type: ignore1508async def do_map(
346 unmodified lines
modified:src/jinja2/lexer.py+2 added
1 unmodified line
2is used to do some preprocessing. It filters out invalid operators like3the bitshift operators we don't allow in templates. It separates4template code and python code in expressions.5"""67import re8import typing as t9from ast import literal_eval10from collections import deque
4 unmodified lines
15from .utils import LRUCache1617if t.TYPE_CHECKING:18 import typing_extensions as te1920 from .environment import Environment2122# cache for the lexers. Exists in order to be able to have multiple23# environments with the same lexer
845 unmodified lines
modified:src/jinja2/loaders.py+1 added
1"""API and implementations for loading templates from different data2sources.3"""45import importlib.util6import os7import posixpath8import sys
656 unmodified lines
modified:src/jinja2/meta.py+1 added
1"""Functions that expose information about templates that might be2interesting for introspection.3"""45import typing as t67from . import nodes8from .compiler import CodeGenerator
104 unmodified lines
modified:src/jinja2/nodes.py+3 added-1 removed
1"""AST nodes generated by the parser for the compiler. Also provides2some node tree helper functions used by the parser and compiler in order3to normalize nodes.4"""56import inspect7import operator8import typing as t9from collections import deque
3 unmodified lines
13from .utils import _PassArg1415if t.TYPE_CHECKING:16 import typing_extensions as te1718 from .environment import Environment1920_NodeBound = t.TypeVar("_NodeBound", bound="Node")21
35 unmodified lines
57 automatically forwarded to the child."""5859 def __new__(mcs, name, bases, d): # type: ignore60 for attr in "fields", "attributes":59 storage: t.List[t.Any] = []61 storage: t.List[t.Tuple[str, ...]] = []62 storage.extend(getattr(bases[0] if bases else object, attr, ()))63 storage.extend(d.get(attr, ()))64 assert len(bases) <= 1, "multiple inheritance not allowed"65 assert len(storage) == len(set(storage)), "layout conflict"
1141 unmodified lines
modified:src/jinja2/optimizer.py+1 added
5 unmodified lines
6want. For example, loop unrolling doesn't work because unrolled loops7would have a different scope. The solution would be a second syntax tree8that stored the scoping rules.9"""1011import typing as t1213from . import nodes14from .visitor import NodeTransformer
34 unmodified lines
modified:src/jinja2/parser.py+4 added-4 removed
1"""Parse tokens from the lexer into nodes for the compiler."""23import typing4import typing as t56from . import nodes
3 unmodified lines
10from .lexer import describe_token_expr1112if t.TYPE_CHECKING:13 import typing_extensions as te1415 from .environment import Environment1617_ImportInclude = t.TypeVar("_ImportInclude", nodes.Import, nodes.Include)18_MacroCall = t.TypeVar("_MacroCall", nodes.Macro, nodes.CallBlock)
439 unmodified lines
458459 @typing.overload460 def parse_assign_target(461 self, with_tuple: bool = ..., name_only: "te.Literal[True]" = ...460 ) -> nodes.Name:461 ...462 ) -> nodes.Name: ...463464 @typing.overload465 def parse_assign_target(466 self,467 with_tuple: bool = True,468 name_only: bool = False,469 extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,470 with_namespace: bool = False,470 ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]:471 ...471 ) -> t.Union[nodes.NSRef, nodes.Name, nodes.Tuple]: ...472473 def parse_assign_target(474 self,475 with_tuple: bool = True,
566 unmodified lines
modified:src/jinja2/runtime.py+5 added-3 removed
1"""The runtime functions and state used by compiled templates."""23import functools4import sys5import typing as t6from collections import abc
21 unmodified lines
28F = t.TypeVar("F", bound=t.Callable[..., t.Any])2930if t.TYPE_CHECKING:31 import logging3233 import typing_extensions as te3435 from .environment import Environment3637 class LoopRenderFunc(te.Protocol):38 def __call__(39 self,40 reciter: t.Iterable[V],41 loop_render_func: "LoopRenderFunc",42 depth: int = 0,40 ) -> str:41 ...43 ) -> str: ...444546# these variables are exported to the template runtime47exported = [
542 unmodified lines
590 _iterator: t.AsyncIterator[t.Any] # type: ignore591592 @staticmethod593 def _to_iterator( # type: ignore592 iterable: t.Union[t.Iterable[V], t.AsyncIterable[V]]594 iterable: t.Union[t.Iterable[V], t.AsyncIterable[V]],595 ) -> t.AsyncIterator[V]:596 return auto_aiter(iterable)597598 @property
458 unmodified lines
modified:src/jinja2/sandbox.py+2 added-1 removed
1"""A sandbox layer that ensures unsafe operations cannot be performed.2Useful when the template itself comes from an untrusted source.3"""45import operator6import types7import typing as t7from _string import formatter_field_name_split # type: ignore8from collections import abc9from collections import deque10from string import Formatter1112from _string import formatter_field_name_split # type: ignore13from markupsafe import EscapeFormatter14from markupsafe import Markup1516from .environment import Environment
413 unmodified lines
modified:src/jinja2/tests.py+2 added-1 removed
1"""Built-in template tests used with the ``is`` operator."""23import operator4import typing as t5from collections import abc6from numbers import Number
162 unmodified lines
169 that are iterable.170 """171 try:172 len(value)172 value.__getitem__173 value.__getitem__ # noqa B018174 except Exception:175 return False176177 return True
79 unmodified lines
modified:src/jinja2/utils.py+1 added-3 removed
448 unmodified lines
449 def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:450 self.__dict__.update(d)451 self._postinit()452453 def __getnewargs__(454 self,455 ) -> t.Tuple[int,]:453 def __getnewargs__(self) -> t.Tuple[t.Any, ...]:454 return (self.capacity,)455456 def copy(self) -> "LRUCache":457 """Return a shallow copy of the instance."""
298 unmodified lines
modified:src/jinja2/visitor.py+2 added-2 removed
1"""API for traversing the AST nodes. Implemented by the compiler and2meta introspection.3"""45import typing as t67from .nodes import Node89if t.TYPE_CHECKING:10 import typing_extensions as te1112 class VisitCallable(te.Protocol):12 def __call__(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any:13 ...13 def __call__(self, node: Node, *args: t.Any, **kwargs: t.Any) -> t.Any: ...141516class NodeVisitor:17 """Walks the abstract syntax tree and call visitor functions for every
75 unmodified lines
modified:tests/test_api.py+3 added-2 removed
148 unmodified lines
149 t = env.from_string("{{ foo }}")150 assert t.render(foo="<foo>") == "<foo>"151152 def test_sandbox_max_range(self, env):153 from jinja2.sandbox import SandboxedEnvironment, MAX_RANGE153 from jinja2.sandbox import MAX_RANGE154 from jinja2.sandbox import SandboxedEnvironment155156 env = SandboxedEnvironment()157 t = env.from_string("{% for item in range(total) %}{{ item }}{% endfor %}")158
105 unmodified lines
264 pytest.raises(UndefinedError, t.render, test=test)265266 def test_undefined_and_special_attributes(self):267 with pytest.raises(AttributeError):267 Undefined("Foo").__dict__268 Undefined("Foo").__dict__ # noqa B018269270 def test_undefined_attribute_error(self):271 # Django's LazyObject turns the __class__ attribute into a272 # property that resolves the wrapped function. If that wrapped
163 unmodified lines
modified:tests/test_inheritance.py+8 added-14 removed
363 unmodified lines
364365366class TestBugFix:367 def test_fixed_macro_scoping_bug(self, env):368 assert (369 Environment(370 loader=DictLoader(371 {372 "test.html": """\368 assert Environment(369 loader=DictLoader(370 {371 "test.html": """\372 {% extends 'details.html' %}373374 {% macro my_macro() %}375 my_macro
2 unmodified lines
378 {% block inner_box %}379 {{ my_macro() }}380 {% endblock %}381 """,383 "details.html": """\382 "details.html": """\383 {% extends 'standard.html' %}384385 {% macro my_macro() %}386 my_macro
7 unmodified lines
394 {% endblock %}395 {% endblock %}396 {% endblock %}397 """,399 "standard.html": """398 "standard.html": """399 {% block content %}&nbsp;{% endblock %}400 """,402 }403 )401 }402 )405 .get_template("test.html")406 .render()407 .split()408 == ["outer_box", "my_macro"]409 )403 ).get_template("test.html").render().split() == ["outer_box", "my_macro"]404405 def test_double_extends(self, env):406 """Ensures that a template with more than 1 {% extends ... %} usage407 raises a ``TemplateError``.
3 unmodified lines
modified:tests/test_regression.py+1 added
597 unmodified lines
598 assert tmpl.render(values=[]) == "0"599600 def test_markup_and_chainable_undefined(self):601 from markupsafe import Markup602603 from jinja2.runtime import ChainableUndefined604605 assert str(Markup(ChainableUndefined())) == ""606
139 unmodified lines
modified:.editorconfig+1 added-1 removed
7 unmodified lines
8end_of_line = lf9charset = utf-810max_line_length = 881112[*.{yml,yaml,json,js,css,html}]12[*.{css,html,js,json,jsx,scss,ts,tsx,yaml,yml}]13indent_size = 2
deleted:.flake8-28 removed
1[flake8]2extend-select =3 # bugbear4 B5 # bugbear opinions6 B97 # implicit str concat8 ISC9extend-ignore =10 # slice notation whitespace, invalid11 E20312 # line length, handled by bugbear B95013 E50114 # bare except, handled by bugbear B00115 E72216 # zip with strict=, requires python >= 3.1017 B90518 # string formatting opinion, B028 renamed to B90719 B02820 B90721# up to 88 allowed by bugbear B95022max-line-length = 8023per-file-ignores =24 # __init__ exports names25 src/jinja2/__init__.py: F40126 # not relevant to jinja's compiler27 src/jinja2/compiler.py: B90628 src/jinja2/idtracking.py: B906
modified:.gitignore+8 added-19 removed
1*.so2docs/_build/3*.pyc4*.pyo5*.egg-info/6*.egg7build/1.idea/2.vscode/3.venv*/4venv*/5__pycache__/6dist/9.DS_Store7.coverage*8htmlcov/9.tox/11.cache/12.idea/13env/14venv/15venv-*/16.coverage17.coverage.*18htmlcov19.pytest_cache/20/.vscode/21.mypy_cache10docs/_build/
modified:.pre-commit-config.yaml+7 added-24 removed
1ci:2 autoupdate_branch: "3.1.x"2 autoupdate_schedule: monthly3repos:5 - repo: https://github.com/asottile/pyupgrade6 rev: v3.15.04 - repo: https://github.com/astral-sh/ruff-pre-commit5 rev: v0.4.16 hooks:8 - id: pyupgrade9 args: ["--py37-plus"]10 - repo: https://github.com/asottile/reorder-python-imports11 rev: v3.12.012 hooks:13 - id: reorder-python-imports14 args: ["--application-directories", "src"]15 - repo: https://github.com/psf/black16 rev: 23.12.117 hooks:18 - id: black19 - repo: https://github.com/PyCQA/flake820 rev: 7.0.021 hooks:22 - id: flake823 additional_dependencies: [flake8-bugbear]24 - repo: https://github.com/peterdemin/pip-compile-multi25 rev: v2.6.326 hooks:27 - id: pip-compile-multi-verify7 - id: ruff8 - id: ruff-format9 - repo: https://github.com/pre-commit/pre-commit-hooks29 rev: v4.5.010 rev: v4.6.011 hooks:12 - id: check-merge-conflict13 - id: debug-statements14 - id: fix-byte-order-marker15 - id: trailing-whitespace16 - id: end-of-file-fixer
modified:.readthedocs.yaml+2 added-2 removed
1version: 22build:3 os: ubuntu-20.043 os: ubuntu-22.044 tools:5 python: "3.10"5 python: '3.12'6python:7 install:8 - requirements: requirements/docs.txt9 - method: pip
4 unmodified lines
deleted:CODE_OF_CONDUCT.md-76 removed
1# Contributor Covenant Code of Conduct23## Our Pledge45In the interest of fostering an open and welcoming environment, we as6contributors and maintainers pledge to making participation in our project and7our community a harassment-free experience for everyone, regardless of age, body8size, disability, ethnicity, sex characteristics, gender identity and expression,9level of experience, education, socio-economic status, nationality, personal10appearance, race, religion, or sexual identity and orientation.1112## Our Standards1314Examples of behavior that contributes to creating a positive environment15include:1617* Using welcoming and inclusive language18* Being respectful of differing viewpoints and experiences19* Gracefully accepting constructive criticism20* Focusing on what is best for the community21* Showing empathy towards other community members2223Examples of unacceptable behavior by participants include:2425* The use of sexualized language or imagery and unwelcome sexual attention or26 advances27* Trolling, insulting/derogatory comments, and personal or political attacks28* Public or private harassment29* Publishing others' private information, such as a physical or electronic30 address, without explicit permission31* Other conduct which could reasonably be considered inappropriate in a32 professional setting3334## Our Responsibilities3536Project maintainers are responsible for clarifying the standards of acceptable37behavior and are expected to take appropriate and fair corrective action in38response to any instances of unacceptable behavior.3940Project maintainers have the right and responsibility to remove, edit, or41reject comments, commits, code, wiki edits, issues, and other contributions42that are not aligned to this Code of Conduct, or to ban temporarily or43permanently any contributor for other behaviors that they deem inappropriate,44threatening, offensive, or harmful.4546## Scope4748This Code of Conduct applies both within project spaces and in public spaces49when an individual is representing the project or its community. Examples of50representing a project or community include using an official project e-mail51address, posting via an official social media account, or acting as an appointed52representative at an online or offline event. Representation of a project may be53further defined and clarified by project maintainers.5455## Enforcement5657Instances of abusive, harassing, or otherwise unacceptable behavior may be58reported by contacting the project team at report@palletsprojects.com. All59complaints will be reviewed and investigated and will result in a response that60is deemed necessary and appropriate to the circumstances. The project team is61obligated to maintain confidentiality with regard to the reporter of an incident.62Further details of specific enforcement policies may be posted separately.6364Project maintainers who do not follow or enforce the Code of Conduct in good65faith may face temporary or permanent repercussions as determined by other66members of the project's leadership.6768## Attribution6970This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,71available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html7273[homepage]: https://www.contributor-covenant.org7475For answers to common questions about this code of conduct, see76https://www.contributor-covenant.org/faq
deleted:LICENSE.rst-28 removed
1Copyright 2007 Pallets23Redistribution and use in source and binary forms, with or without4modification, are permitted provided that the following conditions are5met:671. Redistributions of source code must retain the above copyright8 notice, this list of conditions and the following disclaimer.9102. Redistributions in binary form must reproduce the above copyright11 notice, this list of conditions and the following disclaimer in the12 documentation and/or other materials provided with the distribution.13143. Neither the name of the copyright holder nor the names of its15 contributors may be used to endorse or promote products derived from16 this software without specific prior written permission.1718THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
added:LICENSE.txt+28 added
1Copyright 2007 Pallets23Redistribution and use in source and binary forms, with or without4modification, are permitted provided that the following conditions are5met:671. Redistributions of source code must retain the above copyright8 notice, this list of conditions and the following disclaimer.9102. Redistributions in binary form must reproduce the above copyright11 notice, this list of conditions and the following disclaimer in the12 documentation and/or other materials provided with the distribution.13143. Neither the name of the copyright holder nor the names of its15 contributors may be used to endorse or promote products derived from16 this software without specific prior written permission.1718THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
modified:pyproject.toml+31 added-11 removed
1[project]2name = "Jinja2"3description = "A very fast and expressive template engine."4readme = "README.rst"5license = {file = "LICENSE.rst"}4readme = "README.md"5license = {file = "LICENSE.txt"}6maintainers = [{name = "Pallets", email = "contact@palletsprojects.com"}]7classifiers = [8 "Development Status :: 5 - Production/Stable",9 "Environment :: Web Environment",
2 unmodified lines
12 "Operating System :: OS Independent",13 "Programming Language :: Python",14 "Topic :: Internet :: WWW/HTTP :: Dynamic Content",15 "Topic :: Text Processing :: Markup :: HTML",16 "Typing :: Typed",17]18requires-python = ">=3.7"19dependencies = ["MarkupSafe>=2.0"]20dynamic = ["version"]
1 unmodified line
22[project.urls]23Donate = "https://palletsprojects.com/donate"24Documentation = "https://jinja.palletsprojects.com/"25Changes = "https://jinja.palletsprojects.com/changes/"25"Source Code" = "https://github.com/pallets/jinja/"26"Issue Tracker" = "https://github.com/pallets/jinja/issues/"26Source = "https://github.com/pallets/jinja/"27Chat = "https://discord.gg/pallets"2829[project.optional-dependencies]30i18n = ["Babel>=2.7"]3132[project.entry-points."babel.extractors"]33jinja2 = "jinja2.ext:babel_extract[i18n]"3435[build-system]36requires = ["flit_core<4"]37build-backend = "flit_core.buildapi"
6 unmodified lines
44 "docs/",45 "examples/",46 "requirements/",47 "tests/",47 "CHANGES.rst",48 "CHANGES.md",49 "tox.ini",50]51exclude = [52 "docs/_build/",
12 unmodified lines
65[tool.coverage.paths]66source = ["src", "*/site-packages"]6768[tool.mypy]68python_version = "3.7"69python_version = "3.8"70files = ["src/jinja2"]71show_error_codes = true72pretty = true73strict = true74local_partial_types = true75warn_unreachable = true7676[[tool.mypy.overrides]]77module = [78 "jinja2.defaults",79 "markupsafe",77[tool.pyright]78pythonVersion = "3.8"79include = ["src/jinja2"]80typeCheckingMode = "basic"8182[tool.ruff]83src = ["src"]84fix = true85show-fixes = true86output-format = "full"8788[tool.ruff.lint]89select = [90 "B", # flake8-bugbear91 "E", # pycodestyle error92 "F", # pyflakes93 "I", # isort94 "UP", # pyupgrade95 "W", # pycodestyle warning96]81no_implicit_reexport = false97ignore-init-module-imports = true9899[tool.ruff.lint.isort]100force-single-line = true101order-by-type = false
added:README.md+50 added
1# Jinja23Jinja is a fast, expressive, extensible templating engine. Special4placeholders in the template allow writing code similar to Python5syntax. Then the template is passed data to render the final document.67It includes:89- Template inheritance and inclusion.10- Define and import macros within templates.11- HTML templates can use autoescaping to prevent XSS from untrusted12 user input.13- A sandboxed environment can safely render untrusted templates.14- AsyncIO support for generating templates and calling async15 functions.16- I18N support with Babel.17- Templates are compiled to optimized Python code just-in-time and18 cached, or can be compiled ahead-of-time.19- Exceptions point to the correct line in templates to make debugging20 easier.21- Extensible filters, tests, functions, and even syntax.2223Jinja's philosophy is that while application logic belongs in Python if24possible, it shouldn't make the template designer's job difficult by25restricting functionality too much.262728## In A Nutshell2930.. code-block:: jinja3132 {% extends "base.html" %}33 {% block title %}Members{% endblock %}34 {% block content %}35 <ul>36 {% for user in users %}37 <li><a href="{{ user.url }}">{{ user.username }}</a></li>38 {% endfor %}39 </ul>40 {% endblock %}414243## Donate4445The Pallets organization develops and supports Jinja and other popular46packages. In order to grow the community of contributors and users, and47allow the maintainers to devote more time to the projects, [please48donate today][].4950[please donate today]: https://palletsprojects.com/donate
deleted:README.rst-76 removed
1Jinja2=====34Jinja is a fast, expressive, extensible templating engine. Special5placeholders in the template allow writing code similar to Python6syntax. Then the template is passed data to render the final document.78It includes:910- Template inheritance and inclusion.11- Define and import macros within templates.12- HTML templates can use autoescaping to prevent XSS from untrusted13 user input.14- A sandboxed environment can safely render untrusted templates.15- AsyncIO support for generating templates and calling async16 functions.17- I18N support with Babel.18- Templates are compiled to optimized Python code just-in-time and19 cached, or can be compiled ahead-of-time.20- Exceptions point to the correct line in templates to make debugging21 easier.22- Extensible filters, tests, functions, and even syntax.2324Jinja's philosophy is that while application logic belongs in Python if25possible, it shouldn't make the template designer's job difficult by26restricting functionality too much.272829Installing30----------3132Install and update using `pip`_:3334.. code-block:: text3536 $ pip install -U Jinja23738.. _pip: https://pip.pypa.io/en/stable/getting-started/394041In A Nutshell42-------------4344.. code-block:: jinja4546 {% extends "base.html" %}47 {% block title %}Members{% endblock %}48 {% block content %}49 <ul>50 {% for user in users %}51 <li><a href="{{ user.url }}">{{ user.username }}</a></li>52 {% endfor %}53 </ul>54 {% endblock %}555657Donate58------5960The Pallets organization develops and supports Jinja and other popular61packages. In order to grow the community of contributors and users, and62allow the maintainers to devote more time to the projects, `please63donate today`_.6465.. _please donate today: https://palletsprojects.com/donate666768Links69-----7071- Documentation: https://jinja.palletsprojects.com/72- Changes: https://jinja.palletsprojects.com/changes/73- PyPI Releases: https://pypi.org/project/Jinja2/74- Source Code: https://github.com/pallets/jinja/75- Issue Tracker: https://github.com/pallets/jinja/issues/76- Chat: https://discord.gg/pallets
modified:tox.ini+17 added-1 removed
8 unmodified lines
910[testenv]11package = wheel12wheel_build_env = .pkg13constrain_package_deps = true14use_frozen_constraints = true15deps = -r requirements/tests.txt16commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs}1718[testenv:style]
6 unmodified lines
25commands = mypy2627[testenv:docs]28deps = -r requirements/docs.txt27commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html29commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml3031[testenv:update-requirements]32deps =33 pip-tools34 pre-commit35skip_install = true36change_dir = requirements37commands =38 pre-commit autoupdate -j439 pip-compile -U build.in40 pip-compile -U docs.in41 pip-compile -U tests.in42 pip-compile -U typing.in43 pip-compile -U dev.in