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

Add auto-fixing implementation for no-jinja-when rule #3721

Merged
merged 5 commits into from
Sep 7, 2023
Merged
Show file tree
Hide file tree
Changes from 4 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
Expand Up @@ -71,7 +71,7 @@ jobs:
WSLENV: FORCE_COLOR:PYTEST_REQPASS:TOXENV:GITHUB_STEP_SUMMARY
# Number of expected test passes, safety measure for accidental skip of
# tests. Update value if you add/remove tests.
PYTEST_REQPASS: 820
PYTEST_REQPASS: 821
steps:
- name: Activate WSL1
if: "contains(matrix.shell, 'wsl')"
Expand Down
21 changes: 21 additions & 0 deletions examples/playbooks/transform-no-jinja-when.transformed.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
- name: One
hosts: all
tasks:
- name: Test when with jinja2 # noqa: jinja[spacing]
ansible.builtin.debug:
msg: text
when: "false"

- name: Two
hosts: all
roles:
- role: hello
when: "'1' = '1'"

- name: Three
hosts: all
roles:
- role: hello
when:
- "'1' = '1'"
21 changes: 21 additions & 0 deletions examples/playbooks/transform-no-jinja-when.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
- name: One
hosts: all
tasks:
- name: Test when with jinja2 # noqa: jinja[spacing]
ansible.builtin.debug:
msg: text
when: "{{ false }}"

- name: Two
hosts: all
roles:
- role: hello
when: "{{ '1' = '1' }}"

- name: Three
hosts: all
roles:
- role: hello
when:
- "{{ '1' = '1' }}"
41 changes: 39 additions & 2 deletions src/ansiblelint/rules/no_jinja_when.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,22 @@
"""Implementation of no-jinja-when rule."""
from __future__ import annotations

import re
import sys
from typing import TYPE_CHECKING, Any

from ansiblelint.constants import LINE_NUMBER_KEY
from ansiblelint.rules import AnsibleLintRule
from ansiblelint.rules import AnsibleLintRule, TransformMixin

if TYPE_CHECKING:
from ruamel.yaml.comments import CommentedMap, CommentedSeq

from ansiblelint.errors import MatchError
from ansiblelint.file_utils import Lintable
from ansiblelint.utils import Task


class NoFormattingInWhenRule(AnsibleLintRule):
class NoFormattingInWhenRule(AnsibleLintRule, TransformMixin):
"""No Jinja2 in when."""

id = "no-jinja-when"
Expand Down Expand Up @@ -66,6 +69,40 @@ def matchtask(
) -> bool | str:
return "when" in task.raw_task and not self._is_valid(task.raw_task["when"])

def transform(
self,
match: MatchError,
lintable: Lintable,
data: CommentedMap | CommentedSeq | str,
) -> None:
if match.tag == self.id:
task = self.seek(match.yaml_path, data)
key_to_check = ("when", "changed_when", "failed_when")
for _ in range(len(task)):
k, v = task.popitem(False)
if k == "roles" and isinstance(v, list):
transform_for_roles(v, key_to_check=key_to_check)
elif k in key_to_check:
processed_value = re.sub(r"{{ (.*?) }}", r"\1", v)
shatakshiiii marked this conversation as resolved.
Show resolved Hide resolved
v = processed_value
task[k] = v
match.fixed = True


def transform_for_roles(v: list[Any], key_to_check: tuple[str, ...]) -> None:
"""Additional transform logic in case of roles."""
for idx, new_dict in enumerate(v):
for new_key, new_value in new_dict.items():
if new_key in key_to_check:
if isinstance(new_value, list):
for index, nested_value in enumerate(new_value):
processed_value = re.sub(r"{{ (.*?) }}", r"\1", nested_value)
shatakshiiii marked this conversation as resolved.
Show resolved Hide resolved
new_value[index] = processed_value
v[idx][new_key] = new_value
shatakshiiii marked this conversation as resolved.
Show resolved Hide resolved
if isinstance(new_value, str):
processed_value = re.sub(r"{{ (.*?) }}", r"\1", new_value)
shatakshiiii marked this conversation as resolved.
Show resolved Hide resolved
v[idx][new_key] = processed_value


if "pytest" in sys.modules:
# Tests for no-jinja-when rule.
Expand Down
6 changes: 6 additions & 0 deletions test/test_transformer.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,12 @@ def fixture_runner_result(
True,
id="jinja_spacing",
),
pytest.param(
"examples/playbooks/transform-no-jinja-when.yml",
3,
True,
id="no_jinja_when",
),
pytest.param(
"examples/playbooks/vars/transform_nested_data.yml",
3,
Expand Down