Skip to content

Commit 6c4ef30

Browse files
committed
Renamed rule class methods (naming convention)
Renames - matchyaml -> match_file - matchtask -> match_task - matchtasks -> match_tasks - matcherror -> match_error - matchvar -> match_var - matchdir -> match_dir - create_matcherror -> create_match_error
1 parent 3942375 commit 6c4ef30

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

69 files changed

+498
-690
lines changed

.config/dictionary.txt

Lines changed: 37 additions & 242 deletions
Large diffs are not rendered by default.

.pre-commit-config.yaml

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -64,9 +64,10 @@ repos:
6464
rev: v9.0.1
6565
hooks:
6666
- id: cspell
67-
# entry: codespell --relative
68-
args: [--relative, --no-progress, --no-summary]
69-
name: Spell check with cspell
67+
entry: sh
68+
pass_filenames: false
69+
args: ["-c", "cspell-cli . --relative --no-progress --no-summary && cspell . --disable-dictionary=words --words-only --quiet --unique | sort --ignore-case > .config/dictionary.txt"]
70+
name: Spell check with cspell and remove unused dictionary entries
7071
- repo: https://github.com/python-jsonschema/check-jsonschema
7172
rev: 0.33.1
7273
hooks:

cspell.config.yaml

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,13 @@ ignorePaths:
2323
# Other
2424
- "*.svg"
2525
- ".vscode/**"
26+
- build
27+
- _readthedocs
28+
- examples/playbooks/collections
29+
- site
30+
- test/schemas/node_modules
31+
- .config/dictionary.txt
32+
- "*.egg-info"
33+
- junit.xml
34+
- examples/broken/encoding.yml
35+

docs/custom-rules.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Each rule definition should have the following parts:
1717
- `description` explains what the rule checks for.
1818
- `tags` specifies one or more tags for including or excluding the rule.
1919

20-
### Match and matchtask methods
20+
### Match and match_task methods
2121

2222
Each rule definition should also invoke one of the following methods:
2323

