Debian Codegraph @

ansible_collections/community/general/plugins/plugin_utils/_unsafe.py

raw
1 # Copyright (c) 2023, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this plugin util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import re
11 import typing as t
12 from collections.abc import Mapping, Sequence, Set
13
14 from ansible.module_utils.common.collections import is_sequence
15 from ansible.utils.unsafe_proxy import (
16 AnsibleUnsafe,
17 )
18 from ansible.utils.unsafe_proxy import (
19 wrap_var as _make_unsafe,
20 )
21
22 _RE_TEMPLATE_CHARS = re.compile("[{}]")
23 _RE_TEMPLATE_CHARS_BYTES = re.compile(b"[{}]")
24
25
26 @t.overload
27 def make_unsafe(value: None) -> None: ...
28
29
30 @t.overload
31 def make_unsafe(value: Mapping) -> dict: ...
32
33
34 @t.overload
35 def make_unsafe(value: Set) -> set: ...
36
37
38 @t.overload
39 def make_unsafe(value: tuple) -> tuple: ...
40
41
42 @t.overload
43 def make_unsafe(value: list) -> list: ...
44
45
46 @t.overload
47 def make_unsafe(value: Sequence) -> Sequence: ...
48
49
50 @t.overload
51 def make_unsafe(value: str) -> str: ...
52
53
54 @t.overload
55 def make_unsafe(value: bool) -> bool: ...
56
57
58 @t.overload
59 def make_unsafe(value: int) -> int: ...
60
61
62 @t.overload
63 def make_unsafe(value: float) -> float: ...
64
65
66 def make_unsafe(value: t.Any) -> t.Any:
67 if value is None or isinstance(value, AnsibleUnsafe):
68 return value
69
70 if isinstance(value, Mapping):
71 return {make_unsafe(key): make_unsafe(val) for key, val in value.items()}
72 elif isinstance(value, Set):
73 return {make_unsafe(elt) for elt in value}
74 elif is_sequence(value):
75 return type(value)(make_unsafe(elt) for elt in value)
76 elif isinstance(value, bytes):
77 if _RE_TEMPLATE_CHARS_BYTES.search(value):
78 value = _make_unsafe(value)
79 return value
80 elif isinstance(value, str):
81 if _RE_TEMPLATE_CHARS.search(value):
82 value = _make_unsafe(value)
83 return value
84
85 return value