Skip to content

Commit

Permalink
Add ability to ignore jinja2 templates
Browse files Browse the repository at this point in the history
Fixes issue where jinja2 templated YAML files would endup raising
errors, as the YAML loader would have failed to load them.
  • Loading branch information
ssbarnea committed Mar 25, 2021
1 parent 8a5eddf commit 1958a56
Show file tree
Hide file tree
Showing 5 changed files with 11 additions and 2 deletions.
4 changes: 4 additions & 0 deletions .pre-commit-config.yaml
Expand Up @@ -46,6 +46,10 @@ repos:
rev: v1.26.0
hooks:
- id: yamllint
exclude: >
(?x)^(
examples/other/some.j2.yaml
)$
files: \.(yaml|yml)$
types: [file, yaml]
entry: yamllint --strict
Expand Down
2 changes: 2 additions & 0 deletions examples/other/some.j2.yaml
@@ -0,0 +1,2 @@
# Used to validate that a templated YAML file does not confuse the linter
{% include 'port.j2' %}
2 changes: 2 additions & 0 deletions src/ansiblelint/config.py
Expand Up @@ -40,6 +40,8 @@
# These assignations are only for internal use and are only inspired by
# MIME/IANA model. Their purpose is to be able to process a file based on
# it type, including generic processing of text files using the prefix.
{"jinja2": "**/*.j2"}, # jinja2 templates are not always parsable as something else
{"jinja2": "**/*.j2.*"},
{"text/json": "**/*.json"}, # standardized
{"text/markdown": "**/*.md"}, # https://tools.ietf.org/html/rfc7763
{"text/rst": "**/*.rst"}, # https://en.wikipedia.org/wiki/ReStructuredText
Expand Down
4 changes: 2 additions & 2 deletions src/ansiblelint/rules/__init__.py
Expand Up @@ -89,7 +89,7 @@ def matchlines(self, file: "Lintable") -> List[MatchError]:
# https://github.com/ansible-community/ansible-lint/issues/744
def matchtasks(self, file: Lintable) -> List[MatchError]:
matches: List[MatchError] = []
if not self.matchtask or file.kind not in ['handlers', 'tasks', 'playbook']:
if file.base_kind != 'text/yaml':
return matches

yaml = ansiblelint.utils.parse_yaml_linenumbers(file)
Expand Down Expand Up @@ -136,7 +136,7 @@ def _matchplay_linenumber(play, optional_linenumber):

def matchyaml(self, file: Lintable) -> List[MatchError]:
matches: List[MatchError] = []
if not self.matchplay:
if not self.matchplay or file.base_kind != 'text/yaml':
return matches

yaml = ansiblelint.utils.parse_yaml_linenumbers(file)
Expand Down
1 change: 1 addition & 0 deletions src/ansiblelint/utils.py
Expand Up @@ -737,6 +737,7 @@ def construct_mapping(node, deep=False):
loader.construct_mapping = construct_mapping
data = loader.get_single_data()
except (yaml.parser.ParserError, yaml.scanner.ScannerError) as e:
logging.exception(e)
raise SystemExit("Failed to parse YAML in %s: %s" % (lintable.path, str(e)))
return data

Expand Down

0 comments on commit 1958a56

Please sign in to comment.