update project files (#1968)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents e491223, 0ee5eb4 · Browse files · 49 files·+503 added−564 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
49 files+503 added−564 removed
- tests:+12 added−16 removed
- other:+491 added−548 removed
Provenance
- Commit
da3a9f0- Tree
3277a64- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
e491223- Parent 2
0ee5eb4
49 files changed+503 added−564 removed
added:.devcontainer/devcontainer.json+17 added
1234567891011121314151617{ "name": "pallets/jinja", "image": "mcr.microsoft.com/devcontainers/python:3", "customizations": { "vscode": { "settings": { "python.defaultInterpreterPath": "${workspaceFolder}/.venv", "python.terminal.activateEnvInCurrentTerminal": true, "python.terminal.launchArgs": [ "-X", "dev" ] } } }, "onCreateCommand": ".devcontainer/on-create-command.sh"}added:.devcontainer/on-create-command.sh+7 added
1234567#!/bin/bashset -epython3 -m venv --upgrade-deps .venv. .venv/bin/activatepip install -r requirements/dev.txtpip install -e .pre-commit install --install-hooksmodified:.github/ISSUE_TEMPLATE/bug-report.md+2 added-2 removed
2 unmodified lines34567878910111215 unmodified lines2 unmodified linesabout: Report a bug in Jinja (not other projects which depend on Jinja)---
<!--This issue tracker is a tool to address bugs in Jinja itself. Pleaseuse Pallets Discord or Stack Overflow for questions about your own code.This issue tracker is a tool to address bugs in Jinja itself. Please useGitHub Discussions or the Pallets Discord for questions about your own code.
Replace this comment with a clear outline of what the bug is.-->
15 unmodified linesmodified:.github/ISSUE_TEMPLATE/config.yml+5 added-8 removed
12345678934567118blank_issues_enabled: falsecontact_links: - name: Security issue url: security@palletsprojects.com about: Do not report security issues publicly. Email our security contact. - name: Questions url: https://stackoverflow.com/questions/tagged/Jinja?tab=Frequent about: Search for and ask questions about your code on Stack Overflow. - name: Questions and discussions - name: Questions on Discussions url: https://github.com/pallets/jinja/discussions/ about: Ask questions about your own code on the Discussions tab. - name: Questions on Chat url: https://discord.gg/pallets about: Discuss questions about your code on our Discord chat. about: Ask questions about your own code on our Discord chat.modified:.github/ISSUE_TEMPLATE/feature-request.md+3 added-3 removed
3 unmodified lines456788910111213141314153 unmodified lines---
<!--Replace this comment with a description of what the feature should do.Include details such as links relevant specs or previous discussions.Include details such as links to relevant specs or previous discussions.-->
<!--Replace this comment with an example of the problem which this featurewould resolve. Is this problem solvable without changes to Jinja,such as by subclassing or using an extension?would resolve. Is this problem solvable without changes to Jinja, suchas by subclassing or using an extension?-->modified:.github/workflows/lock.yaml+7 added-9 removed
12345123456789101011121413141715161718221920212223name: 'Lock threads'# Lock closed issues that have not received any further activity for# two weeks. This does not close open issues, only humans may do that.# We find that it is easier to respond to new issues with fresh examples# rather than continuing discussions on old issues.name: Lock inactive closed issues# Lock closed issues that have not received any further activity for two weeks.# This does not close open issues, only humans may do that. It is easier to# respond to new issues with fresh examples rather than continuing discussions# on old issues.
on: schedule: - cron: '0 0 * * *'
permissions: issues: write pull-requests: write
concurrency: group: lock
jobs: lock: runs-on: ubuntu-latest steps: - uses: dessant/lock-threads@c1b35aecc5cdb1a34539d14196df55838bb2f836 - uses: dessant/lock-threads@1bf7ec25051fe7c00bdd17e6a7cf3d7bfb7dc771 # v5.0.1 with: issue-inactive-days: 14 pr-inactive-days: 14 discussion-inactive-days: 14modified:.github/workflows/publish.yaml+19 added-13 removed
7 unmodified lines8910111213121314151617161718192021222324252626272829303031323334353636373839404142424344454647474849505152535455565657585959606162636465646566676869707172737 unmodified lines runs-on: ubuntu-latest outputs: hash: ${{ steps.hash.outputs.hash }} steps: - uses: actions/checkout@ac593985615ec2ede58e132d2e21d2b1cbd6127c - uses: actions/setup-python@5ccb29d8773c3f3f653e1705f474dfaa8a06a912 - uses: actions/checkout@9bb56186c3b09b4f86b1c65136769dd318469633 # v4.1.2 - uses: actions/setup-python@82c7e631bb3cdc910f68e0081d67478d79c6982d # v5.1.0 with: python-version: '3.x' cache: 'pip' cache-dependency-path: 'requirements/*.txt' cache: pip cache-dependency-path: requirements*/*.txt - run: pip install -r requirements/build.txt # Use the commit date instead of the current date during the build. - run: echo "SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct)" >> $GITHUB_ENV - run: python -m build # Generate hashes used for provenance. - name: generate hash id: hash run: cd dist && echo "hash=$(sha256sum * | base64 -w0)" >> $GITHUB_OUTPUT - uses: actions/upload-artifact@0b7f8abb1508181956e8e162db84b466c27e18ce - uses: actions/upload-artifact@a8a3f3ad30e3422c9c7b888a15615d19a852ae32 # v3.1.3 with: path: ./dist provenance: needs: ['build'] needs: [build] permissions: actions: read id-token: write contents: write # Can't pin with hash due to how this workflow works. uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.4.0 uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.10.0 with: base64-subjects: ${{ needs.build.outputs.hash }} create-release: # Upload the sdist, wheels, and provenance to a GitHub release. They remain # available as build artifacts for a while as well. needs: ['provenance'] needs: [provenance] runs-on: ubuntu-latest permissions: contents: write steps: - uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a - uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2 - name: create release run: > gh release create --draft --repo ${{ github.repository }} ${{ github.ref_name }} *.intoto.jsonl/* artifact/* env: GH_TOKEN: ${{ github.token }} publish-pypi: needs: ['provenance'] needs: [provenance] # Wait for approval before attempting to upload to PyPI. This allows reviewing the # files in the draft release. environment: 'publish' environment: name: publish url: https://pypi.org/project/Jinja2/${{ github.ref_name }} runs-on: ubuntu-latest permissions: id-token: write steps: - uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a - uses: pypa/gh-action-pypi-publish@2f6f737ca5f74c637829c0f5c3acd0e29ea5e8bf - uses: actions/download-artifact@9bc31d5ccc31df68ecc42ccf4149144866c47d8a # v3.0.2 - uses: pypa/gh-action-pypi-publish@81e9d935c883d0b210363ab89cf05f3894778450 # v1.8.14 with: repository-url: https://test.pypi.org/legacy/ packages-dir: artifact/ - uses: pypa/gh-action-pypi-publish@81e9d935c883d0b210363ab89cf05f3894778450 # v1.8.14 with: packages-dir: artifact/modified:.github/workflows/tests.yaml+30 added-28 removed
7 unmodified lines8 - 'docs/**'9 - '*.md'10 - '*.rst'11 pull_request:12- branches:13- - main14- - '*.x'12 paths-ignore:13 - 'docs/**'14 - '*.md'15 - '*.rst'16 jobs: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@ac593985615ec2ede58e132d2e21d2b1cbd6127c39- - uses: actions/setup-python@5ccb29d8773c3f3f653e1705f474dfaa8a06a91234+ - 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'44- - name: update pip45- run: |46- pip install -U wheel47- pip install -U setuptools48- python -m pip install -U pip38+ 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 mypy50- uses: actions/cache@58c146cc91c5b9e778e71775dfe9bf1442ad9a1253+ uses: actions/cache@0c45773b623bea8c8e75f6c82b208c3cf94ea4f9 # v4.0.254 with:55 path: ./.mypy_cache53- key: mypy|${{ matrix.python }}|${{ hashFiles('setup.cfg') }}54- if: matrix.tox == 'typing'56+ key: mypy|${{ hashFiles('pyproject.toml') }}57 - run: pip install tox56- - run: tox run -e ${{ matrix.tox }}58+ - run: tox run -e typingmodified:.github/dependabot.yml+22 added-7 removed
1 version: 22 updates: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 <!--2-Before opening a PR, open a ticket describing the issue or feature the PR will address. Follow the steps in CONTRIBUTING.rst.2+Before opening a PR, open a ticket describing the issue or feature the3+PR will address. An issue is not required for fixing typos in4+documentation, or other simple non-code changes.5 4-Replace this comment with a description of the change. Describe how it addresses the linked ticket.6+Replace this comment with a description of the change. Describe how it7+addresses the linked ticket.8 -->9 10 <!--8-Link to relevant issues or previous PRs, one per line. Use "fixes" to automatically close an issue.11+Link to relevant issues or previous PRs, one per line. Use "fixes" to12+automatically close an issue.13+14+fixes #<issue number>15 -->16 11-- fixes #<issue number>12-17 <!--14-Ensure each step in CONTRIBUTING.rst is complete by adding an "x" to each box below.18+Ensure each step in CONTRIBUTING.rst is complete, especially the following:19 16-If 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 -->18-19-Checklist:20-21-- [ ] 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 lines4 from jinja2.ext import Extension5 from jinja2.lexer import count_newlines6 from jinja2.lexer import Token7 8-8 _outside_re = re.compile(r"\\?(gettext|_)\(")9 _inside_re = re.compile(r"\\?[()]")10 11 60 unmodified linesmodified:docs/conf.py+12 added-9 removed
8 unmodified lines9 release, version = get_version("Jinja2")10 11 # General --------------------------------------------------------------12 13-master_doc = "index"13+default_role = "code"14 extensions = [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 ]21+autodoc_member_order = "bysource"22 autodoc_typehints = "description"22-intersphinx_mapping = {"python": ("https://docs.python.org/3/", None)}23-issues_github_path = "pallets/jinja"23+autodoc_preserve_defaults = True24+extlinks = {25+ "issue": ("https://github.com/pallets/jinja/issues/%s", "#%s"),26+ "pr": ("https://github.com/pallets/jinja/pull/%s", "#%s"),27+}28+intersphinx_mapping = {29+ "python": ("https://docs.python.org/3/", None),30+}31 32 # HTML -----------------------------------------------------------------33 34 html_theme = "jinja"16 unmodified lines51 html_favicon = "_static/jinja-logo-sidebar.png"52 html_logo = "_static/jinja-logo-sidebar.png"53 html_title = f"Jinja Documentation ({version})"54 html_show_sourcelink = False48-49-# LaTeX ----------------------------------------------------------------50-51-latex_documents = [(master_doc, f"Jinja-{version}.tex", html_title, author, "manual")]modified:docs/license.rst+2 added-1 removed
1 BSD-3-Clause License2 ====================3 4-.. include:: ../LICENSE.rst4+.. literalinclude:: ../LICENSE.txt5+ :language: textmodified:src/jinja2/__init__.py+1 added
1 """Jinja is a template engine written in pure Python. It provides a2 non-XML syntax that supports inline expressions and an optional3 sandboxed environment.4 """5+6 from .bccache import BytecodeCache as BytecodeCache7 from .bccache import FileSystemBytecodeCache as FileSystemBytecodeCache8 from .bccache import MemcachedBytecodeCache as MemcachedBytecodeCache9 from .environment import Environment as Environment29 unmodified linesmodified:src/jinja2/async_utils.py+1 added-1 removed
45 unmodified lines46 47 if need_eval_context:48 wrapper = pass_eval_context(wrapper)49 50- wrapper.jinja_async_variant = True50+ wrapper.jinja_async_variant = True # type: ignore[attr-defined]51 return wrapper52 53 return decorator54 30 unmodified linesmodified:src/jinja2/bccache.py+6 added-4 removed
3 unmodified lines4 5 Situations where this is useful are often forking web applications that6 are initialized on the first request.7 """8+9 import errno10 import fnmatch11 import marshal12 import os7 unmodified lines20 from types import CodeType21 22 if t.TYPE_CHECKING:23 import typing_extensions as te24+25 from .environment import Environment26 27 class _MemcachedClient(te.Protocol):26- def get(self, key: str) -> bytes:27- ...28+ def get(self, key: str) -> bytes: ...29 29- 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: ...33 34 35 bc_version = 536 # Magic bytes to identify Jinja bytecode cache files. Contains the372 unmodified linesmodified:src/jinja2/compiler.py+14 added-10 removed
1 """Compiles nodes from the parser into Python code."""2+3 import typing as t4 from contextlib import contextmanager5 from functools import update_wrapper6 from io import StringIO17 unmodified lines24 from .visitor import NodeVisitor25 26 if t.TYPE_CHECKING:27 import typing_extensions as te28+29 from .environment import Environment30 31 F = t.TypeVar("F", bound=t.Callable[..., t.Any])32 28 unmodified lines61 def _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 lines84 ) -> 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 lines132 133 if type(value) in {tuple, list, set, frozenset}:134 return all(has_safe_repr(v) for v in value)135 136- 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())138 139 return False140 409 unmodified lines550 551 for node in nodes:552 visitor.visit(node)553 554+ 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 lines831 ) -> None:832 assert frame is None, "no root frame allowed"833 eval_ctx = EvalContext(self.environment, self.name)834 832- from .runtime import exported, async_exported835+ from .runtime import async_exported836+ from .runtime import exported837 838 if self.environment.is_async:839 exported_names = sorted(exported + async_exported)840 else:1120 unmodified linesmodified:src/jinja2/environment.py+28 added-20 removed
1 """Classes for managing templates and their runtime and compile time2 options.3 """4+5 import os6 import typing7 import typing as t8 import weakref11 unmodified lines20 from .defaults import BLOCK_END_STRING21 from .defaults import BLOCK_START_STRING22 from .defaults import COMMENT_END_STRING23 from .defaults import COMMENT_START_STRING23-from .defaults import DEFAULT_FILTERS24+from .defaults import DEFAULT_FILTERS # type: ignore[attr-defined]25 from .defaults import DEFAULT_NAMESPACE26 from .defaults import DEFAULT_POLICIES26-from .defaults import DEFAULT_TESTS27+from .defaults import DEFAULT_TESTS # type: ignore[attr-defined]28 from .defaults import KEEP_TRAILING_NEWLINE29 from .defaults import LINE_COMMENT_PREFIX30 from .defaults import LINE_STATEMENT_PREFIX31 from .defaults import LSTRIP_BLOCKS23 unmodified lines55 from .utils import missing56 57 if t.TYPE_CHECKING:58 import typing_extensions as te59+60 from .bccache import BytecodeCache61 from .ext import Extension62 from .loaders import BaseLoader63 16 unmodified lines80 81 82 def create_cache(83 size: int,82-) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:84+) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]:85 """Return the cache class for the given size."""86 if size == 0:87 return None88 3 unmodified lines92 return LRUCache(size) # type: ignore93 94 95 def copy_cache(94- cache: t.Optional[t.MutableMapping],95-) -> t.Optional[t.MutableMapping[t.Tuple[weakref.ref, str], "Template"]]:96+ cache: t.Optional[t.MutableMapping[t.Any, t.Any]],97+) -> t.Optional[t.MutableMapping[t.Tuple["weakref.ref[t.Any]", str], "Template"]]:98 """Create an empty copy of the given cache."""99 if cache is None:100 return None101 100- if type(cache) is dict:102+ if type(cache) is dict: # noqa E721103 return {}104 105 return LRUCache(cache.capacity) # type: ignore106 564 unmodified lines671 for ext in self.iter_extensions():672 stream = ext.filter_stream(stream) # type: ignore673 674 if not isinstance(stream, TokenStream):673- stream = TokenStream(stream, name, filename) # type: ignore675+ stream = TokenStream(stream, name, filename)676 677 return stream678 679 def _generate(32 unmodified lines712 name: t.Optional[str] = None,713 filename: t.Optional[str] = None,714 raw: "te.Literal[False]" = False,715 defer_init: bool = False,714- ) -> CodeType:715- ...716+ ) -> CodeType: ...717 718 @typing.overload719 def compile(720 self,1 unmodified line722 name: t.Optional[str] = None,723 filename: t.Optional[str] = None,724 raw: "te.Literal[True]" = ...,725 defer_init: bool = False,725- ) -> str:726- ...726+ ) -> str: ...727 728 @internalcode729 def compile(730 self,82 unmodified lines813 return TemplateExpression(template, undefined_to_none)814 815 def compile_templates(816 self,817- target: t.Union[str, os.PathLike],817+ target: t.Union[str, "os.PathLike[str]"],818 extensions: t.Optional[t.Collection[str]] = None,819 filter_func: t.Optional[t.Callable[[str], bool]] = None,820 zip: t.Optional[str] = "deflated",821 log_function: t.Optional[t.Callable[[str], None]] = None,35 unmodified lines857 with open(os.path.join(target, filename), "wb") as f:858 f.write(data.encode("utf8"))859 860 if zip is not None:861- from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED861+ from zipfile import ZIP_DEFLATED862+ from zipfile import ZIP_STORED863+ from zipfile import ZipFile864+ from zipfile import ZipInfo865 866 zip_file = ZipFile(867 target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]868 )550 unmodified lines1419 becomes unavailable in async mode.1420 """1421 ctx = self.new_context(vars, shared, locals)1422 return TemplateModule(1420- self, ctx, [x async for x in self.root_render_func(ctx)] # type: ignore1423+ self,1424+ ctx,1425+ [x async for x in self.root_render_func(ctx)], # type: ignore1426 )1427 1428 @internalcode1429 def _get_default_module(self, ctx: t.Optional[Context] = None) -> "TemplateModule":162 unmodified lines1592 self.disable_buffering()1593 1594 def dump(1595 self,1591- fp: t.Union[str, t.IO],1596+ fp: t.Union[str, t.IO[bytes]],1597 encoding: t.Optional[str] = None,1598 errors: t.Optional[str] = "strict",1599 ) -> None:1600 """Dump the complete stream into a file or file-like object.9 unmodified lines1610 if isinstance(fp, str):1611 if encoding is None:1612 encoding = "utf-8"1613 1609- fp = open(fp, "wb")1614+ real_fp: t.IO[bytes] = open(fp, "wb")1615 close = True1616+ else:1617+ real_fp = fp1618+1619 try:1620 if encoding is not None:1621 iterable = (x.encode(encoding, errors) for x in self) # type: ignore1622 else:1623 iterable = self # type: ignore1624 1617- if hasattr(fp, "writelines"):1618- fp.writelines(iterable)1625+ if hasattr(real_fp, "writelines"):1626+ real_fp.writelines(iterable)1627 else:1628 for item in iterable:1621- fp.write(item)1629+ real_fp.write(item)1630 finally:1631 if close:1624- fp.close()1632+ real_fp.close()1633 1634 def disable_buffering(self) -> None:1635 """Disable the output buffering."""1636 self._next = partial(next, self._gen)39 unmodified linesmodified:src/jinja2/ext.py+10 added-9 removed
1 """Extension API for adding custom tags and behavior."""2+3 import pprint4 import re5 import typing as t6 11 unmodified lines18 from .utils import pass_context19 20 if t.TYPE_CHECKING:21 import typing_extensions as te22+23 from .lexer import Token24 from .lexer import TokenStream25 from .parser import Parser26 27 class _TranslationsBasic(te.Protocol):26- def gettext(self, message: str) -> str:27- ...28+ def gettext(self, message: str) -> str: ...29 30 def ngettext(self, singular: str, plural: str, n: int) -> str:31 pass32 33 class _TranslationsContext(_TranslationsBasic):33- def pgettext(self, context: str, message: str) -> str:34- ...34+ def pgettext(self, context: str, message: str) -> str: ...35 36- 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: ...39 40 _SupportedTranslations = t.Union[_TranslationsBasic, _TranslationsContext]41 42 175 unmodified lines218 return pgettext219 220 221 def _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 lines294 # Python < 3.8295 pgettext = translations.pgettext296 else:297 297- def pgettext(c: str, s: str) -> str:298+ def pgettext(c: str, s: str) -> str: # type: ignore[misc]299 return s300 301 if hasattr(translations, "npgettext"):302 npgettext = translations.npgettext303 else:304 304- 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 p307 308 self._install_callables(309 gettext=translations.gettext,561 unmodified linesmodified:src/jinja2/filters.py+29 added-29 removed
1 """Built-in template filters used with the ``|`` operator."""2+3 import math4 import random5 import re6 import typing21 unmodified lines28 from .utils import urlize29 30 if t.TYPE_CHECKING:31 import typing_extensions as te32+33 from .environment import Environment34 from .nodes import EvalContext35 from .runtime import Context36 from .sandbox import SandboxedEnvironment # noqa: F40186 unmodified lines123 return attrgetter124 125 126 def _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 lines143 return escape(str(value))144 145 146 def 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.150 151 Basic wrapper around :func:`urllib.parse.quote` when given a401 unmodified lines553 554 @pass_eval_context555 def sync_do_join(556 eval_ctx: "EvalContext",555- value: t.Iterable,557+ value: t.Iterable[t.Any],558 d: str = "",559 attribute: t.Optional[t.Union[str, int]] = None,560 ) -> str:561 """Return a string which is the concatenation of the strings in the49 unmodified lines611 612 @async_variant(sync_do_join) # type: ignore613 async def do_join(614 eval_ctx: "EvalContext",613- value: t.Union[t.AsyncIterable, t.Iterable],615+ value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],616 d: str = "",617 attribute: t.Optional[t.Union[str, int]] = None,618 ) -> str:619 return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)541 unmodified lines1161 1162 1163 class _GroupTuple(t.NamedTuple):1164 grouper: t.Any1163- list: t.List1165+ list: t.List[t.Any]1166 1167 # Use the regular tuple repr to hide this subclass if users print1168 # out the value during debugging.1169 def __repr__(self) -> str:187 unmodified lines1357 return str(value)1358 1359 1360 @typing.overload1359-def do_reverse(value: str) -> str:1360- ...1361+def do_reverse(value: str) -> str: ...1362 1363 1364 @typing.overload1364-def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]":1365- ...1365+def do_reverse(value: "t.Iterable[V]") -> "t.Iterable[V]": ...1366 1367 1368 def 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 other45 unmodified lines1415 1416 1417 @typing.overload1418 def sync_do_map(1419- context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any1420-) -> t.Iterable:1421- ...1419+ context: "Context",1420+ value: t.Iterable[t.Any],1421+ name: str,1422+ *args: t.Any,1423+ **kwargs: t.Any,1424+) -> t.Iterable[t.Any]: ...1425 1426 1427 @typing.overload1428 def sync_do_map(1429 context: "Context",1427- value: t.Iterable,1430+ value: t.Iterable[t.Any],1431 *,1432 attribute: str = ...,1433 default: t.Optional[t.Any] = None,1431-) -> t.Iterable:1432- ...1434+) -> t.Iterable[t.Any]: ...1435 1436 1437 @pass_context1438 def sync_do_map(1437- context: "Context", value: t.Iterable, *args: t.Any, **kwargs: t.Any1438-) -> t.Iterable:1439+ context: "Context", value: t.Iterable[t.Any], *args: t.Any, **kwargs: t.Any1440+) -> t.Iterable[t.Any]:1441 """Applies a filter on a sequence of objects or looks up an attribute.1442 This is useful when dealing with lists of objects but you are really1443 only interested in a certain value of it.1444 41 unmodified lines1486 1487 @typing.overload1488 def do_map(1489 context: "Context",1488- value: t.Union[t.AsyncIterable, t.Iterable],1490+ value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],1491 name: str,1492 *args: t.Any,1493 **kwargs: t.Any,1492-) -> t.Iterable:1493- ...1494+) -> t.Iterable[t.Any]: ...1495 1496 1497 @typing.overload1498 def do_map(1499 context: "Context",1499- value: t.Union[t.AsyncIterable, t.Iterable],1500+ value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],1501 *,1502 attribute: str = ...,1503 default: t.Optional[t.Any] = None,1503-) -> t.Iterable:1504- ...1504+) -> t.Iterable[t.Any]: ...1505 1506 1507 @async_variant(sync_do_map) # type: ignore1508 async def do_map(1509 context: "Context",1510- value: t.Union[t.AsyncIterable, t.Iterable],1510+ value: t.Union[t.AsyncIterable[t.Any], t.Iterable[t.Any]],1511 *args: t.Any,1512 **kwargs: t.Any,1513-) -> t.AsyncIterable:1513+) -> t.AsyncIterable[t.Any]:1514 if value:1515 func = prepare_map(context, args, kwargs)1516 1517 async for item in auto_aiter(value):184 unmodified lines1702 return htmlsafe_json_dumps(value, dumps=dumps, **kwargs)1703 1704 1705 def prepare_map(1706- context: "Context", args: t.Tuple, kwargs: t.Dict[str, t.Any]1706+ context: "Context", args: t.Tuple[t.Any, ...], kwargs: t.Dict[str, t.Any]1707 ) -> t.Callable[[t.Any], t.Any]:1708 if not args and "attribute" in kwargs:1709 attribute = kwargs.pop("attribute")1710 default = kwargs.pop("default", None)20 unmodified lines1731 1732 1733 def prepare_select_or_reject(1734 context: "Context",1735- args: t.Tuple,1735+ args: t.Tuple[t.Any, ...],1736 kwargs: t.Dict[str, t.Any],1737 modfunc: t.Callable[[t.Any], t.Any],1738 lookup_attr: bool,1739 ) -> t.Callable[[t.Any], t.Any]:26 unmodified lines1766 1767 def select_or_reject(1768 context: "Context",1769 value: "t.Iterable[V]",1770- args: t.Tuple,1770+ args: t.Tuple[t.Any, ...],1771 kwargs: t.Dict[str, t.Any],1772 modfunc: t.Callable[[t.Any], t.Any],1773 lookup_attr: bool,1774 ) -> "t.Iterator[V]":7 unmodified lines1782 1783 async def async_select_or_reject(1784 context: "Context",1785 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1786- args: t.Tuple,1786+ args: t.Tuple[t.Any, ...],1787 kwargs: t.Dict[str, t.Any],1788 modfunc: t.Callable[[t.Any], t.Any],1789 lookup_attr: bool,1790 ) -> "t.AsyncIterator[V]":64 unmodified linesmodified:src/jinja2/lexer.py+3 added-1 removed
1 unmodified line2 is used to do some preprocessing. It filters out invalid operators like3 the bitshift operators we don't allow in templates. It separates4 template code and python code in expressions.5 """6+7 import re8 import typing as t9 from ast import literal_eval10 from collections import deque4 unmodified lines15 from .utils import LRUCache16 17 if t.TYPE_CHECKING:18 import typing_extensions as te19+20 from .environment import Environment21 22 # cache for the lexers. Exists in order to be able to have multiple23 # environments with the same lexer424 unmodified lines448 449 return lexer450 451 450-class OptionalLStrip(tuple):452+class OptionalLStrip(tuple): # type: ignore[type-arg]453 """A special tuple for marking a point in the state that can have454 lstrip applied.455 """456 412 unmodified linesmodified:src/jinja2/loaders.py+8 added-2 removed
1 """API and implementations for loading templates from different data2 sources.3 """4+5 import importlib.util6 import os7 import posixpath8 import sys168 unmodified lines177 """178 179 def __init__(180 self,180- searchpath: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]],181+ searchpath: t.Union[182+ str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]183+ ],184 encoding: str = "utf-8",185 followlinks: bool = False,186 ) -> None:187 if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):415 unmodified lines603 604 has_source_access = False605 606 def __init__(604- self, path: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]]607+ self,608+ path: t.Union[609+ str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]610+ ],611 ) -> None:612 package_name = f"_jinja2_module_templates_{id(self):x}"613 614 # create a fake module that looks for the templates in the53 unmodified linesmodified:src/jinja2/meta.py+1 added
1 """Functions that expose information about templates that might be2 interesting for introspection.3 """4+5 import typing as t6 7 from . import nodes8 from .compiler import CodeGenerator104 unmodified linesmodified:src/jinja2/nodes.py+3 added-1 removed
1 """AST nodes generated by the parser for the compiler. Also provides2 some node tree helper functions used by the parser and compiler in order3 to normalize nodes.4 """5+6 import inspect7 import operator8 import typing as t9 from collections import deque3 unmodified lines13 from .utils import _PassArg14 15 if t.TYPE_CHECKING:16 import typing_extensions as te17+18 from .environment import Environment19 20 _NodeBound = t.TypeVar("_NodeBound", bound="Node")21 35 unmodified lines57 automatically forwarded to the child."""58 59 def __new__(mcs, name, bases, d): # type: ignore60 for attr in "fields", "attributes":59- storage = []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 linesmodified:src/jinja2/optimizer.py+1 added
5 unmodified lines6 want. For example, loop unrolling doesn't work because unrolled loops7 would have a different scope. The solution would be a second syntax tree8 that stored the scoping rules.9 """10+11 import typing as t12 13 from . import nodes14 from .visitor import NodeTransformer34 unmodified linesmodified:src/jinja2/parser.py+13 added-6 removed
1 """Parse tokens from the lexer into nodes for the compiler."""2+3 import typing4 import typing as t5 6 from . import nodes3 unmodified lines10 from .lexer import describe_token_expr11 12 if t.TYPE_CHECKING:13 import typing_extensions as te14+15 from .environment import Environment16 17 _ImportInclude = t.TypeVar("_ImportInclude", nodes.Import, nodes.Include)18 _MacroCall = t.TypeVar("_MacroCall", nodes.Macro, nodes.CallBlock)439 unmodified lines458 459 @typing.overload460 def parse_assign_target(461 self, with_tuple: bool = ..., name_only: "te.Literal[True]" = ...460- ) -> nodes.Name:461- ...462+ ) -> nodes.Name: ...463 464 @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]: ...472 473 def parse_assign_target(474 self,475 with_tuple: bool = True,384 unmodified lines860 args.append(None)861 862 return nodes.Slice(lineno=lineno, *args) # noqa: B026863 864- def parse_call_args(self) -> t.Tuple:864+ def parse_call_args(865+ self,866+ ) -> t.Tuple[867+ t.List[nodes.Expr],868+ t.List[nodes.Keyword],869+ t.Optional[nodes.Expr],870+ t.Optional[nodes.Expr],871+ ]:872 token = self.stream.expect("lparen")873 args = []874 kwargs = []875 dyn_args = None82 unmodified lines958 while self.stream.current.type == "dot":959 next(self.stream)960 name += "." + self.stream.expect("name").value961 dyn_args = dyn_kwargs = None955- kwargs = []962+ kwargs: t.List[nodes.Keyword] = []963 if self.stream.current.type == "lparen":964 args, kwargs, dyn_args, dyn_kwargs = self.parse_call_args()965 elif self.stream.current.type in {966 "name",75 unmodified linesmodified:src/jinja2/runtime.py+9 added-4 removed
1 """The runtime functions and state used by compiled templates."""2+3 import functools4 import sys5 import typing as t6 from collections import abc21 unmodified lines28 F = t.TypeVar("F", bound=t.Callable[..., t.Any])29 30 if t.TYPE_CHECKING:31 import logging32+33 import typing_extensions as te34+35 from .environment import Environment36 37 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: ...44 45 46 # these variables are exported to the template runtime47 exported = [212 unmodified lines260 return dict(self.parent, **self.vars)261 262 @internalcode263 def call(262- __self, __obj: t.Callable, *args: t.Any, **kwargs: t.Any # noqa: B902264+ __self,265+ __obj: t.Callable[..., t.Any],266+ *args: t.Any,267+ **kwargs: t.Any, # noqa: B902268 ) -> t.Union[t.Any, "Undefined"]:269 """Call the callable with the arguments and keyword arguments270 provided but inject the active context or environment as first271 argument if the callable has :func:`pass_context` or318 unmodified lines590 _iterator: t.AsyncIterator[t.Any] # type: ignore591 592 @staticmethod593 def _to_iterator( # type: ignore589- 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)597 598 @property458 unmodified linesmodified:src/jinja2/sandbox.py+5 added-4 removed
1 """A sandbox layer that ensures unsafe operations cannot be performed.2 Useful when the template itself comes from an untrusted source.3 """4+5 import operator6 import types7 import typing as t7-from _string import formatter_field_name_split # type: ignore8 from collections import abc9 from collections import deque10 from string import Formatter11 12+from _string import formatter_field_name_split # type: ignore13 from markupsafe import EscapeFormatter14 from markupsafe import Markup15 16 from .environment import Environment20 unmodified lines37 38 #: unsafe attributes on async generators39 UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}40 40-_mutable_spec: t.Tuple[t.Tuple[t.Type, t.FrozenSet[str]], ...] = (41+_mutable_spec: t.Tuple[t.Tuple[t.Type[t.Any], t.FrozenSet[str]], ...] = (42 (43 abc.MutableSet,44 frozenset(45 [34 unmodified lines80 ),81 )82 83 83-def inspect_format_method(callable: t.Callable) -> t.Optional[str]:84+def inspect_format_method(callable: t.Callable[..., t.Any]) -> t.Optional[str]:85 if not isinstance(86 callable, (types.MethodType, types.BuiltinMethodType)87 ) or callable.__name__ not in ("format", "format_map"):88 return None261 unmodified lines350 self,351 s: str,352 args: t.Tuple[t.Any, ...],353 kwargs: t.Dict[str, t.Any],353- format_func: t.Optional[t.Callable] = None,354+ format_func: t.Optional[t.Callable[..., t.Any]] = None,355 ) -> str:356 """If a format call is detected, then this is routed through this357 method so that our safety sandbox can be used for it.358 """71 unmodified linesmodified:src/jinja2/tests.py+3 added-2 removed
1 """Built-in template tests used with the ``is`` operator."""2+3 import operator4 import typing as t5 from collections import abc6 from numbers import Number162 unmodified lines169 that are iterable.170 """171 try:172 len(value)172- value.__getitem__173+ value.__getitem__ # noqa B018174 except Exception:175 return False176 177 return True26 unmodified lines204 """Check if the value is escaped."""205 return hasattr(value, "__html__")206 207 207-def test_in(value: t.Any, seq: t.Container) -> bool:208+def test_in(value: t.Any, seq: t.Container[t.Any]) -> bool:209 """Check if value is in seq.210 211 .. versionadded:: 2.10212 """44 unmodified linesmodified:src/jinja2/utils.py+2 added-2 removed
150 unmodified lines151 if not silent:152 raise153 154 155-def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO]:155+def open_if_exists(filename: str, mode: str = "rb") -> t.Optional[t.IO[t.Any]]:156 """Returns a file descriptor for the filename if that file exists,157 otherwise ``None``.158 """159 if not os.path.isfile(filename):289 unmodified lines449 def __setstate__(self, d: t.Mapping[str, t.Any]) -> None:450 self.__dict__.update(d)451 self._postinit()452 453- def __getnewargs__(self) -> t.Tuple:453+ def __getnewargs__(self) -> t.Tuple[t.Any, ...]:454 return (self.capacity,)455 456 def copy(self) -> "LRUCache":457 """Return a shallow copy of the instance."""298 unmodified linesmodified:src/jinja2/visitor.py+2 added-2 removed
1 """API for traversing the AST nodes. Implemented by the compiler and2 meta introspection.3 """4+5 import typing as t6 7 from .nodes import Node8 9 if t.TYPE_CHECKING:10 import typing_extensions as te11 12 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: ...14 15 16 class NodeVisitor:17 """Walks the abstract syntax tree and call visitor functions for every75 unmodified linesmodified:tests/test_api.py+3 added-2 removed
148 unmodified lines149 t = env.from_string("{{ foo }}")150 assert t.render(foo="<foo>") == "<foo>"151 152 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 SandboxedEnvironment155 156 env = SandboxedEnvironment()157 t = env.from_string("{% for item in range(total) %}{{ item }}{% endfor %}")158 105 unmodified lines264 pytest.raises(UndefinedError, t.render, test=test)265 266 def test_undefined_and_special_attributes(self):267 with pytest.raises(AttributeError):267- Undefined("Foo").__dict__268+ Undefined("Foo").__dict__ # noqa B018269 270 def test_undefined_attribute_error(self):271 # Django's LazyObject turns the __class__ attribute into a272 # property that resolves the wrapped function. If that wrapped163 unmodified linesmodified:tests/test_inheritance.py+8 added-14 removed
363 unmodified lines364 365 366 class 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' %}373 374 {% macro my_macro() %}375 my_macro2 unmodified lines378 {% block inner_box %}379 {{ my_macro() }}380 {% endblock %}381 """,383- "details.html": """\382+ "details.html": """\383 {% extends 'standard.html' %}384 385 {% macro my_macro() %}386 my_macro7 unmodified lines394 {% endblock %}395 {% endblock %}396 {% endblock %}397 """,399- "standard.html": """398+ "standard.html": """399 {% block content %} {% 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"]404 405 def test_double_extends(self, env):406 """Ensures that a template with more than 1 {% extends ... %} usage407 raises a ``TemplateError``.3 unmodified linesmodified:tests/test_regression.py+1 added
597 unmodified lines598 assert tmpl.render(values=[]) == "0"599 600 def test_markup_and_chainable_undefined(self):601 from markupsafe import Markup602+603 from jinja2.runtime import ChainableUndefined604 605 assert str(Markup(ChainableUndefined())) == ""606 139 unmodified linesmodified:.editorconfig+1 added-1 removed
7 unmodified lines8 end_of_line = lf9 charset = utf-810 max_line_length = 8811 12-[*.{yml,yaml,json,js,css,html}]12+[*.{css,html,js,json,jsx,scss,ts,tsx,yaml,yml}]13 indent_size = 2deleted:.flake8-28 removed
1-[flake8]2-extend-select =3- # bugbear4- B5- # bugbear opinions6- B97- # implicit str concat8- ISC9-extend-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 B95022-max-line-length = 8023-per-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: B906modified:.gitignore+8 added-19 removed
1-*.so2-docs/_build/3-*.pyc4-*.pyo5-*.egg-info/6-*.egg7-build/1+.idea/2+.vscode/3+.venv*/4+venv*/5+__pycache__/6 dist/9-.DS_Store7+.coverage*8+htmlcov/9 .tox/11-.cache/12-.idea/13-env/14-venv/15-venv-*/16-.coverage17-.coverage.*18-htmlcov19-.pytest_cache/20-/.vscode/21-.mypy_cache10+docs/_build/modified:.pre-commit-config.yaml+7 added-24 removed
1 ci:2- autoupdate_branch: "3.1.x"2 autoupdate_schedule: monthly3 repos: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-fixermodified:.readthedocs.yaml+2 added-2 removed
1 version: 22 build:3- os: ubuntu-20.043+ os: ubuntu-22.044 tools:5- python: "3.10"5+ python: '3.12'6 python:7 install:8 - requirements: requirements/docs.txt9 - method: pip4 unmodified linesdeleted:CODE_OF_CONDUCT.md-76 removed
1-# Contributor Covenant Code of Conduct2-3-## Our Pledge4-5-In the interest of fostering an open and welcoming environment, we as6-contributors and maintainers pledge to making participation in our project and7-our community a harassment-free experience for everyone, regardless of age, body8-size, disability, ethnicity, sex characteristics, gender identity and expression,9-level of experience, education, socio-economic status, nationality, personal10-appearance, race, religion, or sexual identity and orientation.11-12-## Our Standards13-14-Examples of behavior that contributes to creating a positive environment15-include:16-17-* 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 members22-23-Examples of unacceptable behavior by participants include:24-25-* 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 setting33-34-## Our Responsibilities35-36-Project maintainers are responsible for clarifying the standards of acceptable37-behavior and are expected to take appropriate and fair corrective action in38-response to any instances of unacceptable behavior.39-40-Project maintainers have the right and responsibility to remove, edit, or41-reject comments, commits, code, wiki edits, issues, and other contributions42-that are not aligned to this Code of Conduct, or to ban temporarily or43-permanently any contributor for other behaviors that they deem inappropriate,44-threatening, offensive, or harmful.45-46-## Scope47-48-This Code of Conduct applies both within project spaces and in public spaces49-when an individual is representing the project or its community. Examples of50-representing a project or community include using an official project e-mail51-address, posting via an official social media account, or acting as an appointed52-representative at an online or offline event. Representation of a project may be53-further defined and clarified by project maintainers.54-55-## Enforcement56-57-Instances of abusive, harassing, or otherwise unacceptable behavior may be58-reported by contacting the project team at report@palletsprojects.com. All59-complaints will be reviewed and investigated and will result in a response that60-is deemed necessary and appropriate to the circumstances. The project team is61-obligated to maintain confidentiality with regard to the reporter of an incident.62-Further details of specific enforcement policies may be posted separately.63-64-Project maintainers who do not follow or enforce the Code of Conduct in good65-faith may face temporary or permanent repercussions as determined by other66-members of the project's leadership.67-68-## Attribution69-70-This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,71-available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html72-73-[homepage]: https://www.contributor-covenant.org74-75-For answers to common questions about this code of conduct, see76-https://www.contributor-covenant.org/faqdeleted:LICENSE.rst-28 removed
1-Copyright 2007 Pallets2-3-Redistribution and use in source and binary forms, with or without4-modification, are permitted provided that the following conditions are5-met:6-7-1. Redistributions of source code must retain the above copyright8- notice, this list of conditions and the following disclaimer.9-10-2. 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.13-14-3. 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.17-18-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19-"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20-LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21-PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22-HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23-SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24-TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25-PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26-LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27-NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.added:LICENSE.txt+28 added
1+Copyright 2007 Pallets2+3+Redistribution and use in source and binary forms, with or without4+modification, are permitted provided that the following conditions are5+met:6+7+1. Redistributions of source code must retain the above copyright8+ notice, this list of conditions and the following disclaimer.9+10+2. 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.13+14+3. 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.17+18+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20+LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21+PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22+HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24+TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25+PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26+LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27+NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.deleted:MANIFEST.in-10 removed
1-include CHANGES.rst2-include tox.ini3-include requirements/*.txt4-graft artwork5-graft docs6-prune docs/_build7-graft examples8-graft tests9-include src/jinja2/py.typed10-global-exclude *.pycadded:pyproject.toml+98 added
1+[project]2+name = "Jinja2"3+description = "A very fast and expressive template engine."4+readme = "README.md"5+license = {file = "LICENSE.txt"}6+maintainers = [{name = "Pallets", email = "contact@palletsprojects.com"}]7+classifiers = [8+ "Development Status :: 5 - Production/Stable",9+ "Environment :: Web Environment",10+ "Intended Audience :: Developers",11+ "License :: OSI Approved :: BSD License",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+]18+requires-python = ">=3.7"19+dependencies = ["MarkupSafe>=2.0"]20+dynamic = ["version"]21+22+[project.urls]23+Donate = "https://palletsprojects.com/donate"24+Documentation = "https://jinja.palletsprojects.com/"25+Changes = "https://jinja.palletsprojects.com/changes/"26+Source = "https://github.com/pallets/jinja/"27+Chat = "https://discord.gg/pallets"28+29+[project.optional-dependencies]30+i18n = ["Babel>=2.7"]31+32+[project.entry-points."babel.extractors"]33+jinja2 = "jinja2.ext:babel_extract[i18n]"34+35+[build-system]36+requires = ["flit_core<4"]37+build-backend = "flit_core.buildapi"38+39+[tool.flit.module]40+name = "jinja2"41+42+[tool.flit.sdist]43+include = [44+ "docs/",45+ "requirements/",46+ "tests/",47+ "CHANGES.md",48+ "tox.ini",49+]50+exclude = [51+ "docs/_build/",52+]53+54+[tool.pytest.ini_options]55+testpaths = ["tests"]56+filterwarnings = [57+ "error",58+]59+60+[tool.coverage.run]61+branch = true62+source = ["jinja2", "tests"]63+64+[tool.coverage.paths]65+source = ["src", "*/site-packages"]66+67+[tool.mypy]68+python_version = "3.8"69+files = ["src/jinja2"]70+show_error_codes = true71+pretty = true72+strict = true73+74+[tool.pyright]75+pythonVersion = "3.8"76+include = ["src/jinja2"]77+typeCheckingMode = "basic"78+79+[tool.ruff]80+src = ["src"]81+fix = true82+show-fixes = true83+output-format = "full"84+85+[tool.ruff.lint]86+select = [87+ "B", # flake8-bugbear88+ "E", # pycodestyle error89+ "F", # pyflakes90+ "I", # isort91+ "UP", # pyupgrade92+ "W", # pycodestyle warning93+]94+ignore-init-module-imports = true95+96+[tool.ruff.lint.isort]97+force-single-line = true98+order-by-type = falseadded:README.md+50 added
1+# Jinja2+3+Jinja is a fast, expressive, extensible templating engine. Special4+placeholders in the template allow writing code similar to Python5+syntax. Then the template is passed data to render the final document.6+7+It includes:8+9+- 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.22+23+Jinja's philosophy is that while application logic belongs in Python if24+possible, it shouldn't make the template designer's job difficult by25+restricting functionality too much.26+27+28+## In A Nutshell29+30+.. code-block:: jinja31+32+ {% 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 %}41+42+43+## Donate44+45+The Pallets organization develops and supports Jinja and other popular46+packages. In order to grow the community of contributors and users, and47+allow the maintainers to devote more time to the projects, [please48+donate today][].49+50+[please donate today]: https://palletsprojects.com/donatedeleted:README.rst-76 removed
1-Jinja2-=====3-4-Jinja is a fast, expressive, extensible templating engine. Special5-placeholders in the template allow writing code similar to Python6-syntax. Then the template is passed data to render the final document.7-8-It includes:9-10-- 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.23-24-Jinja's philosophy is that while application logic belongs in Python if25-possible, it shouldn't make the template designer's job difficult by26-restricting functionality too much.27-28-29-Installing30-----------31-32-Install and update using `pip`_:33-34-.. code-block:: text35-36- $ pip install -U Jinja237-38-.. _pip: https://pip.pypa.io/en/stable/getting-started/39-40-41-In A Nutshell42--------------43-44-.. code-block:: jinja45-46- {% 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 %}55-56-57-Donate58-------59-60-The Pallets organization develops and supports Jinja and other popular61-packages. In order to grow the community of contributors and users, and62-allow the maintainers to devote more time to the projects, `please63-donate today`_.64-65-.. _please donate today: https://palletsprojects.com/donate66-67-68-Links69------70-71-- 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/palletsdeleted:setup.cfg-81 removed
1-[metadata]2-name = Jinja23-version = attr: jinja2.__version__4-url = https://palletsprojects.com/p/jinja/5-project_urls =6- Donate = https://palletsprojects.com/donate7- Documentation = https://jinja.palletsprojects.com/8- Changes = https://jinja.palletsprojects.com/changes/9- Source Code = https://github.com/pallets/jinja/10- Issue Tracker = https://github.com/pallets/jinja/issues/11- Chat = https://discord.gg/pallets12-license = BSD-3-Clause13-license_files = LICENSE.rst14-maintainer = Pallets15-maintainer_email = contact@palletsprojects.com16-description = A very fast and expressive template engine.17-long_description = file: README.rst18-long_description_content_type = text/x-rst19-classifiers =20- Development Status :: 5 - Production/Stable21- Environment :: Web Environment22- Intended Audience :: Developers23- License :: OSI Approved :: BSD License24- Operating System :: OS Independent25- Programming Language :: Python26- Topic :: Internet :: WWW/HTTP :: Dynamic Content27- Topic :: Text Processing :: Markup :: HTML28-29-[options]30-packages = find:31-package_dir = = src32-include_package_data = True33-python_requires = >= 3.734-# Dependencies are in setup.py for GitHub's dependency graph.35-36-[options.packages.find]37-where = src38-39-[options.entry_points]40-babel.extractors =41- jinja2 = jinja2.ext:babel_extract[i18n]42-43-[tool:pytest]44-testpaths = tests45-filterwarnings =46- error47-48-[coverage:run]49-branch = True50-source =51- jinja252- tests53-54-[coverage:paths]55-source =56- src57- */site-packages58-59-[mypy]60-files = src/jinja261-python_version = 3.762-show_error_codes = True63-disallow_subclassing_any = True64-disallow_untyped_calls = True65-disallow_untyped_defs = True66-disallow_incomplete_defs = True67-no_implicit_optional = True68-local_partial_types = True69-no_implicit_reexport = True70-strict_equality = True71-warn_redundant_casts = True72-warn_unused_configs = True73-warn_unused_ignores = True74-warn_return_any = True75-warn_unreachable = True76-77-[mypy-jinja2.defaults]78-no_implicit_reexport = False79-80-[mypy-markupsafe]81-no_implicit_reexport = Falsedeleted:setup.py-8 removed
1-from setuptools import setup2-3-# Metadata goes in setup.cfg. These are here for GitHub's dependency graph.4-setup(5- name="Jinja2",6- install_requires=["MarkupSafe>=2.0"],7- extras_require={"i18n": ["Babel>=2.7"]},8-)modified:tox.ini+17 added-1 removed
8 unmodified lines9 10 [testenv]11 package = wheel12 wheel_build_env = .pkg13+constrain_package_deps = true14+use_frozen_constraints = true15 deps = -r requirements/tests.txt16 commands = pytest -v --tb=short --basetemp={envtmpdir} {posargs}17 18 [testenv:style]6 unmodified lines25 commands = mypy26 27 [testenv:docs]28 deps = -r requirements/docs.txt27-commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html29+commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml30+31+[testenv:update-requirements]32+deps =33+ pip-tools34+ pre-commit35+skip_install = true36+change_dir = requirements37+commands =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