Debian Codegraph @

lib/ansible/_internal/_yaml/_loader.py

raw
1 from __future__ import annotations
2
3 import io as _io
4
5 from yaml.resolver import Resolver
6
7 from ansible.module_utils._internal._datatag import AnsibleTagHelper
8 from ansible.module_utils.common.yaml import HAS_LIBYAML
9 from ansible._internal._datatag import _tags
10
11 from ._constructor import AnsibleConstructor, AnsibleInstrumentedConstructor
12
13 if HAS_LIBYAML:
14 from yaml.cyaml import CParser
15
16 class _Parser(CParser):
17 def __init__(self, stream: str | bytes | _io.IOBase) -> None:
18 if isinstance(stream, (str, bytes)):
19 stream = AnsibleTagHelper.untag(stream) # PyYAML + libyaml barfs on str/bytes subclasses
20
21 CParser.__init__(self, stream)
22
23 else:
24 from yaml.composer import Composer
25 from yaml.reader import Reader
26 from yaml.scanner import Scanner
27 from yaml.parser import Parser
28
29 class _Parser(Reader, Scanner, Parser, Composer): # type: ignore[no-redef]
30 def __init__(self, stream: str | bytes | _io.IOBase) -> None:
31 Reader.__init__(self, stream)
32 Scanner.__init__(self)
33 Parser.__init__(self)
34 Composer.__init__(self)
35
36
37 class _YamlParser(_Parser):
38 def __init__(self, stream: str | bytes | _io.IOBase) -> None:
39 super().__init__(stream)
40
41 # The Python implementation of PyYAML (yaml.reader.Reader) provides self.name.
42 # However, it will fall back to "<...>" in various cases.
43 # The C implementation of PyYAML does not provide self.name.
44 # To provide consistency, name retrieval is re-implemented here.
45 self.name = getattr(stream, 'name', None)
46
47
48 class AnsibleInstrumentedLoader(_YamlParser, AnsibleInstrumentedConstructor, Resolver):
49 """Ansible YAML loader which supports Ansible custom behavior such as `Origin` tagging, but no Ansible-specific YAML tags."""
50
51 def __init__(self, stream: str | bytes | _io.IOBase) -> None:
52 _YamlParser.__init__(self, stream)
53
54 AnsibleInstrumentedConstructor.__init__(
55 self,
56 origin=_tags.Origin.get_or_create_tag(stream, self.name),
57 trusted_as_template=_tags.TrustedAsTemplate.is_tagged_on(stream),
58 )
59
60 Resolver.__init__(self)
61
62
63 class AnsibleLoader(_YamlParser, AnsibleConstructor, Resolver):
64 """Ansible loader which supports Ansible custom behavior such as `Origin` tagging, as well as Ansible-specific YAML tags."""
65
66 def __init__(self, stream: str | bytes | _io.IOBase) -> None:
67 _YamlParser.__init__(self, stream)
68
69 AnsibleConstructor.__init__(
70 self,
71 origin=_tags.Origin.get_or_create_tag(stream, self.name),
72 trusted_as_template=_tags.TrustedAsTemplate.is_tagged_on(stream),
73 sensitive_source_data=_tags.SourceWasEncrypted.is_tagged_on(stream),
74 )
75
76 Resolver.__init__(self)