Skip to content

Commit

Permalink
E206: Avoid false positives with multilines
Browse files Browse the repository at this point in the history
- Fix regression caused by recent refactoring or rule on multilines
- Adds tests for preventing future regression
- Makes the error message mention the failure variable so user
  is not confused (reported line is the first of task, not the
  exact location within)
  • Loading branch information
ssbarnea committed Feb 2, 2021
1 parent c2de341 commit b64a8ed
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
11 changes: 11 additions & 0 deletions examples/playbooks/206.yml
Expand Up @@ -35,3 +35,14 @@
- name: JSON inside jinja is valid
debug:
msg: "{{ {'test': {'subtest': variable}} }}"
- name: Avoid false positive on multiline
vars:
cases:
case1: >-
http://example.com/{{
case1 }}
case2: >-
http://example.com/{{
case2 }}
debug:
var: cases
14 changes: 8 additions & 6 deletions src/ansiblelint/rules/VariableHasSpacesRule.py
Expand Up @@ -11,21 +11,23 @@

class VariableHasSpacesRule(AnsibleLintRule):
id = '206'
shortdesc = 'Variables should have spaces before and after: {{ var_name }}'
base_msg = 'Variables should have spaces before and after: '
shortdesc = base_msg + ' {{ var_name }}'
description = 'Variables should have spaces before and after: ``{{ var_name }}``'
severity = 'LOW'
tags = ['formatting']
version_added = 'v4.0.0'

variable_syntax = re.compile(r"{{.*}}")
bracket_regex = re.compile(r"{{[^{' -]|[^ '}-]}}")
bracket_regex = re.compile(
r"{{[^{\n' -]|[^ '\n}-]}}", re.MULTILINE | re.DOTALL)
exclude_json_re = re.compile(r"[^{]{'\w+': ?[^{]{.*?}}")

def matchtask(self, task: Dict[str, Any]) -> Union[bool, str]:
for k, v in nested_items(task):
if isinstance(v, str):
line_exclude_json = re.sub(r"[^{]{'\w+': ?[^{]{.*?}}", "", v)
if bool(self.bracket_regex.search(line_exclude_json)):
return True
cleaned = self.exclude_json_re.sub("", v)
if bool(self.bracket_regex.search(cleaned)):
return self.base_msg + v
return False


Expand Down

0 comments on commit b64a8ed

Please sign in to comment.