Skip to content

Commit

Permalink
Apply var-spacing tests to vars files
Browse files Browse the repository at this point in the history
  • Loading branch information
notok committed Apr 2, 2022
1 parent 29ceb53 commit 9f72276
Showing 1 changed file with 30 additions and 1 deletion.
31 changes: 30 additions & 1 deletion src/ansiblelint/rules/var_spacing.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,16 @@

import re
import sys
from typing import Any, Dict, List, Optional, Union
from typing import TYPE_CHECKING, Any, Dict, List, Optional, Union

from ansiblelint.file_utils import Lintable
from ansiblelint.rules import AnsibleLintRule
from ansiblelint.utils import parse_yaml_from_file
from ansiblelint.yaml_utils import nested_items_path

if TYPE_CHECKING:
from ansiblelint.errors import MatchError


class VariableHasSpacesRule(AnsibleLintRule):
"""Variables should have spaces before and after: {{ var_name }}."""
Expand All @@ -33,6 +37,31 @@ def matchtask(
return self.shortdesc.format(var_name=v)
return False

def matchyaml(self, file: Lintable) -> List["MatchError"]:
"""Return matches for variables defined in vars files."""
results: List["MatchError"] = []
meta_data: Dict[str, Any] = {}

if str(file.kind) == "vars":
meta_data = parse_yaml_from_file(str(file.path))
for k, v, path in nested_items_path(meta_data):
if isinstance(v, str):
cleaned = self.exclude_json_re.sub("", v)
if bool(self.bracket_regex.search(cleaned)):
path_elem = [
f"[{i}]" if isinstance(i, int) else i for i in path + [k]
]
results.append(
self.create_matcherror(
filename=file,
message=self.shortdesc.format(var_name=v)
+ f" The error is at ``.{'.'.join(path_elem)}``.",
)
)
else:
results.extend(super().matchyaml(file))
return results


if "pytest" in sys.modules:

Expand Down

0 comments on commit 9f72276

Please sign in to comment.