From 2a55cd2ed8191c97f289d30766f697bddf4c9bab Mon Sep 17 00:00:00 2001 From: Sorin Sbarnea Date: Thu, 26 Jun 2025 17:46:43 +0100 Subject: [PATCH 1/2] 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 --- .config/dictionary.txt | 370 ++---------------- .pre-commit-config.yaml | 11 +- cspell.config.yaml | 15 +- docs/custom-rules.md | 8 +- examples/rules/task_has_tag.py | 2 +- src/ansiblelint/_internal/rules.py | 12 +- src/ansiblelint/config.py | 4 +- src/ansiblelint/rules/__init__.py | 30 +- src/ansiblelint/rules/args.py | 6 +- src/ansiblelint/rules/avoid_implicit.py | 2 +- .../rules/command_instead_of_module.py | 2 +- .../rules/command_instead_of_shell.py | 2 +- src/ansiblelint/rules/complexity.py | 6 +- src/ansiblelint/rules/deprecated_bare_vars.py | 2 +- .../rules/deprecated_local_action.py | 2 +- src/ansiblelint/rules/deprecated_module.py | 2 +- src/ansiblelint/rules/empty_string_compare.py | 2 +- src/ansiblelint/rules/fqcn.py | 14 +- src/ansiblelint/rules/galaxy.py | 16 +- .../rules/galaxy_version_incorrect.py | 2 +- src/ansiblelint/rules/ignore_errors.py | 2 +- src/ansiblelint/rules/inline_env_var.py | 2 +- src/ansiblelint/rules/jinja.py | 20 +- src/ansiblelint/rules/key_order.py | 6 +- src/ansiblelint/rules/latest.py | 6 +- src/ansiblelint/rules/literal_compare.py | 2 +- src/ansiblelint/rules/loop_var_prefix.py | 6 +- src/ansiblelint/rules/meta_incorrect.py | 4 +- src/ansiblelint/rules/meta_no_tags.py | 12 +- src/ansiblelint/rules/meta_runtime.py | 6 +- src/ansiblelint/rules/meta_video_links.py | 8 +- src/ansiblelint/rules/name.py | 14 +- src/ansiblelint/rules/no_changed_when.py | 4 +- src/ansiblelint/rules/no_free_form.py | 8 +- src/ansiblelint/rules/no_handler.py | 4 +- src/ansiblelint/rules/no_jinja_when.py | 4 +- src/ansiblelint/rules/no_log_password.py | 2 +- src/ansiblelint/rules/no_prompting.py | 4 +- src/ansiblelint/rules/no_relative_paths.py | 2 +- src/ansiblelint/rules/no_same_owner.py | 2 +- src/ansiblelint/rules/no_tabs.py | 6 +- src/ansiblelint/rules/only_builtins.py | 2 +- src/ansiblelint/rules/package_latest.py | 2 +- src/ansiblelint/rules/partial_become.py | 6 +- src/ansiblelint/rules/playbook_extension.py | 4 +- .../rules/risky_file_permissions.py | 2 +- src/ansiblelint/rules/risky_octal.py | 2 +- src/ansiblelint/rules/risky_shell_pipe.py | 2 +- src/ansiblelint/rules/role_name.py | 16 +- src/ansiblelint/rules/run_once.py | 6 +- src/ansiblelint/rules/sanity.py | 6 +- src/ansiblelint/rules/schema.py | 12 +- src/ansiblelint/rules/var_naming.py | 20 +- src/ansiblelint/rules/yaml_rule.py | 4 +- test/rules/fixtures/raw_task.py | 2 +- test/test_lint_rule.py | 2 +- 56 files changed, 207 insertions(+), 515 deletions(-) diff --git a/.config/dictionary.txt b/.config/dictionary.txt index 0d7925e538..576d11f2d2 100644 --- a/.config/dictionary.txt +++ b/.config/dictionary.txt @@ -1,437 +1,113 @@ -Adrián -Autobuild -CLICOLOR -CODENOTIFY -CODEOWNERS -CTYPE -Cacqueray -Chamoulaud -DISTRO -DOTGLOB -ENVVAR -EPEL -EPIPE # linux -Fimport -Jython -MYTAG -PYTHONBREAKPOINT -PYTHONIOENCODING -PYTHONPYCACHEPREFIX -RULEDIRS -RUNLEVEL -Renderable -Representer -SIGUSR1 -SRCROOT -Sbarnea -Sorin -Sshell -TOXENV -TYPECHECK -Taskfiles -Tsukinowa -Tóth -WSLENV -aarch64 -abspath -addoption -addopts alertmanager ansiblelint -apidoc apport -argparsing -argspec -argspecs -arxcruz audgirka -auditd -autobuild -autoclass -autodetected -autodiscovery -autodoc -autofix autohide -autorefs -autoupdate -awcrosby -backports -backticks -bdist -becomeuserabove -bindep -blockincludes blockinfile -bools -boto bracketsmatchtest bracketsmatchtestfile -buildinfo -buildset -builtins -cacheable cachier -capfd -caplog -capsys -cffi -chdir -chgrp -chkconfig -chunksize -clib +Chamoulaud codeclimate -codecov -codenotify -codeql +Codeclimate codespell -colorama -colsystem -commandline -commitlint -commonmark -compat -conftest -coveragerc -cpus -cpuset -createfile -darglint -dataclasses -dbservers deannotate debconf -debops -decryptable -delenv dellemc -denormalize -deps devel -dharmabumstead -direnv -dirhtml -dists -distutils +DEVEL doas -docstrings -doctest -doctrees -docutils -dotconfig -dotslash -drybjed -dunder dzdo ematcher ematchtestfile -envrc -execnet -extlinks -facelessuser facter fakerole -fastapi -fileglob -filelock filesspot -filetree -fips firewalld fontawesome -formatstr formetting fqcn -fqrn -fstring -fulltoc -fullwidth -gecos +FQCN +FQCNs geerlingguy -getent getmatches -globbing -globmatch -gplv3 -groupname -hostkey -hostnames -hostvars -htmldir +gplv htmlproofer -htpasswd -hwchksum -hwcksum -idempotency -ignorelist -importlib indentless -iniconfig inlinehilite -insertafter -ipaddr -ipwrap -isclass iscsi -isdir -isdisjoint -iskeyword -isort -isorted -jsonfile -jsonschema junitxml -keepends -keypair -keyserver -konstruktoid -kubernetes kubevirt lalo -languageservice -letsencrypt -levelname -libbzip -libera libyaml +LIBYAML licensedb lineinfile -linenums -linkcheck +Lineinfile +LINEINFILE lintable +Lintable lintables -literalinclude -localectl -machinectl -magiclink -markdownlint -matchdir -matcherror -matchlines -matchtask -matchtasks -matchvar -matchyaml -maxdepth -maxsplit -minversion -mkdir -mkdocs -mkdocstrings -mkdtemp mockings -mockreturn -modifyitems -modindex -moduleauthor -mypy -myrole -namedtempfile -nestedincludes netcommon -netscaler -nilashishc -nitpicky -nocolor nodeps -noexist -nomatches +NODEPS nomatchestest -noqa -norole -nostderr -notest nxos -octal octals -opensearch -openshift -outdir -outlen -pacman -pageview -panos +Octals parseable +Parseable pathex -pathlib -pathspec -pathspecs pbrun pfexec -pickleable -pipefail -piptools -pipx -pkgcache # linux -pkgs placefolder plainexamples -pluggy -pluginmanager pmrun -podman -portchannel -posargs -preexec -prerun -prettierignore -programoutput -psutil pwsh -pyargs -pycache -pycharm -pyenv -pygments -pylint -pylintrc -pymdown pymdownx -pypa -pyparsing -pypi -pyproject -pyproject.toml -pypy -pyright -pytest -pyupgrade -pyyaml -redef +PYTHONBREAKPOINT +PYTHONIOENCODING +PYTHONPYCACHEPREFIX redirections -reexec reformatter -regexes releasenotes -relpath -reportversion representer -reqs -resolvelib -returncode -rmtree -robertdebock -rolepath -roundtrip -ruamel -rulebook +Representer rulebooks -ruledirs -rulesdir -rulesdirs -ruleset runas sarif -scalarint -scalarstring -scancode -schemafile -sdist -sdists -sectionauthor +Sarif +SARIF +Sbarnea seealso sesu -setenv -setuptools -shortdesc -showlocals -shutil -signoff -simpletask simplifiable -skippable -skiptasks -skiputils slackpkg -slaveinput -sortfunc -sourcegraph -srcs -srpm +Sorin ssbarnea -stylesheet -subdir -subelements -subfolders -subresults -subschema -subschemas -substrs -subtest sudosu superfences supervisorctl swdepot switchport -synchronize sysvinit -taskfile -taskhandler -taskimports -taskincludes taskshandlers -templatevars -templating -testcollection testinfra -testmon testns -testpath -testpaths -testproject -testpypi -testrun timesyncd tmpfs -toctree -toidentifier -tomli tomlsort -toolset -tripleo +Tsukinowa tuco -typehint typehints -ulimits -uncook -ungrouped -unignored -unimported -unindented -uninstallation unjinja unlex -unloadable -unnormalized unskippable -unspaced -unsubscriptable untemplated -userbase -uwsgi -validable -vararg -varname -varnotset -varset -varsfile -varstring -varunset -venv -viewcode virtnet -virtualenv -virtualenvs -wcmatch -webserver -webservers willthames -workdir workerinput -worktree +WSLENV xdist -xfail -xunit yatesr -zuul diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 2a5041b47b..5d38912373 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -64,9 +64,14 @@ repos: rev: v9.0.1 hooks: - id: cspell - # entry: codespell --relative - args: [--relative, --no-progress, --no-summary] - name: Spell check with cspell + entry: sh + pass_filenames: false + args: + [ + "-c", + "cspell-cli . --relative --no-progress --no-summary && cspell . --disable-dictionary=words --words-only --quiet --unique | sort --ignore-case > .config/dictionary.txt", + ] + name: Spell check with cspell and remove unused dictionary entries - repo: https://github.com/python-jsonschema/check-jsonschema rev: 0.33.1 hooks: diff --git a/cspell.config.yaml b/cspell.config.yaml index d7cd4c47d9..01d6626c22 100644 --- a/cspell.config.yaml +++ b/cspell.config.yaml @@ -5,11 +5,13 @@ dictionaryDefinitions: addWords: true dictionaries: # Use `cspell-cli trace word` to check where a work is defined - - en_US - bash - - words + - cpp + - en_US + - node - python - python-common + - words enabled: true ignorePaths: - cspell.config.yaml @@ -23,3 +25,12 @@ ignorePaths: # Other - "*.svg" - ".vscode/**" + - build + - _readthedocs + - examples/playbooks/collections + - site + - test/schemas/node_modules + - .config/dictionary.txt + - "*.egg-info" + - junit.xml + - examples/broken/encoding.yml diff --git a/docs/custom-rules.md b/docs/custom-rules.md index 50b95375ca..db3052800f 100644 --- a/docs/custom-rules.md +++ b/docs/custom-rules.md @@ -17,7 +17,7 @@ Each rule definition should have the following parts: - `description` explains what the rule checks for. - `tags` specifies one or more tags for including or excluding the rule. -### Match and matchtask methods +### Match and match_task methods Each rule definition should also invoke one of the following methods: @@ -26,7 +26,7 @@ Each rule definition should also invoke one of the following methods: - True or a custom message if the line does match the test. (This allows one rule to test multiple behaviors - see e.g. the _CommandsInsteadOfModulesRule_.) -- `matchtask` operates on a single task or handler, such that tasks get +- `match_task` operates on a single task or handler, such that tasks get standardized to always contain a _module_ key and _module_arguments_ key. Other common task modifiers, such as _when_, _with_items_, etc., are also available as keys if present in the task. @@ -50,13 +50,13 @@ class DeprecatedVariableRule(AnsibleLintRule): return '${' in line ``` -The following is an example rule that uses the `matchtask` method: +The following is an example rule that uses the `match_task` method: ```python {!../examples/rules/task_has_tag.py!} ``` -The task argument to `matchtask` contains a number of keys - the critical one is +The task argument to `match_task` contains a number of keys - the critical one is _action_. The value of `task['action']` contains the module being used, and the arguments passed, both as key-value pairs and a list of other arguments (e.g. the command used with shell). diff --git a/examples/rules/task_has_tag.py b/examples/rules/task_has_tag.py index 691d1fc31e..ff73a7c7ef 100644 --- a/examples/rules/task_has_tag.py +++ b/examples/rules/task_has_tag.py @@ -18,7 +18,7 @@ class TaskHasTag(AnsibleLintRule): description = "Tasks must have tag" tags = ["productivity", "tags"] - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/_internal/rules.py b/src/ansiblelint/_internal/rules.py index c201767e35..57d87e67b8 100644 --- a/src/ansiblelint/_internal/rules.py +++ b/src/ansiblelint/_internal/rules.py @@ -100,7 +100,7 @@ def getmatches(self, file: Lintable) -> list[MatchError]: """Return all matches while ignoring exceptions.""" matches = [] if not file.path.is_dir(): - for method in [self.matchlines, self.matchtasks, self.matchyaml]: + for method in [self.matchlines, self.match_tasks, self.match_file]: try: matches.extend(method(file)) except Exception as exc: # pylint: disable=broad-except # noqa: BLE001 @@ -113,14 +113,14 @@ def getmatches(self, file: Lintable) -> list[MatchError]: ) _logger.debug("Ignored exception details", exc_info=True) else: - matches.extend(self.matchdir(file)) + matches.extend(self.match_dir(file)) return matches def matchlines(self, file: Lintable) -> list[MatchError]: """Return matches found for a specific line.""" return [] - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -133,11 +133,11 @@ def matchtask( """ return False - def matchtasks(self, file: Lintable) -> list[MatchError]: + def match_tasks(self, file: Lintable) -> list[MatchError]: """Return matches for a tasks file.""" return [] - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: """Return matches found for a specific YAML text.""" return [] @@ -145,7 +145,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: """Return matches found for a specific playbook.""" return [] - def matchdir(self, lintable: Lintable) -> list[MatchError]: + def match_dir(self, lintable: Lintable) -> list[MatchError]: """Return matches for lintable folders.""" return [] diff --git a/src/ansiblelint/config.py b/src/ansiblelint/config.py index f96478b7a0..bcbf5c2cde 100644 --- a/src/ansiblelint/config.py +++ b/src/ansiblelint/config.py @@ -39,7 +39,7 @@ {"jinja2": "**/*.j2"}, # jinja2 templates are not always parsable as something else {"jinja2": "**/*.j2.*"}, {"yaml": ".github/**/*.{yaml,yml}"}, # github workflows - {"text": "**/templates/**/*.*"}, # templates are likely not validable + {"text": "**/templates/**/*.*"}, # templates will probably not validate {"execution-environment": "**/execution-environment.yml"}, {"ansible-lint-config": "**/.ansible-lint"}, {"ansible-lint-config": "**/.ansible-lint.{yaml,yml}"}, @@ -91,7 +91,7 @@ "text/jinja2": "**/*.j2", }, # jinja2 templates are not always parsable as something else {"text/jinja2": "**/*.j2.*"}, - {"text": "**/templates/**/*.*"}, # templates are likely not validable + {"text": "**/templates/**/*.*"}, # templates will likely not validate {"text/json": "**/*.json"}, # standardized {"text/markdown": "**/*.md"}, # https://tools.ietf.org/html/rfc7763 {"text/rst": "**/*.rst"}, # https://en.wikipedia.org/wiki/ReStructuredText diff --git a/src/ansiblelint/rules/__init__.py b/src/ansiblelint/rules/__init__.py index bc68d1ce76..b25b96f0ec 100644 --- a/src/ansiblelint/rules/__init__.py +++ b/src/ansiblelint/rules/__init__.py @@ -40,11 +40,11 @@ match_types = { "matchlines": "line", "match": "line", # called by matchlines - "matchtasks": "task", - "matchtask": "task", # called by matchtasks - "matchyaml": "yaml", - "matchplay": "play", # called by matchyaml - "matchdir": "dir", + "match_tasks": "task", + "match_task": "task", # called by match_tasks + "match_file": "yaml", + "matchplay": "play", # called by match_file + "match_dir": "dir", } RE_JINJA_EXPRESSION = re.compile(r"{{.+?}}") RE_JINJA_STATEMENT = re.compile(r"{%.+?%}") @@ -72,7 +72,7 @@ def unjinja(text: str) -> str: return text # pylint: disable=too-many-arguments,too-many-positional-arguments - def create_matcherror( + def create_match_error( self, message: str = "", lineno: int = 1, @@ -143,20 +143,20 @@ def matchlines(self, file: Lintable) -> list[MatchError]: message = "" if isinstance(result, str): message = result - matcherror = self.create_matcherror( + match_error = self.create_match_error( message=message, lineno=prev_line_no + 1, details=line, filename=file, ) - matches.append(matcherror) + matches.append(match_error) return matches - def matchtasks(self, file: Lintable) -> list[MatchError]: - """Call matchtask for each task inside file and return aggregate results. + def match_tasks(self, file: Lintable) -> list[MatchError]: + """Call match_task for each task inside file and return aggregate results. - Most rules will never need to override matchtasks because its main - purpose is to call matchtask for each task/handlers in the same file, + Most rules will never need to override match_tasks because its main + purpose is to call match_task for each task/handlers in the same file, and to aggregate the results. """ matches: list[MatchError] = [] @@ -185,7 +185,7 @@ def matchtasks(self, file: Lintable) -> list[MatchError]: if self.needs_raw_task: task.normalized_task["__raw_task__"] = task.raw_task - result = self.matchtask(task, file=file) + result = self.match_task(task, file=file) if not result: continue @@ -212,7 +212,7 @@ def matchtasks(self, file: Lintable) -> list[MatchError]: message = "" if isinstance(result, str): message = result - match = self.create_matcherror( + match = self.create_match_error( message=message, lineno=task.line, filename=file, @@ -222,7 +222,7 @@ def matchtasks(self, file: Lintable) -> list[MatchError]: matches.append(match) return matches - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: matches: list[MatchError] = [] if str(file.base_kind) != "text/yaml": return matches diff --git a/src/ansiblelint/rules/args.py b/src/ansiblelint/rules/args.py index f412314e96..e62cd65b5a 100644 --- a/src/ansiblelint/rules/args.py +++ b/src/ansiblelint/rules/args.py @@ -99,7 +99,7 @@ class ArgsRule(AnsibleLintRule): RE_PATTERN = re.compile(r"(argument|option) '(?P.*)' is of type") RE_VALUE_OF = re.compile(r"value of (?P.*) must be one of:") - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -142,7 +142,7 @@ def matchtask( module_args.update(workarounds_inject_map[loaded_module.resolved_fqcn]) if loaded_module.resolved_fqcn in workarounds_mutex_args_map: results.extend( - self.create_matcherror( + self.create_match_error( message=f"Module arguments {mutex_set} are mutually exclusive", lineno=task.line, tag="args[module]", @@ -284,7 +284,7 @@ def _parse_failed_msg( return results results.append( - self.create_matcherror( + self.create_match_error( message=error_message, lineno=task.line, tag="args[module]", diff --git a/src/ansiblelint/rules/avoid_implicit.py b/src/ansiblelint/rules/avoid_implicit.py index 050385ec5e..4a8866ee99 100644 --- a/src/ansiblelint/rules/avoid_implicit.py +++ b/src/ansiblelint/rules/avoid_implicit.py @@ -26,7 +26,7 @@ class AvoidImplicitRule(AnsibleLintRule): tags = ["unpredictability"] version_changed = "6.8.0" - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/command_instead_of_module.py b/src/ansiblelint/rules/command_instead_of_module.py index af6cda3c05..7cddf75649 100644 --- a/src/ansiblelint/rules/command_instead_of_module.py +++ b/src/ansiblelint/rules/command_instead_of_module.py @@ -84,7 +84,7 @@ class CommandsInsteadOfModulesRule(AnsibleLintRule): "rpm": ["--nodeps"], } - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/command_instead_of_shell.py b/src/ansiblelint/rules/command_instead_of_shell.py index 67db8492b4..f2698fd52a 100644 --- a/src/ansiblelint/rules/command_instead_of_shell.py +++ b/src/ansiblelint/rules/command_instead_of_shell.py @@ -48,7 +48,7 @@ class UseCommandInsteadOfShellRule(AnsibleLintRule, TransformMixin): tags = ["command-shell", "idiom"] version_changed = "6.18.0" - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/complexity.py b/src/ansiblelint/rules/complexity.py index 820beccef8..56d2228f4c 100644 --- a/src/ansiblelint/rules/complexity.py +++ b/src/ansiblelint/rules/complexity.py @@ -37,7 +37,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: raise TypeError(msg) if len(tasks) > self._collection.options.max_tasks: results.append( - self.create_matcherror( + self.create_match_error( message=f"Maximum tasks allowed in a play is {self._collection.options.max_tasks}.", tag=f"{self.id}[play]", filename=file, @@ -46,7 +46,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: ) return results - def matchtask(self, task: Task, file: Lintable | None = None) -> list[MatchError]: + def match_task(self, task: Task, file: Lintable | None = None) -> list[MatchError]: """Check if the task is a block and count the number of items inside it.""" results: list[MatchError] = [] @@ -58,7 +58,7 @@ def matchtask(self, task: Task, file: Lintable | None = None) -> list[MatchError block_depth = self.calculate_block_depth(task) if block_depth > self._collection.options.max_block_depth: results.append( - self.create_matcherror( + self.create_match_error( message=f"Replace nested block with an include_tasks to make code easier to maintain. Maximum block depth allowed is {self._collection.options.max_block_depth}.", lineno=task.line, tag=f"{self.id}[nesting]", diff --git a/src/ansiblelint/rules/deprecated_bare_vars.py b/src/ansiblelint/rules/deprecated_bare_vars.py index 66f6fe0799..fa3676729a 100644 --- a/src/ansiblelint/rules/deprecated_bare_vars.py +++ b/src/ansiblelint/rules/deprecated_bare_vars.py @@ -49,7 +49,7 @@ class UsingBareVariablesIsDeprecatedRule(AnsibleLintRule): tags = ["deprecations"] version_changed = "6.19.0" - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/deprecated_local_action.py b/src/ansiblelint/rules/deprecated_local_action.py index bf2e3570d7..6e001b1903 100644 --- a/src/ansiblelint/rules/deprecated_local_action.py +++ b/src/ansiblelint/rules/deprecated_local_action.py @@ -37,7 +37,7 @@ class TaskNoLocalActionRule(AnsibleLintRule, TransformMixin): tags = ["deprecations"] version_changed = "4.0.0" - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/deprecated_module.py b/src/ansiblelint/rules/deprecated_module.py index 3de6a4bc97..5a73cad885 100644 --- a/src/ansiblelint/rules/deprecated_module.py +++ b/src/ansiblelint/rules/deprecated_module.py @@ -68,7 +68,7 @@ class DeprecatedModuleRule(AnsibleLintRule): "include", ] - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/empty_string_compare.py b/src/ansiblelint/rules/empty_string_compare.py index 58e76a3f22..79f2514545 100644 --- a/src/ansiblelint/rules/empty_string_compare.py +++ b/src/ansiblelint/rules/empty_string_compare.py @@ -31,7 +31,7 @@ class ComparisonToEmptyStringRule(AnsibleLintRule): empty_string_compare = re.compile(r"[=!]= ?(\"{2}|'{2})") - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/fqcn.py b/src/ansiblelint/rules/fqcn.py index 8fe63031cc..0bccd5f500 100644 --- a/src/ansiblelint/rules/fqcn.py +++ b/src/ansiblelint/rules/fqcn.py @@ -110,7 +110,7 @@ class FQCNBuiltinsRule(AnsibleLintRule, TransformMixin): "fqcn[canonical]": "You should use canonical module name", } - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -154,7 +154,7 @@ def matchtask( message = f"Use FQCN for builtin module actions ({module})." details = f"Use `{module_alias}` or `{legacy_module}` instead." result.append( - self.create_matcherror( + self.create_match_error( message=message, details=details, filename=file, @@ -164,7 +164,7 @@ def matchtask( ) elif module.count(".") < 2: result.append( - self.create_matcherror( + self.create_match_error( message=f"Use FQCN for module actions, such `{self.module_aliases[module]}`.", details=f"Action `{module}` is not FQCN.", filename=file, @@ -179,7 +179,7 @@ def matchtask( "community.network.", ): result.append( - self.create_matcherror( + self.create_match_error( message=f"You should use canonical module name `{self.module_aliases[module]}` instead of `{module}`.", filename=file, data=module, @@ -188,7 +188,7 @@ def matchtask( ) return result - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: """Return matches found for a specific YAML text.""" result = [] if file.kind == "plugin": @@ -197,7 +197,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: short_path = file.path.resolve().parts[i + 2 :] if len(short_path) > 1 and "test" not in str(file.path): result.append( - self.create_matcherror( + self.create_match_error( message=f"Deep plugins directory is discouraged. Move '{file.path}' directly under '{'/'.join(plugin_type)}' folder.", tag="fqcn[deep]", filename=file, @@ -216,7 +216,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: return [] if "collections" in data: return [ - self.create_matcherror( + self.create_match_error( message="Avoid `collections` keyword by using FQCN for all plugins, modules, roles and playbooks.", data=data, tag="fqcn[keyword]", diff --git a/src/ansiblelint/rules/galaxy.py b/src/ansiblelint/rules/galaxy.py index 0d1c775e85..2c2aafef31 100644 --- a/src/ansiblelint/rules/galaxy.py +++ b/src/ansiblelint/rules/galaxy.py @@ -89,7 +89,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: and len(str(ver).strip()) == 0 ): results.append( - self.create_matcherror( + self.create_match_error( message=f"Invalid collection metadata. Dependency version spec range is invalid for '{dep}'.", tag="galaxy[invalid-dependency-version]", filename=file, @@ -100,7 +100,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: # for a nonexistent file if not changelog_found: results.append( - self.create_matcherror( + self.create_match_error( message="No changelog found. Please add a changelog file. Refer to the galaxy.md file for more info.", tag="galaxy[no-changelog]", filename=file, @@ -112,7 +112,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: tag in required_tag_list for tag in galaxy_tag_list ): results.append( - self.create_matcherror( + self.create_match_error( message=( f"galaxy.yaml must have one of the required tags: {required_tag_list}" ), @@ -124,7 +124,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: # Checking if galaxy.yml tags are formatted correctly if galaxy_tag_invalid_format: results.append( - self.create_matcherror( + self.create_match_error( message=( f"galaxy.yaml must have properly formatted tags. Invalid tags: {','.join(galaxy_tag_invalid_format)}" ), @@ -136,7 +136,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: # Checking if galaxy.yml tags length are within limits if galaxy_tag_invalid_length: results.append( - self.create_matcherror( + self.create_match_error( message=( f"galaxy.yaml tags must not exceed {MAX_LENGTH_TAG} characters. Invalid tags: {','.join(galaxy_tag_invalid_length)}" ), @@ -148,7 +148,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: # Checking if galaxy.yml tags does not exceed the max number if len(galaxy_tag_list) > MAX_TAGS_COUNT: results.append( - self.create_matcherror( + self.create_match_error( message=( f"galaxy.yaml exceeds {MAX_TAGS_COUNT} tags. Current count: {len(galaxy_tag_list)}" ), @@ -159,7 +159,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: if "version" not in data: results.append( - self.create_matcherror( + self.create_match_error( message="galaxy.yaml should have version tag.", data=data, tag="galaxy[version-missing]", @@ -172,7 +172,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: if not (base_path / "meta" / "runtime.yml").is_file(): results.append( - self.create_matcherror( + self.create_match_error( message="meta/runtime.yml file not found.", tag="galaxy[no-runtime]", filename=file, diff --git a/src/ansiblelint/rules/galaxy_version_incorrect.py b/src/ansiblelint/rules/galaxy_version_incorrect.py index 27af6ef524..8d079c349b 100644 --- a/src/ansiblelint/rules/galaxy_version_incorrect.py +++ b/src/ansiblelint/rules/galaxy_version_incorrect.py @@ -31,7 +31,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: version = data.get("version") if not version or Version(version) < Version("1.0.0"): results.append( - self.create_matcherror( + self.create_match_error( message="collection version should be greater than or equal to 1.0.0", data=version, filename=file, diff --git a/src/ansiblelint/rules/ignore_errors.py b/src/ansiblelint/rules/ignore_errors.py index 0014c2ec6c..ab29318f8c 100644 --- a/src/ansiblelint/rules/ignore_errors.py +++ b/src/ansiblelint/rules/ignore_errors.py @@ -26,7 +26,7 @@ class IgnoreErrorsRule(AnsibleLintRule): tags = ["unpredictability"] version_changed = "5.0.7" - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/inline_env_var.py b/src/ansiblelint/rules/inline_env_var.py index 6cc6643600..30d4b16bfa 100644 --- a/src/ansiblelint/rules/inline_env_var.py +++ b/src/ansiblelint/rules/inline_env_var.py @@ -61,7 +61,7 @@ class EnvVarsInCommandRule(AnsibleLintRule): FILENAME_KEY, ] - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/jinja.py b/src/ansiblelint/rules/jinja.py index 99751545cb..2d76ab68a0 100644 --- a/src/ansiblelint/rules/jinja.py +++ b/src/ansiblelint/rules/jinja.py @@ -125,7 +125,7 @@ def _msg(self, tag: str, value: str, reformatted: str) -> str: return self._tag2msg[tag].format(value=value, reformatted=reformatted) # pylint: disable=too-many-locals - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -217,7 +217,7 @@ def matchtask( if not bypass: lineno = task.get_error_line([*path, key]) result.append( - self.create_matcherror( + self.create_match_error( message=str(exc), lineno=lineno, data=v, @@ -234,7 +234,7 @@ def matchtask( if reformatted != v: lineno = task.get_error_line([*path, key]) result.append( - self.create_matcherror( + self.create_match_error( message=self._msg( tag=tag, value=v, @@ -254,11 +254,11 @@ def matchtask( ), ) except Exception as exc: - _logger.info("Exception in JinjaRule.matchtask: %s", exc) + _logger.info("Exception in JinjaRule.match_task: %s", exc) raise return result - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: """Return matches for variables defined in vars files.""" raw_results: list[MatchError] = [] results: list[MatchError] = [] @@ -276,7 +276,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: ) if reformatted != v: results.append( - self.create_matcherror( + self.create_match_error( message=self._msg( tag=tag, value=v, @@ -299,7 +299,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: if match.rule.id not in skip_list and match.tag not in skip_list: results.append(match) else: - results.extend(super().matchyaml(file)) + results.extend(super().match_file(file)) return results def lex(self, text: str) -> list[Token]: @@ -358,7 +358,7 @@ def cook(value: str, *, implicit: bool = False) -> str: return value return f"{{{{ {value} }}}}" - def uncook(value: str, *, implicit: bool = False) -> str: + def reverse_cook(value: str, *, implicit: bool = False) -> str: """Restore an string to original form when it was an implicit one.""" if not implicit: return value @@ -440,12 +440,12 @@ def uncook(value: str, *, implicit: bool = False) -> str: # newlines, as we decided to not touch them yet. # These both are documented as known limitations. _logger.debug("Ignored jinja internal error %s", exc) - return uncook(text, implicit=implicit), "", "spacing" + return reverse_cook(text, implicit=implicit), "", "spacing" # finalize reformatted = self.unlex(tokens) failed = reformatted != text - reformatted = uncook(reformatted, implicit=implicit) + reformatted = reverse_cook(reformatted, implicit=implicit) details = ( f"Jinja2 template rewrite recommendation: `{reformatted}`." if failed diff --git a/src/ansiblelint/rules/key_order.py b/src/ansiblelint/rules/key_order.py index 965496b7dc..7261928afb 100644 --- a/src/ansiblelint/rules/key_order.py +++ b/src/ansiblelint/rules/key_order.py @@ -86,7 +86,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: sorted_keys = sorted(keys, key=functools.cmp_to_key(task_property_sorter)) if keys != sorted_keys: result.append( - self.create_matcherror( + self.create_match_error( f"You can improve the play key order to: {', '.join(sorted_keys)}", filename=file, tag=f"{self.id}[play]", @@ -96,7 +96,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: ) return result - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -107,7 +107,7 @@ def matchtask( sorted_keys = sorted(keys, key=functools.cmp_to_key(task_property_sorter)) if keys != sorted_keys: result.append( - self.create_matcherror( + self.create_match_error( f"You can improve the task key order to: {', '.join(sorted_keys)}", filename=file, tag="key-order[task]", diff --git a/src/ansiblelint/rules/latest.py b/src/ansiblelint/rules/latest.py index ccf7339098..9d9bd673ff 100644 --- a/src/ansiblelint/rules/latest.py +++ b/src/ansiblelint/rules/latest.py @@ -28,7 +28,7 @@ class LatestRule(AnsibleLintRule): "latest[hg]": "Use a commit hash or tag instead of 'latest' for hg", } - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -38,10 +38,10 @@ def matchtask( task["action"]["__ansible_module__"] == "git" and task["action"].get("version", "HEAD") == "HEAD" ): - return self.create_matcherror(tag="latest[git]", filename=file) + return self.create_match_error(tag="latest[git]", filename=file) if ( task["action"]["__ansible_module__"] == "hg" and task["action"].get("revision", "default") == "default" ): # pragma: no cover - return self.create_matcherror(tag="latest[hg]", filename=file) + return self.create_match_error(tag="latest[hg]", filename=file) return False diff --git a/src/ansiblelint/rules/literal_compare.py b/src/ansiblelint/rules/literal_compare.py index f0a3a072f7..43da59a44b 100644 --- a/src/ansiblelint/rules/literal_compare.py +++ b/src/ansiblelint/rules/literal_compare.py @@ -31,7 +31,7 @@ class ComparisonToLiteralBoolRule(AnsibleLintRule): literal_bool_compare = re.compile(r"[=!]= ?(True|true|False|false)") - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/loop_var_prefix.py b/src/ansiblelint/rules/loop_var_prefix.py index 729ba9b0a2..6313631d4a 100644 --- a/src/ansiblelint/rules/loop_var_prefix.py +++ b/src/ansiblelint/rules/loop_var_prefix.py @@ -37,7 +37,7 @@ class RoleLoopVarPrefix(AnsibleLintRule): } version_changed = "6.7.0" - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -67,7 +67,7 @@ def matchtask( if loop_var: if not self.prefix.match(loop_var): return [ - self.create_matcherror( + self.create_match_error( message=f"Loop variable name does not match /{options.loop_var_prefix}/ regex, where role={toidentifier(file.role)}.", filename=file, data=loop_var, @@ -76,7 +76,7 @@ def matchtask( ] else: return [ - self.create_matcherror( + self.create_match_error( message=f"Replace unsafe implicit `item` loop variable by adding a `loop_var` that is matching /{options.loop_var_prefix}/ regex.", filename=file, data=data, diff --git a/src/ansiblelint/rules/meta_incorrect.py b/src/ansiblelint/rules/meta_incorrect.py index 511c27d9d4..95d5609431 100644 --- a/src/ansiblelint/rules/meta_incorrect.py +++ b/src/ansiblelint/rules/meta_incorrect.py @@ -32,7 +32,7 @@ class MetaChangeFromDefaultRule(AnsibleLintRule): tags = ["metadata"] version_changed = "4.0.0" - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: if file.kind != "meta" or not file.data: return [] @@ -45,7 +45,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: value = galaxy_info.get(field, None) if value and value == default: results.append( - self.create_matcherror( + self.create_match_error( filename=file, message=f"Should change default metadata: {field}", data=file.data, diff --git a/src/ansiblelint/rules/meta_no_tags.py b/src/ansiblelint/rules/meta_no_tags.py index d25c0ffe4f..55b8cc57ac 100644 --- a/src/ansiblelint/rules/meta_no_tags.py +++ b/src/ansiblelint/rules/meta_no_tags.py @@ -34,7 +34,7 @@ class MetaTagValidRule(AnsibleLintRule): TAG_REGEXP = re.compile(r"^[a-z0-9]+$") - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: """Find violations inside meta files.""" if file.kind != "meta" or not file.data: return [] @@ -51,7 +51,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: tags += galaxy_info["galaxy_tags"] else: results.append( - self.create_matcherror( + self.create_match_error( "Expected 'galaxy_tags' to be a list", filename=file, ), @@ -59,7 +59,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: if "categories" in galaxy_info: results.append( - self.create_matcherror( + self.create_match_error( "Use 'galaxy_tags' rather than 'categories'", filename=file, ), @@ -68,7 +68,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: tags += galaxy_info["categories"] else: results.append( - self.create_matcherror( + self.create_match_error( "Expected 'categories' to be a list", filename=file, ), @@ -78,7 +78,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: msg = self.shortdesc if not isinstance(tag, str): results.append( - self.create_matcherror( + self.create_match_error( f"Tags must be strings: '{tag}'", filename=file, ), @@ -86,7 +86,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: continue if not re.match(self.TAG_REGEXP, tag): results.append( - self.create_matcherror( + self.create_match_error( message=f"{msg}, invalid: '{tag}'", filename=file, ), diff --git a/src/ansiblelint/rules/meta_runtime.py b/src/ansiblelint/rules/meta_runtime.py index d5e1dc2fc4..e37a94fec7 100644 --- a/src/ansiblelint/rules/meta_runtime.py +++ b/src/ansiblelint/rules/meta_runtime.py @@ -35,7 +35,7 @@ class CheckRequiresAnsibleVersion(AnsibleLintRule): "meta-runtime[invalid-version]": "'requires_ansible' is not a valid requirement specification", } - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: """Find violations inside meta files. :param file: Input lintable file that is a match for `meta-runtime` @@ -59,7 +59,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: msg = f"'requires_ansible' key must refer to a currently supported version such as: {', '.join(supported_ansible)}" results.append( - self.create_matcherror( + self.create_match_error( message=msg, tag="meta-runtime[unsupported-version]", filename=file, @@ -70,7 +70,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: SpecifierSet(requires_ansible) except ValueError: results.append( - self.create_matcherror( + self.create_match_error( message="'requires_ansible' is not a valid requirement specification", tag="meta-runtime[invalid-version]", filename=file, diff --git a/src/ansiblelint/rules/meta_video_links.py b/src/ansiblelint/rules/meta_video_links.py index 37f305576c..3171a96b43 100644 --- a/src/ansiblelint/rules/meta_video_links.py +++ b/src/ansiblelint/rules/meta_video_links.py @@ -36,7 +36,7 @@ class MetaVideoLinksRule(AnsibleLintRule): "youtube": re.compile(r"https://youtu\.be/([0-9A-Za-z-_]+)"), } - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: if file.kind != "meta" or not file.data: return [] @@ -53,7 +53,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: for video in video_links: if not isinstance(video, dict): results.append( - self.create_matcherror( + self.create_match_error( "Expected item in 'video_links' to be a dictionary", filename=file, data=video, @@ -69,7 +69,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: } if unexpected_keys: results.append( - self.create_matcherror( + self.create_match_error( "Expected item in 'video_links' to contain " "only keys 'url' and 'title'", filename=file, @@ -88,7 +88,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: "or Google Drive." ) results.append( - self.create_matcherror(msg, filename=file, data=video["url"]) + self.create_match_error(msg, filename=file, data=video["url"]) ) return results diff --git a/src/ansiblelint/rules/name.py b/src/ansiblelint/rules/name.py index cc3b1d6877..cc99e1dea6 100644 --- a/src/ansiblelint/rules/name.py +++ b/src/ansiblelint/rules/name.py @@ -69,7 +69,7 @@ def _check_unique_task_names( if task_name in seen_names: message = f"Task name '{task_name}' is not unique. It was first used on line {seen_names[task_name]}." errors.append( - self.create_matcherror( + self.create_match_error( message=message, lineno=lineno, filename=file, @@ -91,7 +91,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: # Check if the play itself is named if "name" not in data: return [ - self.create_matcherror( + self.create_match_error( message="All plays should be named.", tag="name[play]", filename=file, @@ -118,7 +118,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: return results - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -130,7 +130,7 @@ def matchtask( name = task.get("name") if not name: results.append( - self.create_matcherror( + self.create_match_error( message="All tasks should be named.", lineno=task.line, tag="name[missing]", @@ -194,7 +194,7 @@ def _check_name( # having to enable the rule. if "name[prefix]" in self._collection.options.enable_list: results.append( - self.create_matcherror( + self.create_match_error( message=f"Task name should start with '{prefix}'.", data=data, tag="name[prefix]", @@ -212,7 +212,7 @@ def _check_name( and not effective_name[0].isupper() ): results.append( - self.create_matcherror( + self.create_match_error( message="All names should start with an uppercase letter.", data=name, tag="name[casing]", @@ -221,7 +221,7 @@ def _check_name( ) if self._re_templated_inside.match(name): results.append( - self.create_matcherror( + self.create_match_error( message="Jinja templates should only be at the end of 'name'", data=name, tag="name[template]", diff --git a/src/ansiblelint/rules/no_changed_when.py b/src/ansiblelint/rules/no_changed_when.py index d27ec67ab3..c3fbd8fb51 100644 --- a/src/ansiblelint/rules/no_changed_when.py +++ b/src/ansiblelint/rules/no_changed_when.py @@ -53,7 +53,7 @@ class CommandHasChangesCheckRule(AnsibleLintRule): "raw", ] - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -69,7 +69,7 @@ def matchtask( and "removes" not in task["action"] ) ): - result.append(self.create_matcherror(filename=file)) + result.append(self.create_match_error(filename=file)) return result diff --git a/src/ansiblelint/rules/no_free_form.py b/src/ansiblelint/rules/no_free_form.py index 5899a83391..d015ff604f 100644 --- a/src/ansiblelint/rules/no_free_form.py +++ b/src/ansiblelint/rules/no_free_form.py @@ -38,7 +38,7 @@ class NoFreeFormRule(AnsibleLintRule, TransformMixin): "no-free-form[raw-non-string]": "Passing a non string value to `raw` module is neither documented or supported.", } - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -54,7 +54,7 @@ def matchtask( if isinstance(action_value, str): if "executable=" in action_value: results.append( - self.create_matcherror( + self.create_match_error( message="Avoid embedding `executable=` inside raw calls, use explicit args dictionary instead.", lineno=task.line, filename=file, @@ -63,7 +63,7 @@ def matchtask( ) else: results.append( - self.create_matcherror( + self.create_match_error( message="Passing a non string value to `raw` module is neither documented or supported.", lineno=task.line, filename=file, @@ -88,7 +88,7 @@ def matchtask( fail = True if fail: results.append( - self.create_matcherror( + self.create_match_error( message=f"Avoid using free-form when calling module actions. ({action})", lineno=task.line, filename=file, diff --git a/src/ansiblelint/rules/no_handler.py b/src/ansiblelint/rules/no_handler.py index 49be72ff9a..87b8c1590f 100644 --- a/src/ansiblelint/rules/no_handler.py +++ b/src/ansiblelint/rules/no_handler.py @@ -67,7 +67,7 @@ class UseHandlerRatherThanWhenChangedRule(AnsibleLintRule): tags = ["idiom"] version_changed = "24.10.0" - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -85,7 +85,7 @@ def matchtask( and _changed_in_when(when[0]) ): result.append( - self.create_matcherror( + self.create_match_error( message=self.shortdesc, data=when, filename=file, diff --git a/src/ansiblelint/rules/no_jinja_when.py b/src/ansiblelint/rules/no_jinja_when.py index 02149ec3b2..f9d5f5e439 100644 --- a/src/ansiblelint/rules/no_jinja_when.py +++ b/src/ansiblelint/rules/no_jinja_when.py @@ -51,7 +51,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: if "roles" not in data or data["roles"] is None: return errors errors = [ - self.create_matcherror( + self.create_match_error( details=str({"when": role}), filename=file, data=role, @@ -65,7 +65,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: ] return errors - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/no_log_password.py b/src/ansiblelint/rules/no_log_password.py index 3ce7c29069..e63fb4136a 100644 --- a/src/ansiblelint/rules/no_log_password.py +++ b/src/ansiblelint/rules/no_log_password.py @@ -46,7 +46,7 @@ class NoLogPasswordsRule(AnsibleLintRule, TransformMixin): tags = ["opt-in", "security", "experimental"] version_changed = "5.0.9" - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/no_prompting.py b/src/ansiblelint/rules/no_prompting.py index a67daaed99..65ff6040de 100644 --- a/src/ansiblelint/rules/no_prompting.py +++ b/src/ansiblelint/rules/no_prompting.py @@ -37,14 +37,14 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: if not vars_prompt: return [] return [ - self.create_matcherror( + self.create_match_error( message="Play uses vars_prompt", data=vars_prompt[0], filename=file, ), ] - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/no_relative_paths.py b/src/ansiblelint/rules/no_relative_paths.py index d734037784..ef9630d7b9 100644 --- a/src/ansiblelint/rules/no_relative_paths.py +++ b/src/ansiblelint/rules/no_relative_paths.py @@ -31,7 +31,7 @@ class RoleRelativePath(AnsibleLintRule): "win_template": "win_templates", } - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/no_same_owner.py b/src/ansiblelint/rules/no_same_owner.py index 2330a94185..f1a119280e 100644 --- a/src/ansiblelint/rules/no_same_owner.py +++ b/src/ansiblelint/rules/no_same_owner.py @@ -29,7 +29,7 @@ class NoSameOwnerRule(AnsibleLintRule): version_changed = "6.4.0" RE_ARCHIVES = re.compile(r"^.*\.tar(\.(gz|bz2|xz))?$") - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/no_tabs.py b/src/ansiblelint/rules/no_tabs.py index bbb3469d37..f3877d51f9 100644 --- a/src/ansiblelint/rules/no_tabs.py +++ b/src/ansiblelint/rules/no_tabs.py @@ -48,7 +48,7 @@ class NoTabsRule(AnsibleLintRule): ("community.windows.win_lineinfile", "line"), ] - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -58,7 +58,7 @@ def matchtask( for k, v, _ in nested_items_path(task): if isinstance(k, str) and "\t" in k and not has_jinja(k): result.append( - self.create_matcherror( + self.create_match_error( message=self.shortdesc, data=k, filename=file, @@ -71,7 +71,7 @@ def matchtask( and not has_jinja(v) ): result.append( - self.create_matcherror( + self.create_match_error( message=self.shortdesc, data=v, filename=file, diff --git a/src/ansiblelint/rules/only_builtins.py b/src/ansiblelint/rules/only_builtins.py index d31e41bd47..5e42fb03e3 100644 --- a/src/ansiblelint/rules/only_builtins.py +++ b/src/ansiblelint/rules/only_builtins.py @@ -24,7 +24,7 @@ class OnlyBuiltinsRule(AnsibleLintRule): tags = ["opt-in", "experimental"] version_changed = "6.14.0" - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/package_latest.py b/src/ansiblelint/rules/package_latest.py index 9ae27b12a7..b83091ae68 100644 --- a/src/ansiblelint/rules/package_latest.py +++ b/src/ansiblelint/rules/package_latest.py @@ -71,7 +71,7 @@ class PackageIsNotLatestRule(AnsibleLintRule): "zypper", ] - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/partial_become.py b/src/ansiblelint/rules/partial_become.py index 42d5a4a356..336a7ce4ed 100644 --- a/src/ansiblelint/rules/partial_become.py +++ b/src/ansiblelint/rules/partial_become.py @@ -61,7 +61,7 @@ def matchplay( errors = [] partial = "become_user" in data and "become" not in data if partial: - error = self.create_matcherror( + error = self.create_match_error( message=self.shortdesc, filename=file, tag=f"{self.id}[play]", @@ -70,7 +70,7 @@ def matchplay( errors.append(error) return errors - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -85,7 +85,7 @@ def matchtask( errors = [] partial = "become_user" in data and "become" not in data if partial: - error = self.create_matcherror( + error = self.create_match_error( message=self.shortdesc, filename=file, tag=f"{self.id}[task]", diff --git a/src/ansiblelint/rules/playbook_extension.py b/src/ansiblelint/rules/playbook_extension.py index 20a4dae9ba..b281ae5227 100644 --- a/src/ansiblelint/rules/playbook_extension.py +++ b/src/ansiblelint/rules/playbook_extension.py @@ -25,7 +25,7 @@ class PlaybookExtensionRule(AnsibleLintRule): done: list[str] = [] version_changed = "4.0.0" - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: result: list[MatchError] = [] if file.kind != "playbook": return result @@ -33,7 +33,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: ext = file.path.suffix if ext not in [".yml", ".yaml"] and path not in self.done: self.done.append(path) - result.append(self.create_matcherror(filename=file)) + result.append(self.create_match_error(filename=file)) return result diff --git a/src/ansiblelint/rules/risky_file_permissions.py b/src/ansiblelint/rules/risky_file_permissions.py index 078986ff45..4134992543 100644 --- a/src/ansiblelint/rules/risky_file_permissions.py +++ b/src/ansiblelint/rules/risky_file_permissions.py @@ -88,7 +88,7 @@ class MissingFilePermissionsRule(AnsibleLintRule): _modules_with_create = _MODULES_WITH_CREATE # pylint: disable=too-many-return-statements - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/risky_octal.py b/src/ansiblelint/rules/risky_octal.py index da2b7c6bca..ec160a7c62 100644 --- a/src/ansiblelint/rules/risky_octal.py +++ b/src/ansiblelint/rules/risky_octal.py @@ -92,7 +92,7 @@ def is_invalid_permission(mode: int) -> bool: or group_more_generous_than_user, ) - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/src/ansiblelint/rules/risky_shell_pipe.py b/src/ansiblelint/rules/risky_shell_pipe.py index daf8becce5..365c8af4d9 100644 --- a/src/ansiblelint/rules/risky_shell_pipe.py +++ b/src/ansiblelint/rules/risky_shell_pipe.py @@ -33,7 +33,7 @@ class ShellWithoutPipefail(AnsibleLintRule): _pipefail_re = re.compile(r"^\s*set.*[+-][A-Za-z]*o\s*pipefail", re.MULTILINE) _pipe_re = re.compile(r"(? list[MatchError]: - return self.matchyaml(lintable) + def match_dir(self, lintable: Lintable) -> list[MatchError]: + return self.match_file(lintable) - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: result: list[MatchError] = [] column: int | None = None @@ -108,7 +108,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: raise TypeError(msg) if "/" in role_name: result.append( - self.create_matcherror( + self.create_match_error( f"Avoid using paths when importing roles. ({role_name})", filename=file, data=role_name, @@ -133,7 +133,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: raise TypeError(msg) if "/" in role_name: result.append( - self.create_matcherror( + self.create_match_error( f"Avoid using paths when importing roles. ({role_name})", filename=file, lineno=line, @@ -157,7 +157,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: role_name = _remove_prefix(role_name, "ansible-role-") if role_name and not _match_role_name_regex(role_name): result.append( - self.create_matcherror( + self.create_match_error( filename=file, message=self.shortdesc.format(role_name), ), diff --git a/src/ansiblelint/rules/run_once.py b/src/ansiblelint/rules/run_once.py index b5913a34e5..d35eba0a2d 100644 --- a/src/ansiblelint/rules/run_once.py +++ b/src/ansiblelint/rules/run_once.py @@ -41,7 +41,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: return [] lineno = getattr(strategy, "_line_number", 1) return [ - self.create_matcherror( + self.create_match_error( message="Play uses strategy: free", filename=file, tag=f"{self.id}[play]", @@ -49,7 +49,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: ), ] - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -62,7 +62,7 @@ def matchtask( if not run_once: return [] return [ - self.create_matcherror( + self.create_match_error( message="Using run_once may behave differently if strategy is set to free.", filename=file, tag=f"{self.id}[task]", diff --git a/src/ansiblelint/rules/sanity.py b/src/ansiblelint/rules/sanity.py index fa32a1e01f..9282d0c555 100644 --- a/src/ansiblelint/rules/sanity.py +++ b/src/ansiblelint/rules/sanity.py @@ -61,7 +61,7 @@ class CheckSanityIgnoreFiles(AnsibleLintRule): "sanity[bad-ignore]": "Ignore file entry at ... is formatted incorrectly. Please review.", } - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: """Evaluate sanity ignore lists for disallowed ignores. :param file: Input lintable file that is a match for `sanity-ignore-file` @@ -101,7 +101,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: (_, test) = entry.split() if test not in self.allowed_ignores: results.append( - self.create_matcherror( + self.create_match_error( message=f"Ignore file contains {test} at line {line_num}, which is not a permitted ignore.", tag="sanity[cannot-ignore]", lineno=line_num, @@ -111,7 +111,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: except ValueError: results.append( - self.create_matcherror( + self.create_match_error( message=f"Ignore file entry at {line_num} is formatted incorrectly. Please review.", tag="sanity[bad-ignore]", lineno=line_num, diff --git a/src/ansiblelint/rules/schema.py b/src/ansiblelint/rules/schema.py index e8c1747a55..92fb234dda 100644 --- a/src/ansiblelint/rules/schema.py +++ b/src/ansiblelint/rules/schema.py @@ -125,7 +125,7 @@ def _get_field_matches( if not has_jinja(plugin_value) and plugin_value not in values: msg = f"'{key}' must be one of the currently available values: {', '.join(values)}" results.append( - self.create_matcherror( + self.create_match_error( message=msg, data=plugin_value, filename=file, @@ -135,7 +135,7 @@ def _get_field_matches( ) return results - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -153,7 +153,7 @@ def matchtask( msg = pre_checks["task"][key]["msg"] tag = pre_checks["task"][key]["tag"] results.append( - self.create_matcherror( + self.create_match_error( message=msg, filename=file, details=ValidateSchemaRule.description, @@ -162,7 +162,7 @@ def matchtask( ) return results - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: """Return JSON validation errors found as a list of MatchError(s).""" result: list[MatchError] = [] @@ -181,7 +181,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: return [] result.append( - self.create_matcherror( + self.create_match_error( message=error, filename=file, details=ValidateSchemaRule.description, @@ -191,7 +191,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: break if not result: - result = super().matchyaml(file) + result = super().match_file(file) return result diff --git a/src/ansiblelint/rules/var_naming.py b/src/ansiblelint/rules/var_naming.py index 31ac37a89f..3a8053f1e0 100644 --- a/src/ansiblelint/rules/var_naming.py +++ b/src/ansiblelint/rules/var_naming.py @@ -119,7 +119,7 @@ def get_var_naming_matcherror( ) -> MatchError | None: """Return a MatchError if the variable name is not valid, otherwise None.""" if not isinstance(ident, str): # pragma: no cover - return self.create_matcherror( + return self.create_match_error( tag="var-naming[non-string]", message="Variables names must be strings.", filename=file, @@ -131,7 +131,7 @@ def get_var_naming_matcherror( try: ident.encode("ascii") except UnicodeEncodeError: - return self.create_matcherror( + return self.create_match_error( tag="var-naming[non-ascii]", message=f"Variables names must be ASCII. ({ident})", filename=file, @@ -139,7 +139,7 @@ def get_var_naming_matcherror( ) if keyword.iskeyword(ident): - return self.create_matcherror( + return self.create_match_error( tag="var-naming[no-keyword]", message=f"Variables names must not be Python keywords. ({ident})", filename=file, @@ -147,7 +147,7 @@ def get_var_naming_matcherror( ) if ident in self.reserved_names: - return self.create_matcherror( + return self.create_match_error( tag="var-naming[no-reserved]", message=f"Variables names must not be Ansible reserved names. ({ident})", filename=file, @@ -155,7 +155,7 @@ def get_var_naming_matcherror( ) if ident in self.read_only_names: - return self.create_matcherror( + return self.create_match_error( tag="var-naming[read-only]", message=f"This special variable is read-only. ({ident})", filename=file, @@ -169,7 +169,7 @@ def get_var_naming_matcherror( if not bool(self.re_pattern.match(ident)) and ( not prefix or not prefix.from_fqcn ): - return self.create_matcherror( + return self.create_match_error( tag="var-naming[pattern]", message=f"Variables names should match {self.re_pattern_str} regex. ({ident})", filename=file, @@ -182,7 +182,7 @@ def get_var_naming_matcherror( and not has_jinja(prefix.value) and is_fqcn_or_name(prefix.value) ): - return self.create_matcherror( + return self.create_match_error( tag="var-naming[no-role-prefix]", message=f"Variables names from within roles should use {prefix.value}_ as a prefix.", filename=file, @@ -241,7 +241,7 @@ def matchplay(self, file: Lintable, data: dict[str, Any]) -> list[MatchError]: return results - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, @@ -304,7 +304,7 @@ def matchtask( return results - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: """Return matches for variables defined in vars files.""" results: list[MatchError] = [] raw_results: list[MatchError] = [] @@ -335,7 +335,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: if match.rule.id not in skip_list and match.tag not in skip_list: results.append(match) else: - results.extend(super().matchyaml(file)) + results.extend(super().match_file(file)) return results def _parse_prefix(self, fqcn: str) -> Prefix: diff --git a/src/ansiblelint/rules/yaml_rule.py b/src/ansiblelint/rules/yaml_rule.py index ef161391e4..c5598fb61e 100644 --- a/src/ansiblelint/rules/yaml_rule.py +++ b/src/ansiblelint/rules/yaml_rule.py @@ -60,7 +60,7 @@ class YamllintRule(AnsibleLintRule, TransformMixin): "yaml[truthy]": "", } - def matchyaml(self, file: Lintable) -> list[MatchError]: + def match_file(self, file: Lintable) -> list[MatchError]: """Return matches found for a specific YAML text.""" matches: list[MatchError] = [] if str(file.base_kind) != "text/yaml": @@ -81,7 +81,7 @@ def matchyaml(self, file: Lintable) -> list[MatchError]: ): continue matches.append( - self.create_matcherror( + self.create_match_error( # yamllint does return lower-case sentences message=problem.desc.capitalize(), lineno=problem.line, diff --git a/test/rules/fixtures/raw_task.py b/test/rules/fixtures/raw_task.py index 09fc0b8479..221f520d0c 100644 --- a/test/rules/fixtures/raw_task.py +++ b/test/rules/fixtures/raw_task.py @@ -19,7 +19,7 @@ class RawTaskRule(AnsibleLintRule): tags = ["fake", "dummy", "test3"] needs_raw_task = True - def matchtask( + def match_task( self, task: Task, file: Lintable | None = None, diff --git a/test/test_lint_rule.py b/test/test_lint_rule.py index d0edbe9e58..82cace8adf 100644 --- a/test/test_lint_rule.py +++ b/test/test_lint_rule.py @@ -42,5 +42,5 @@ def test_rule_matching(lintable: Lintable) -> None: def test_raw_rule_matching(lintable: Lintable) -> None: """Test rule.matchlines() on a playbook.""" rule = raw_task.RawTaskRule() - matches = rule.matchtasks(lintable) + matches = rule.match_tasks(lintable) assert len(matches) == 1 From 7f493ff951f20ba418f0e54943453b6f869591a8 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Fri, 27 Jun 2025 08:58:34 +0000 Subject: [PATCH 2/2] chore: auto fixes from pre-commit.com hooks --- .config/dictionary.txt | 113 ----------------------------------------- 1 file changed, 113 deletions(-) diff --git a/.config/dictionary.txt b/.config/dictionary.txt index 576d11f2d2..e69de29bb2 100644 --- a/.config/dictionary.txt +++ b/.config/dictionary.txt @@ -1,113 +0,0 @@ -alertmanager -ansiblelint -apport -audgirka -autohide -blockinfile -bracketsmatchtest -bracketsmatchtestfile -cachier -Chamoulaud -codeclimate -Codeclimate -codespell -deannotate -debconf -dellemc -devel -DEVEL -doas -dzdo -ematcher -ematchtestfile -facter -fakerole -filesspot -firewalld -fontawesome -formetting -fqcn -FQCN -FQCNs -geerlingguy -getmatches -gplv -htmlproofer -indentless -inlinehilite -iscsi -junitxml -kubevirt -lalo -libyaml -LIBYAML -licensedb -lineinfile -Lineinfile -LINEINFILE -lintable -Lintable -lintables -mockings -netcommon -nodeps -NODEPS -nomatchestest -nxos -octals -Octals -parseable -Parseable -pathex -pbrun -pfexec -placefolder -plainexamples -pmrun -pwsh -pymdownx -PYTHONBREAKPOINT -PYTHONIOENCODING -PYTHONPYCACHEPREFIX -redirections -reformatter -releasenotes -representer -Representer -rulebooks -runas -sarif -Sarif -SARIF -Sbarnea -seealso -sesu -simplifiable -slackpkg -Sorin -ssbarnea -sudosu -superfences -supervisorctl -swdepot -switchport -sysvinit -taskshandlers -testinfra -testns -timesyncd -tmpfs -tomlsort -Tsukinowa -tuco -typehints -unjinja -unlex -unskippable -untemplated -virtnet -willthames -workerinput -WSLENV -xdist -yatesr