Created
April 19, 2019 23:32
-
-
Save zdw/07790d1a46c965bf1b27dd6b2e7e2d75 to your computer and use it in GitHub Desktop.
Runs yamllint against a jinja2 templated YAML file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# dej2lint - remove jinja2 directives for lint checking | |
# also should try to fix line nums in lint output | |
# currently only runs on yaml files with yamllint | |
import sys | |
import re | |
from yamllint import linter | |
from yamllint.config import YamlLintConfig | |
# Variables | |
linenum = 0 # current line | |
rmln = [] # list of line numbers removed from file (ordered) | |
in_comment = False # if we're in a comment | |
cleanbuf = "" # cleaned up lines, passed to parser | |
def offset_line(lintlinenum): | |
""" given the linted line number, return the original line number """ | |
offset = 0 | |
for rmlinenum in rmln: | |
if (lintlinenum + offset) >= rmlinenum: | |
offset += 1 | |
else: | |
break | |
return lintlinenum + offset | |
infile = open(sys.argv[1]) | |
for line in infile: | |
linenum += 1 | |
trimline = line.rstrip() | |
if in_comment: | |
if re.search(r"#\}$", line): | |
print "line: %d, end of comment block: %s" % (linenum, trimline) | |
in_comment = False | |
rmln.append(linenum) | |
else: | |
print "line: %d, inside comment block: %s" % (linenum, trimline) | |
rmln.append(linenum) | |
elif re.search(r"^\{#", line): | |
print "line: %d, start of comment block: %s" % (linenum, trimline) | |
in_comment = True | |
rmln.append(linenum) | |
elif re.search(r"^\{#.*#\}$", line): | |
print "line: %d, full line comment block: %s" % (linenum, trimline) | |
rmln.append(linenum) | |
elif re.search(r"^\{%.*%\}$", line): | |
print "line: %d, full line nonprinting block: %s" % (linenum, trimline) | |
rmln.append(linenum) | |
elif re.search(r"\{%.*%\}", line): | |
print "line: %d, partial line nonprinting block: %s" % (linenum, | |
trimline) | |
cleanline = re.sub(r"\{%.*%\}", "", line) | |
rmln.append(cleanline) | |
elif re.search(r"\{\{.*\}\}", line): | |
print "line: %d, value block: %s" % (linenum, trimline) | |
cleanline = re.sub(r"\{\{.*\}\}", "lintremove", line) | |
cleanbuf += cleanline | |
else: | |
cleanbuf += line | |
print "j2 lines removed:" | |
print " ".join("%d" % rmn for rmn in rmln) | |
print "---" | |
print cleanbuf | |
print "---" | |
conf = YamlLintConfig('extends: default') | |
# Run the linter and print with original line numbers | |
for item in linter.run(cleanbuf, conf, sys.argv[1]): | |
origline = offset_line(item.line) | |
print "line: %d, col: %d, lvl: %s, msg: %s" % (origline, item.column, | |
item.level, item.message) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment