Skip to content

Commit

Permalink
Add auto-fixing implementation for no-jinja-when rule (#3721)
Browse files Browse the repository at this point in the history
  • Loading branch information
shatakshiiii authored Sep 7, 2023
1 parent fc898ee commit 453269b
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 3 deletions.
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' }}"
38 changes: 36 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,37 @@ 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:
v = re.sub(r"{{ (.*?) }}", r"\1", v)
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):
new_value[index] = re.sub(r"{{ (.*?) }}", r"\1", nested_value)
v[idx][new_key] = new_value
if isinstance(new_value, str):
v[idx][new_key] = re.sub(r"{{ (.*?) }}", r"\1", new_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

0 comments on commit 453269b

Please sign in to comment.