Debian Codegraph @

lib/ansible/utils/collection_loader/__init__.py

raw
1 # (c) 2019 Ansible Project
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 # CAUTION: This implementation of the collection loader is used by ansible-test.
5 # Because of this, it must be compatible with all Python versions supported on the controller or remote.
6
7 from __future__ import annotations
8
9 import typing as t
10
11
12 @t.runtime_checkable
13 class _EncryptedStringProtocol(t.Protocol):
14 """Protocol representing an `EncryptedString`, since it cannot be imported here."""
15
16 # DTFIX-FUTURE: collapse this with the one in config, once we can
17
18 def _decrypt(self) -> str: ...
19
20
21 def _to_text(value: str | bytes | _EncryptedStringProtocol | None, strict: bool = False) -> str | None:
22 """Internal implementation to keep collection loader standalone."""
23 # FUTURE: remove this method when _to_bytes is removed
24
25 if value is None:
26 return None
27
28 if isinstance(value, str):
29 return value
30
31 if isinstance(value, bytes):
32 return value.decode(errors='strict' if strict else 'surrogateescape')
33
34 if isinstance(value, _EncryptedStringProtocol):
35 return value._decrypt()
36
37 raise TypeError(f'unsupported type {type(value)}')
38
39
40 def _to_bytes(value: str | bytes | _EncryptedStringProtocol | None, strict: bool = False) -> bytes | None:
41 """Internal implementation to keep collection loader standalone."""
42 # FUTURE: remove this method and rely on automatic str -> bytes conversions of filesystem methods instead
43
44 if value is None:
45 return None
46
47 if isinstance(value, bytes):
48 return value
49
50 if isinstance(value, str):
51 return value.encode(errors='strict' if strict else 'surrogateescape')
52
53 if isinstance(value, _EncryptedStringProtocol):
54 return value._decrypt().encode(errors='strict' if strict else 'surrogateescape')
55
56 raise TypeError(f'unsupported type {type(value)}')
57
58
59 def resource_from_fqcr(ref):
60 """
61 Return resource from a fully-qualified collection reference,
62 or from a simple resource name.
63 For fully-qualified collection references, this is equivalent to
64 ``AnsibleCollectionRef.from_fqcr(ref).resource``.
65 :param ref: collection reference to parse
66 :return: the resource as a unicode string
67 """
68 ref = _to_text(ref, strict=True)
69 return ref.split(u'.')[-1]
70
71
72 # FIXME: decide what of this we want to actually be public/toplevel, put other stuff on a utility class?
73 from ._collection_config import AnsibleCollectionConfig
74 from ._collection_finder import AnsibleCollectionRef