diff options
author | Sam Doran <sdoran@redhat.com> | 2021-01-19 10:07:36 -0500 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-01-19 10:07:36 -0500 |
commit | e8d4b62b411fb7e3ba3131906a4122185d417266 (patch) | |
tree | c985da0171c197c896c384580616e6a3a32241fb /lib/ansible/errors | |
parent | 30d93995ddcf92636919c2238435064a8089e240 (diff) | |
download | ansible-e8d4b62b411fb7e3ba3131906a4122185d417266.tar.gz |
Fix YAML error message when error is at the end of the file (#73241)
* Fix YAML error message when error is at the end of the file
If a YAML file fails to load due to a syntax error in a file, or there is an error in the last line of a
file, PyYAML reports the last line number of the file as the index where the error occurred.
When reading the file lines, we use that index to the get the relevant line. If the index value is out
of range, the relevant line is lost for error reporting.
Subtract one from the index value to avoid the IndexError in this specific scenario. It is possible
to still get an IndexError, which will be handled as it is currently.
* Update existing tests and add new tests
Diffstat (limited to 'lib/ansible/errors')
-rw-r--r-- | lib/ansible/errors/__init__.py | 14 |
1 files changed, 14 insertions, 0 deletions
diff --git a/lib/ansible/errors/__init__.py b/lib/ansible/errors/__init__.py index c9831a5cdd..782d0719d1 100644 --- a/lib/ansible/errors/__init__.py +++ b/lib/ansible/errors/__init__.py @@ -100,7 +100,21 @@ class AnsibleError(Exception): with open(file_name, 'r') as f: lines = f.readlines() + # In case of a YAML loading error, PyYAML will report the very last line + # as the location of the error. Avoid an index error here in order to + # return a helpful message. + file_length = len(lines) + if line_number >= file_length: + line_number = file_length - 1 + + # If target_line contains only whitespace, move backwards until + # actual code is found. If there are several empty lines after target_line, + # the error lines would just be blank, which is not very helpful. target_line = lines[line_number] + while not target_line.strip(): + line_number -= 1 + target_line = lines[line_number] + if line_number > 0: prev_line = lines[line_number - 1] |