Skip to content

Commit

Permalink
src/ansiblelint/file_utils.py: Fix playbook/rulebook detection
Browse files Browse the repository at this point in the history
Don't try detecting the file type unless file already loaded
in Lintable._data, otherwise the line numbers for inline
rule skipping will be set to the line where's it's used since
self.kind is 'yaml'. After _guess_kind() call, the kind will
be set to playbook and the error line will be the one of the
task, which is possibly different that the one with the 'noqa:'
comment.

Fixes: #2977
Signed-off-by: Arnaud Patard <apatard@hupstream.com>
  • Loading branch information
apatard committed Feb 9, 2023
1 parent 26a12aa commit 736d060
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 5 deletions.
7 changes: 6 additions & 1 deletion src/ansiblelint/file_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ def __init__(
self.abspath = self.path.expanduser().absolute()

if self.kind == "yaml":
self._guess_kind()
self.data

def _guess_kind(self) -> None:
if self.kind == "yaml":
Expand Down Expand Up @@ -371,6 +371,11 @@ def data(self) -> Any:
)

self._data = parse_yaml_linenumbers(self)
# now that _data is not empty, we can try guessing if playbook or rulebook
# it has to be done before append_skipped_rules() call as it's relying
# on self.kind.
if self.kind == "yaml":
self._guess_kind()
# Lazy import to avoid delays and cyclic-imports
if "append_skipped_rules" not in globals():
# pylint: disable=import-outside-toplevel
Expand Down
8 changes: 4 additions & 4 deletions src/ansiblelint/testing/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ def run(self, filename: str) -> list[MatchError]:
"""Lints received filename."""
return self._call_runner(filename)

def run_playbook(self, playbook_text: str) -> list[MatchError]:
def run_playbook(
self, playbook_text: str, prefix: str = "playbook"
) -> list[MatchError]:
"""Lints received text as a playbook."""
with tempfile.NamedTemporaryFile(
mode="w", suffix=".yml", prefix="playbook"
) as fh:
with tempfile.NamedTemporaryFile(mode="w", suffix=".yml", prefix=prefix) as fh:
fh.write(playbook_text)
fh.flush()
results = self._call_runner(fh.name)
Expand Down
7 changes: 7 additions & 0 deletions test/test_skiputils.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,13 @@ def test_playbook_noqa(default_text_runner: RunFromText) -> None:
assert len(results) == 1


def test_playbook_noqa2(default_text_runner: RunFromText) -> None:
"""Check that noqa is properly taken into account on vars and tasks."""
results = default_text_runner.run_playbook(PLAYBOOK_WITH_NOQA, "test")
# Should raise error at "SOME_VAR".
assert len(results) == 1


@pytest.mark.parametrize(
("lintable", "yaml", "expected_form"),
(
Expand Down

0 comments on commit 736d060

Please sign in to comment.