-
Notifications
You must be signed in to change notification settings - Fork 25
/
j2lint.py
executable file
·57 lines (51 loc) · 1.83 KB
/
j2lint.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#!/usr/bin/env python
"""
@author Gerard van Helden <[email protected]>
@license DBAD, see <http://www.dbad-license.org/>
Simple j2 linter, useful for checking jinja2 template syntax
"""
import os.path
from functools import reduce
from jinja2 import BaseLoader, TemplateNotFound, Environment, exceptions, filters
from jinja2_ansible_filters import AnsibleCoreFiltersExtension
try:
from ansible_collections.ansible.utils.plugins.filter import ipaddr
except:
from ansible_collections.ansible.netcommon.plugins.filter import ipaddr
filters.FILTERS['ipaddr'] = ipaddr
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()
return source, template, lambda: mtime == os.path.getmtime(template)
def check(template, out, err,
env=Environment(loader=AbsolutePathLoader(),extensions=[
'jinja2.ext.i18n',
'jinja2.ext.do',
'jinja2.ext.loopcontrols',
'jinja2_ansible_filters.AnsibleCoreFiltersExtension'
]
)):
try:
env.get_template(template)
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
def main(**kwargs):
import sys
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: j2lint.py filename [filename ...]\n")
if __name__ == "__main__":
main()