Debian Codegraph @

lib/ansible/_internal/_yaml/_errors.py

raw
1 from __future__ import annotations
2
3 import re
4
5 import typing as t
6
7 from yaml import MarkedYAMLError
8 from yaml.constructor import ConstructorError
9
10 from ansible._internal._errors import _error_utils
11 from ansible.errors import AnsibleParserError
12 from ansible._internal._datatag._tags import Origin
13
14
15 class AnsibleConstructorError(ConstructorError):
16 """Ansible-specific ConstructorError used to bypass exception analysis during wrapping in AnsibleYAMLParserError."""
17
18
19 class AnsibleYAMLParserError(AnsibleParserError):
20 """YAML-specific parsing failure wrapping an exception raised by the YAML parser."""
21
22 _default_message = 'YAML parsing failed.'
23
24 _include_cause_message = False # hide the underlying cause message, it's included by `handle_exception` as needed
25
26 _formatted_source_context_value: str | None = None
27
28 @property
29 def _formatted_source_context(self) -> str | None:
30 return self._formatted_source_context_value
31
32 @classmethod
33 def handle_exception(cls, exception: Exception, origin: Origin) -> t.NoReturn:
34 if isinstance(exception, MarkedYAMLError):
35 origin = origin.replace(line_num=exception.problem_mark.line + 1, col_num=exception.problem_mark.column + 1)
36
37 source_context = _error_utils.SourceContext.from_origin(origin)
38
39 target_line = source_context.target_line or '' # for these cases, we don't need to distinguish between None and empty string
40
41 message: str | None = None
42 help_text = None
43
44 # FIXME: Do all this by walking the parsed YAML doc stream. Using regexes is a dead-end; YAML's just too flexible to not have a
45 # raft of false-positives and corner cases. If we directly consume either the YAML parse stream or override the YAML composer, we can
46 # better catch these things without worrying about duplicating YAML's scalar parsing logic around quoting/escaping. At first, we can
47 # replace the regex logic below with tiny special-purpose parse consumers to catch specific issues, but ideally, we could do a lot of this
48 # inline with the actual doc parse, since our rules are a lot more strict than YAML's (eg, no support for non-scalar keys), and a lot of the
49 # problem cases where that comes into play are around expression quoting and Jinja {{ syntax looking like weird YAML values we don't support.
50 # Some common examples, where -> is "what YAML actually sees":
51 # foo: {{ bar }} -> {"foo": {{"bar": None}: None}} - a mapping with a mapping as its key (legal YAML, but not legal Python/Ansible)
52 #
53 # - copy: src=foo.txt # kv syntax (kv could be on following line(s), too- implicit multi-line block scalar)
54 # dest: bar.txt # orphaned mapping, since the value of `copy` is the scalar "src=foo.txt"
55 #
56 # - msg == "Error: 'dude' was not found" # unquoted scalar has a : in it -> {'msg == "Error"': 'dude'} [ was not found" ] is garbage orphan scalar
57
58 # noinspection PyUnboundLocalVariable
59 if not isinstance(exception, MarkedYAMLError):
60 pass # unexpected exception, don't use special analysis of exception
61
62 elif isinstance(exception, AnsibleConstructorError):
63 pass # raised internally by ansible code, don't use special analysis of exception
64
65 # Check for tabs.
66 # There may be cases where there is a valid tab in a line that has other errors.
67 # That's OK, users should "fix" their tab usage anyway -- at which point later error handling logic will hopefully find the real issue.
68 elif (tab_idx := target_line.find('\t')) >= 0:
69 source_context = _error_utils.SourceContext.from_origin(origin.replace(col_num=tab_idx + 1))
70 message = "Tabs are usually invalid in YAML."
71
72 # Check for unquoted templates.
73 elif match := re.search(r'^\s*(?:-\s+)*(?:[\w\s]+:\s+)?(?P<value>\{\{.*}})', target_line):
74 source_context = _error_utils.SourceContext.from_origin(origin.replace(col_num=match.start('value') + 1))
75 message = 'This may be an issue with missing quotes around a template block.'
76 # FIXME: Use the captured value to show the actual fix required.
77 help_text = """
78 For example:
79
80 raw: {{ some_var }}
81
82 Should be:
83
84 raw: "{{ some_var }}"
85 """
86
87 # Check for common unquoted colon mistakes.
88 elif (
89 # ignore lines starting with only whitespace and a colon
90 not target_line.lstrip().startswith(':')
91 # find the value after list/dict preamble
92 and (value_match := re.search(r'^\s*(?:-\s+)*(?:[\w\s\[\]{}]+:\s+)?(?P<value>.*)$', target_line))
93 # ignore properly quoted values
94 and (target_fragment := _replace_quoted_value(value_match.group('value')))
95 # look for an unquoted colon in the value
96 and (colon_match := re.search(r':($| )', target_fragment))
97 ):
98 source_context = _error_utils.SourceContext.from_origin(origin.replace(col_num=value_match.start('value') + colon_match.start() + 1))
99 message = 'Colons in unquoted values must be followed by a non-space character.'
100 # FIXME: Use the captured value to show the actual fix required.
101 help_text = """
102 For example:
103
104 raw: echo 'name: ansible'
105
106 Should be:
107
108 raw: "echo 'name: ansible'"
109 """
110
111 # Check for common quoting mistakes.
112 elif match := re.search(r'^\s*(?:-\s+)*(?:[\w\s]+:\s+)?(?P<value>[\"\'].*?\s*)$', target_line):
113 suspected_value = match.group('value')
114 first, last = suspected_value[0], suspected_value[-1]
115
116 if first != last: # "foo" in bar
117 source_context = _error_utils.SourceContext.from_origin(origin.replace(col_num=match.start('value') + 1))
118 message = 'Values starting with a quote must end with the same quote.'
119 # FIXME: Use the captured value to show the actual fix required, and use that same logic to improve the origin further.
120 help_text = """
121 For example:
122
123 raw: "foo" in bar
124
125 Should be:
126
127 raw: '"foo" in bar'
128 """
129 elif first == last and target_line.count(first) > 2: # "foo" and "bar"
130 source_context = _error_utils.SourceContext.from_origin(origin.replace(col_num=match.start('value') + 1))
131 message = 'Values starting with a quote must end with the same quote, and not contain that quote.'
132 # FIXME: Use the captured value to show the actual fix required, and use that same logic to improve the origin further.
133 help_text = """
134 For example:
135
136 raw: "foo" in "bar"
137
138 Should be:
139
140 raw: '"foo" in "bar"'
141 """
142
143 if not message:
144 if isinstance(exception, MarkedYAMLError):
145 # marked YAML error, pull out the useful messages while omitting the noise
146 message = ' '.join(filter(None, (exception.context, exception.problem, exception.note)))
147 message = message.strip()
148 message = f'{message[0].upper()}{message[1:]}'
149
150 if not message.endswith('.'):
151 message += '.'
152 else:
153 # unexpected error, use the exception message (normally hidden by overriding include_cause_message)
154 message = str(exception)
155
156 message = re.sub(r'\s+', ' ', message).strip()
157
158 error = cls(message, obj=source_context.origin)
159 error._formatted_source_context_value = str(source_context)
160 error._help_text = help_text
161
162 raise error from exception
163
164
165 def _replace_quoted_value(value: str, replacement='.') -> str:
166 return re.sub(r"""^\s*('[^']*'|"[^"]*")\s*$""", lambda match: replacement * len(match.group(0)), value)