Skip to content

Commit

Permalink
Remove filename from MatchError class
Browse files Browse the repository at this point in the history
  • Loading branch information
ssbarnea committed Jun 3, 2024
1 parent 17c812e commit 4ac5525
Show file tree
Hide file tree
Showing 9 changed files with 61 additions and 26 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tox.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ jobs:
env:
# Number of expected test passes, safety measure for accidental skip of
# tests. Update value if you add/remove tests.
PYTEST_REQPASS: 873
PYTEST_REQPASS: 874
steps:
- uses: actions/checkout@v4
with:
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,4 @@ collections
site
_readthedocs
*.tmp.*
coverage.lcov
8 changes: 5 additions & 3 deletions src/ansiblelint/_internal/rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,19 +165,21 @@ def ids(cls) -> dict[str, str]:
@property
def rule_config(self) -> dict[str, Any]:
"""Retrieve rule specific configuration."""
rule_config = self.options.rules.get(self.id, {})
rule_config = {}
if self.options:
rule_config = self.options.rules.get(self.id, {})
if not isinstance(rule_config, dict): # pragma: no branch
msg = f"Invalid rule config for {self.id}: {rule_config}"
raise RuntimeError(msg) # noqa: TRY004
return rule_config

@property
def options(self) -> Options:
def options(self) -> Options | None:
"""Used to access linter configuration."""
if self._collection is None:
msg = f"A rule ({self.id}) that is not part of a collection cannot access its configuration."
_logger.warning(msg)
raise RuntimeError(msg)
return None
return self._collection.options


Expand Down
18 changes: 9 additions & 9 deletions src/ansiblelint/errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ class MatchError(ValueError):
# order matters for these:
message: str = field(init=True, repr=False, default="")
lintable: Lintable = field(init=True, repr=False, default=Lintable(name=""))
filename: str = field(init=True, repr=False, default="")

tag: str = field(init=True, repr=False, default="")
lineno: int = 1
Expand All @@ -63,10 +62,7 @@ class MatchError(ValueError):

def __post_init__(self) -> None:
"""Can be use by rules that can report multiple errors type, so we can still filter by them."""
if not self.lintable and self.filename:
self.lintable = Lintable(self.filename)
elif self.lintable and not self.filename:
self.filename = self.lintable.name
self.filename = self.lintable.name

# We want to catch accidental MatchError() which contains no useful
# information. When no arguments are passed, the '_message' field is
Expand Down Expand Up @@ -109,8 +105,12 @@ def __post_init__(self) -> None:
@functools.cached_property
def level(self) -> str:
"""Return the level of the rule: error, warning or notice."""
if not self.ignored and {self.tag, self.rule.id, *self.rule.tags}.isdisjoint(
self.rule.options.warn_list,
if (
not self.ignored
and self.rule.options
and {self.tag, self.rule.id, *self.rule.tags}.isdisjoint(
self.rule.options.warn_list,
)
):
return "error"
return "warning"
Expand Down Expand Up @@ -158,11 +158,11 @@ def _hash_key(self) -> Any:
def __lt__(self, other: object) -> bool:
"""Return whether the current object is less than the other."""
if not isinstance(other, self.__class__):
return NotImplemented
raise TypeError
return bool(self._hash_key < other._hash_key)

def __eq__(self, other: object) -> bool:
"""Identify whether the other object represents the same rule match."""
if not isinstance(other, self.__class__):
return NotImplemented
raise TypeError
return self.__hash__() == other.__hash__()
10 changes: 6 additions & 4 deletions src/ansiblelint/rules/name.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,10 +205,12 @@ def _find_full_stem(self, lintable: Lintable) -> str:
lintable_dir = lintable_dir.parent
pathex = lintable_dir / stem
glob = ""
for entry in self.options.kinds:
for key, value in entry.items():
if kind == key:
glob = value

if self.options:
for entry in self.options.kinds:
for key, value in entry.items():
if kind == key:
glob = value

while pathex.globmatch(
glob,
Expand Down
6 changes: 4 additions & 2 deletions src/ansiblelint/rules/only_builtins.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@ def matchtask(
allowed_collections = [
"ansible.builtin",
"ansible.legacy",
*self.options.only_builtins_allow_collections,
]
allowed_modules = builtins + self.options.only_builtins_allow_modules
allowed_modules = builtins
if self.options:
allowed_collections += self.options.only_builtins_allow_collections
allowed_modules += self.options.only_builtins_allow_modules

is_allowed = (
any(module.startswith(f"{prefix}.") for prefix in allowed_collections)
Expand Down
4 changes: 2 additions & 2 deletions src/ansiblelint/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ def run(self) -> list[MatchError]:
match = MatchError(
message=warn.source.message or warn.category.__name__,
rule=self.rules["warning"],
filename=warn.source.filename.filename,
lintable=Lintable(warn.source.filename.filename),
tag=warn.source.tag,
lineno=warn.source.lineno,
)
Expand All @@ -185,7 +185,7 @@ def run(self) -> list[MatchError]:
warn.message if isinstance(warn.message, str) else "?"
),
rule=self.rules["warning"],
filename=str(filename),
lintable=Lintable(str(filename)),
)
matches.append(match)
continue
Expand Down
12 changes: 7 additions & 5 deletions src/ansiblelint/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,10 +404,12 @@ def _validate_task_handler_action_for_role(self, th_action: dict[str, Any]) -> N
raise MatchError(
message=f"Failed to find required 'name' key in {module!s}",
rule=self.rules.rules[0],
filename=(
self.rules.options.lintables[0]
if self.rules.options.lintables
else "."
lintable=Lintable(
(
self.rules.options.lintables[0]
if self.rules.options.lintables
else "."
),
),
)

Expand Down Expand Up @@ -586,7 +588,7 @@ def normalize_task_v2(task: Task) -> dict[str, Any]:
raise MatchError(
rule=AnsibleParserErrorRule(),
message=exc.message,
filename=task.filename or "Unknown",
lintable=Lintable(task.filename or ""),
lineno=raw_task.get(LINE_NUMBER_KEY, 1),
) from exc

Expand Down
26 changes: 26 additions & 0 deletions test/test_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""Test ansiblelint.errors."""

import pytest

from ansiblelint.errors import MatchError


def test_matcherror() -> None:
"""."""
match = MatchError("foo", lineno=1, column=2)
with pytest.raises(TypeError):
assert match <= 0

with pytest.raises(TypeError):
assert match == 0

assert match.position == "1:2"

match2 = MatchError("foo", lineno=1)
assert match2.position == "1"

# str and repr are for the moment the same
assert str(match) == repr(match)

# tests implicit level
assert match.level == "warning"

0 comments on commit 4ac5525

Please sign in to comment.