Debian Codegraph @

lib/ansible/_internal/_templating/_jinja_patches.py

raw
1 """Runtime patches for Jinja bugs affecting Ansible."""
2
3 from __future__ import annotations
4
5 import jinja2
6 import jinja2.utils
7
8
9 def _patch_jinja_undefined_slots() -> None:
10 """
11 Fix the broken __slots__ on Jinja's Undefined and StrictUndefined if they're missing in the current version.
12 This will no longer be necessary once the fix is included in the minimum supported Jinja version.
13 See: https://github.com/pallets/jinja/issues/2025
14 """
15 if not hasattr(jinja2.Undefined, '__slots__'):
16 jinja2.Undefined.__slots__ = (
17 "_undefined_hint",
18 "_undefined_obj",
19 "_undefined_name",
20 "_undefined_exception",
21 )
22
23 if not hasattr(jinja2.StrictUndefined, '__slots__'):
24 jinja2.StrictUndefined.__slots__ = ()
25
26
27 def _patch_jinja_missing_type() -> None:
28 """
29 Fix the `jinja2.utils.missing` type to support pickling while remaining a singleton.
30 This will no longer be necessary once the fix is included in the minimum supported Jinja version.
31 See: https://github.com/pallets/jinja/issues/2027
32 """
33 if getattr(jinja2.utils.missing, '__reduce__')() != 'missing':
34
35 def __reduce__(*_args):
36 return 'missing'
37
38 type(jinja2.utils.missing).__reduce__ = __reduce__
39
40
41 def _patch_jinja() -> None:
42 """Apply Jinja2 patches."""
43 _patch_jinja_undefined_slots()
44 _patch_jinja_missing_type()