Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove filename from MatchError class #4202

Merged
merged 1 commit into from
Jun 4, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/tox.yml
Original file line number Diff line number Diff line change
@@ -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:
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -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
@@ -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


14 changes: 7 additions & 7 deletions src/ansiblelint/errors.py
Original file line number Diff line number Diff line change
@@ -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
@@ -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
@@ -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"
10 changes: 6 additions & 4 deletions src/ansiblelint/rules/name.py
Original file line number Diff line number Diff line change
@@ -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,
6 changes: 4 additions & 2 deletions src/ansiblelint/rules/only_builtins.py
Original file line number Diff line number Diff line change
@@ -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)
4 changes: 2 additions & 2 deletions src/ansiblelint/runner.py
Original file line number Diff line number Diff line change
@@ -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,
)
@@ -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
12 changes: 7 additions & 5 deletions src/ansiblelint/utils.py
Original file line number Diff line number Diff line change
@@ -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 "."
),
),
)

@@ -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

25 changes: 25 additions & 0 deletions test/test_errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""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

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"