@@ -26,7 +26,7 @@ Each rule definition should also invoke one of the following methods:
2626
- True or a custom message if the line does match the test. (This allows one
2727
rule to test multiple behaviors - see e.g. the
2828
_CommandsInsteadOfModulesRule_.)
29-
- `matchtask` operates on a single task or handler, such that tasks get
29+
- `match_task` operates on a single task or handler, such that tasks get
3030
standardized to always contain a _module_ key and _module_arguments_ key.
3131
Other common task modifiers, such as _when_, _with_items_, etc., are also
3232
available as keys if present in the task.
@@ -50,13 +50,13 @@ class DeprecatedVariableRule(AnsibleLintRule):
5050
return '${' in line
5151
```
5252

53-
The following is an example rule that uses the `matchtask` method:
53+
The following is an example rule that uses the `match_task` method:
5454

5555
```python
5656
{!../examples/rules/task_has_tag.py!}
5757
```
5858

59-
The task argument to `matchtask` contains a number of keys - the critical one is
59+
The task argument to `match_task` contains a number of keys - the critical one is
6060
_action_. The value of `task['action']` contains the module being used, and the
6161
arguments passed, both as key-value pairs and a list of other arguments (e.g.
6262
the command used with shell).

examples/rules/task_has_tag.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ class TaskHasTag(AnsibleLintRule):
1818
description = "Tasks must have tag"
1919
tags = ["productivity", "tags"]
2020

21-
def matchtask(
21+
def match_task(
2222
self,
2323
task: Task,
2424
file: Lintable | None = None,

src/ansiblelint/_internal/rules.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313

1414
if TYPE_CHECKING:
1515
from ansiblelint.config import Options
16-
from ansiblelint.errors import MatchError
16+
from ansiblelint.errors import match_error
1717
from ansiblelint.file_utils import Lintable
1818
from ansiblelint.rules import RulesCollection
1919
from ansiblelint.utils import Task
@@ -96,11 +96,11 @@ def shortdesc(self) -> str:
9696
"""Return the short description of the rule, basically the docstring."""
9797
return self._shortdesc or self.__doc__ or ""
9898

99-
def getmatches(self, file: Lintable) -> list[MatchError]:
99+
def getmatches(self, file: Lintable) -> list[match_error]:
100100
"""Return all matches while ignoring exceptions."""
101101
matches = []
102102
if not file.path.is_dir():
103-
for method in [self.matchlines, self.matchtasks, self.matchyaml]:
103+
for method in [self.match_lines, self.match_tasks, self.match_file]:
104104
try:
105105
matches.extend(method(file))
106106
except Exception as exc: # pylint: disable=broad-except # noqa: BLE001
@@ -113,18 +113,18 @@ def getmatches(self, file: Lintable) -> list[MatchError]:
113113
)
114114
_logger.debug("Ignored exception details", exc_info=True)
115115
else:
116-
matches.extend(self.matchdir(file))
116+
matches.extend(self.match_dir(file))
117117
return matches
118118

119-
def matchlines(self, file: Lintable) -> list[MatchError]:
119+
def match_lines(self, file: Lintable) -> list[match_error]:
120120
"""Return matches found for a specific line."""
121121
return []
122122

123-
def matchtask(
123+
def match_task(
124124
self,
125125
task: Task,
126126
file: Lintable | None = None,
127-
) -> bool | str | MatchError | list[MatchError]:
127+
) -> bool | str | match_error | list[match_error]:
128128
"""Confirm if current rule is matching a specific task.
129129
130130
If ``needs_raw_task`` (a class level attribute) is ``True``, then
@@ -133,19 +133,19 @@ def matchtask(
133133
"""
134134
return False
135135

136-
def matchtasks(self, file: Lintable) -> list[MatchError]:
136+
def match_tasks(self, file: Lintable) -> list[match_error]:
137137
"""Return matches for a tasks file."""
138138
return []
139139

140-
def matchyaml(self, file: Lintable) -> list[MatchError]:
140+
def match_file(self, file: Lintable) -> list[match_error]:
141141
"""Return matches found for a specific YAML text."""
142142
return []
143143

144-
def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]:
144+
def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[match_error]:
145145
"""Return matches found for a specific playbook."""
146146
return []
147147

148-
def matchdir(self, lintable: Lintable) -> list[MatchError]:
148+
def match_dir(self, lintable: Lintable) -> list[match_error]:
149149
"""Return matches for lintable folders."""
150150
return []
151151

src/ansiblelint/app.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525

2626
if TYPE_CHECKING:
2727
from ansiblelint._internal.rules import BaseRule
28-
from ansiblelint.errors import MatchError
28+
from ansiblelint.errors import match_error
2929
from ansiblelint.file_utils import Lintable
3030
from ansiblelint.runner import LintResult
3131

@@ -68,7 +68,7 @@ def __init__(self, options: Options):
6868

6969
self.yamllint_config = load_yamllint_config()
7070

71-
def render_matches(self, matches: list[MatchError]) -> None:
71+
def render_matches(self, matches: list[match_error]) -> None:
7272
"""Display given matches (if they are not fixed)."""
7373
matches = [match for match in matches if not match.fixed]
7474

@@ -129,7 +129,7 @@ def render_matches(self, matches: list[MatchError]) -> None:
129129
encoding="utf-8",
130130
)
131131

132-
def count_results(self, matches: list[MatchError]) -> SummarizedResults:
132+
def count_results(self, matches: list[match_error]) -> SummarizedResults:
133133
"""Count failures and warnings in matches."""
134134
result = SummarizedResults()
135135

@@ -175,7 +175,7 @@ def count_lintables(files: set[Lintable]) -> tuple[int, int]:
175175

176176
@staticmethod
177177
def _get_matched_skippable_rules(
178-
matches: list[MatchError],
178+
matches: list[match_error],
179179
) -> dict[str, BaseRule]:
180180
"""Extract the list of matched rules, if skippable, from the list of matches."""
181181
matches_unignored = [match for match in matches if not match.ignored]

src/ansiblelint/errors.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ class LintWarning(Warning):
1919

2020
@dataclass
2121
class WarnSource:
22-
"""Container for warning information, so we can later create a MatchError from it."""
22+
"""Container for warning information, so we can later create a match_error from it."""
2323

2424
filename: Lintable
2525
lineno: int
@@ -35,7 +35,7 @@ class RuleMatchTransformMeta:
3535
# pylint: disable=too-many-instance-attributes
3636
@dataclass(unsafe_hash=True)
3737
@functools.total_ordering
38-
class MatchError(ValueError):
38+
class match_error(ValueError):
3939
"""Rule violation detected during linting.
4040
4141
It can be raised as Exception but also just added to the list of found
@@ -57,14 +57,14 @@ class MatchError(ValueError):
5757
# of the same rule, but we use the 'tag' to identify the rule.
5858
rule: BaseRule = field(hash=False, default=RuntimeErrorRule())
5959
ignored: bool = False
60-
fixed: bool = False # True when a transform has resolved this MatchError
60+
fixed: bool = False # True when a transform has resolved this match_error
6161
transform_meta: RuleMatchTransformMeta | None = None
6262

6363
def __post_init__(self) -> None:
6464
"""Can be use by rules that can report multiple errors type, so we can still filter by them."""
6565
self.filename = self.lintable.name
6666

67-
# We want to catch accidental MatchError() which contains no useful
67+
# We want to catch accidental match_error() which contains no useful
6868
# information. When no arguments are passed, the '_message' field is
6969
# set to 'property', only if passed it becomes a string.
7070
if self.rule.__class__ is RuntimeErrorRule:
@@ -89,10 +89,10 @@ def __post_init__(self) -> None:
8989

9090
# Safety measure to ensure we do not end-up with incorrect indexes
9191
if self.lineno == 0: # pragma: no cover
92-
msg = "MatchError called incorrectly as line numbers start with 1"
92+
msg = "match_error called incorrectly as line numbers start with 1"
9393
raise RuntimeError(msg)
9494
if self.column == 0: # pragma: no cover
95-
msg = "MatchError called incorrectly as column numbers start with 1"
95+
msg = "match_error called incorrectly as column numbers start with 1"
9696
raise RuntimeError(msg)
9797

9898
self.lineno += self.lintable.line_offset
@@ -116,7 +116,7 @@ def level(self) -> str:
116116
return "warning"
117117

118118
def __repr__(self) -> str:
119-
"""Return a MatchError instance representation."""
119+
"""Return a match_error instance representation."""
120120
formatstr = "[{0}] ({1}) matched {2}:{3} {4}"
121121
# note that `rule.id` can be int, str or even missing, as users
122122
# can defined their own custom rules.
@@ -131,7 +131,7 @@ def __repr__(self) -> str:
131131
)
132132

133133
def __str__(self) -> str:
134-
"""Return a MatchError instance string representation."""
134+
"""Return a match_error instance string representation."""
135135
return self.__repr__()
136136

137137
@property

src/ansiblelint/file_utils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
if TYPE_CHECKING:
2525
from collections.abc import Iterator, Sequence
2626

27-
from ansiblelint.errors import MatchError
27+
from ansiblelint.errors import match_error
2828

2929

3030
_logger = logging.getLogger(__package__)
@@ -204,7 +204,7 @@ def __init__(
204204
self.line_offset = (
205205
0 # Amount to offset line numbers by to get accurate position
206206
)
207-
self.matches: list[MatchError] = []
207+
self.matches: list[match_error] = []
208208

209209
if isinstance(name, str):
210210
name = Path(name)

src/ansiblelint/formatters/__init__.py

Lines changed: 16 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
from ansiblelint.version import __version__
1313

1414
if TYPE_CHECKING:
15-
from ansiblelint.errors import MatchError
15+
from ansiblelint.errors import match_error
1616
from ansiblelint.rules import BaseRule # type: ignore[attr-defined]
1717

1818
T = TypeVar("T", bound="BaseFormatter") # type: ignore[type-arg]
@@ -49,7 +49,7 @@ def _format_path(self, path: str | Path) -> str | Path:
4949
return path
5050
return rel_path
5151

52-
def apply(self, match: MatchError) -> str:
52+
def apply(self, match: match_error) -> str:
5353
"""Format a match error."""
5454
return str(match)
5555

@@ -62,7 +62,7 @@ def escape(text: str) -> str:
6262
class Formatter(BaseFormatter): # type: ignore[type-arg]
6363
"""Default output formatter of ansible-lint."""
6464

65-
def apply(self, match: MatchError) -> str:
65+
def apply(self, match: match_error) -> str:
6666
_id = getattr(match.rule, "id", "000")
6767
result = f"[{match.level}][link={match.rule.url}]{match.tag}[/link][dim]:[/] [{match.level}]{self.escape(match.message)}[/]"
6868
if match.level != "error":
@@ -82,7 +82,7 @@ def apply(self, match: MatchError) -> str:
8282
class QuietFormatter(BaseFormatter[Any]):
8383
"""Brief output formatter for ansible-lint."""
8484

85-
def apply(self, match: MatchError) -> str:
85+
def apply(self, match: match_error) -> str:
8686
return (
8787
f"[{match.level}]{match.rule.id}[/] "
8888
f"[repr.path]{self._format_path(match.filename or '')}[/]:{match.position}"
@@ -92,7 +92,7 @@ def apply(self, match: MatchError) -> str:
9292
class ParseableFormatter(BaseFormatter[Any]):
9393
"""Parseable uses PEP8 compatible format."""
9494

95-
def apply(self, match: MatchError) -> str:
95+
def apply(self, match: match_error) -> str:
9696
result = (
9797
f"[repr.path]{self._format_path(match.filename or '')}[/][dim]:{match.position}:[/] "
9898
f"[{match.level}][bold]{self.escape(match.tag)}[/]"
@@ -119,7 +119,7 @@ class AnnotationsFormatter(BaseFormatter): # type: ignore[type-arg]
119119
Supported levels: debug, warning, error
120120
"""
121121

122-
def apply(self, match: MatchError) -> str:
122+
def apply(self, match: match_error) -> str:
123123
"""Prepare a match instance for reporting as a GitHub Actions annotation."""
124124
file_path = self._format_path(match.filename or "")
125125
line_num = match.lineno
@@ -135,15 +135,15 @@ def apply(self, match: MatchError) -> str:
135135
class CodeclimateJSONFormatter(BaseFormatter[Any]):
136136
"""Formatter for emitting violations in Codeclimate JSON report format.
137137
138-
The formatter expects a list of MatchError objects and returns a JSON formatted string.
138+
The formatter expects a list of match_error objects and returns a JSON formatted string.
139139
The spec for the codeclimate report can be found here:
140140
https://github.com/codeclimate/platform/blob/master/spec/analyzers/SPEC.md#user-content-data-types
141141
"""
142142

143-
def format_result(self, matches: list[MatchError]) -> str:
143+
def format_result(self, matches: list[match_error]) -> str:
144144
"""Format a list of match errors as a JSON string."""
145145
if not isinstance(matches, list):
146-
msg = f"The {self.__class__} was expecting a list of MatchError."
146+
msg = f"The {self.__class__} was expecting a list of match_error."
147147
raise TypeError(msg)
148148

149149
result = []
@@ -180,7 +180,7 @@ def format_result(self, matches: list[MatchError]) -> str:
180180
return json.dumps(result, sort_keys=False)
181181

182182
@staticmethod
183-
def _remap_severity(match: MatchError) -> str:
183+
def _remap_severity(match: match_error) -> str:
184184
# level is not part of CodeClimate specification, but there is
185185
# no other way to expose that info. We recommend switching to
186186
# SARIF format which is better suited for interoperability.
@@ -207,10 +207,10 @@ class SarifFormatter(BaseFormatter[Any]):
207207
"https://schemastore.azurewebsites.net/schemas/json/sarif-2.1.0-rtm.5.json"
208208
)
209209

210-
def format_result(self, matches: list[MatchError]) -> str:
210+
def format_result(self, matches: list[match_error]) -> str:
211211
"""Format a list of match errors as a JSON string."""
212212
if not isinstance(matches, list):
213-
msg = f"The {self.__class__} was expecting a list of MatchError."
213+
msg = f"The {self.__class__} was expecting a list of match_error."
214214
raise TypeError(msg)
215215

216216
root_path = Path(str(self.base_dir)).as_uri()
@@ -247,7 +247,7 @@ def format_result(self, matches: list[MatchError]) -> str:
247247

248248
def _extract_results(
249249
self,
250-
matches: list[MatchError],
250+
matches: list[match_error],
251251
) -> tuple[list[Any], list[Any]]:
252252
rules = {}
253253
results = []
@@ -257,7 +257,7 @@ def _extract_results(
257257
results.append(self._to_sarif_result(match))
258258
return list(rules.values()), results
259259

260-
def _to_sarif_rule(self, match: MatchError) -> dict[str, Any]:
260+
def _to_sarif_rule(self, match: match_error) -> dict[str, Any]:
261261
rule: dict[str, Any] = {
262262
"id": match.tag,
263263
"name": match.tag,
@@ -275,7 +275,7 @@ def _to_sarif_rule(self, match: MatchError) -> dict[str, Any]:
275275
}
276276
return rule
277277

278-
def _to_sarif_result(self, match: MatchError) -> dict[str, Any]:
278+
def _to_sarif_result(self, match: match_error) -> dict[str, Any]:
279279
# https://docs.oasis-open.org/sarif/sarif/v2.1.0/errata01/os/sarif-v2.1.0-errata01-os-complete.html#_Toc141790898
280280
if match.level not in ("warning", "error", "note", "none"):
281281
msg = "Unexpected failure to map '%s' level to SARIF."
@@ -333,7 +333,7 @@ def get_sarif_rule_severity_level(rule: BaseRule) -> str:
333333
return "none"
334334

335335
@staticmethod
336-
def get_sarif_result_severity_level(match: MatchError) -> str:
336+
def get_sarif_result_severity_level(match: match_error) -> str:
337337
"""SARIF severity level for an actual result/match.
338338
339339
Possible values: "none", "note", "warning", "error"

0 commit comments

Comments
 (0)