Debian Codegraph @

lib/ansible/_internal/_json/_legacy_encoder.py

raw
1 from __future__ import annotations as _annotations
2
3 import typing as _t
4
5 from ansible.module_utils._internal._json import _profiles
6 from ansible._internal._json._profiles import _legacy
7 from ansible.parsing import vault as _vault
8
9
10 class LegacyControllerJSONEncoder(_legacy.Encoder):
11 """Compatibility wrapper over `legacy` profile JSON encoder to support trust stripping and vault value plaintext conversion."""
12
13 def __init__(self, preprocess_unsafe: bool = False, vault_to_text: bool = False, _decode_bytes: bool = False, **kwargs) -> None:
14 self._preprocess_unsafe = preprocess_unsafe
15 self._vault_to_text = vault_to_text
16 self._decode_bytes = _decode_bytes
17
18 super().__init__(**kwargs)
19
20 def default(self, o: _t.Any) -> _t.Any:
21 """Hooked default that can conditionally bypass base encoder behavior based on this instance's config."""
22 if type(o) is _profiles._WrappedValue: # pylint: disable=unidiomatic-typecheck
23 o = o.wrapped
24
25 if not self._preprocess_unsafe and type(o) is _legacy._Untrusted: # pylint: disable=unidiomatic-typecheck
26 return o.value # if not emitting unsafe markers, bypass custom unsafe serialization and just return the raw value
27
28 if self._vault_to_text and type(o) is _vault.EncryptedString: # pylint: disable=unidiomatic-typecheck
29 return str(o) # decrypt and return the plaintext (or fail trying)
30
31 if self._decode_bytes and isinstance(o, bytes):
32 return o.decode(errors='surrogateescape') # backward compatibility with `ansible.module_utils.basic.jsonify`
33
34 return super().default(o)