Created
October 13, 2018 20:03
-
-
Save pysysops/b878bbc9fbe06d9deb1c0531873fa564 to your computer and use it in GitHub Desktop.
Python script to lint salt / YAML files.
This file contains hidden or 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 | |
""" | |
Simple Salty Jinja2 linter | |
""" | |
import re | |
import sys | |
import os.path | |
from functools import reduce | |
from jinja2 import BaseLoader, TemplateNotFound, Environment, exceptions | |
import yaml | |
class AbsolutePathLoader(BaseLoader): | |
def get_source(self, environment, template): | |
if not os.path.exists(template): | |
raise TemplateNotFound(template) | |
mtime = os.path.getmtime(template) | |
with open(template) as file: | |
source = file.read().decode('utf-8') | |
return source, template, lambda: mtime == os.path.getmtime(template) | |
def check(template, out, err, env=Environment(extensions=[ | |
'salt.utils.jinja.SerializerExtension', 'jinja2.ext.do'], | |
loader=AbsolutePathLoader())): | |
try: | |
env.get_template(template) | |
with open(template) as fp: | |
file_raw = fp.read() | |
if re.search('{%|{{|{#',file_raw,re.MULTILINE) is None: | |
data = yaml.load(file_raw) | |
out.write("%s: Syntax OK\n" % template) | |
return 0 | |
except TemplateNotFound: | |
err.write("%s: File not found\n" % template) | |
return 2 | |
except exceptions.TemplateSyntaxError as ex: | |
err.write("%s: Syntax check failed: %s in %s at %d\n" | |
% (template, ex.message, ex.filename, ex.lineno)) | |
return 1 | |
except yaml.YAMLError, ex: | |
err.write("%s: Error in file: %s" % (template, ex.problem)) | |
if hasattr(ex, 'problem_mark'): | |
mark = ex.problem_mark | |
err.write(" error position: (%s:%s)" % (mark.line+1, mark.column+1)) | |
err.write('\n') | |
return 1 | |
def main(**kwargs): | |
try: | |
sys.exit(reduce(lambda r, fn: r + | |
check(fn, sys.stdout, sys.stderr, **kwargs), | |
sys.argv[1:], 0)) | |
except IndexError: | |
sys.stdout.write("Usage: ./saltlint.py filename [filename ...]\n") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment