1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3#
4# Copyright 2017, Data61
5# Commonwealth Scientific and Industrial Research Organisation (CSIRO)
6# ABN 41 687 119 230.
7#
8# This software may be distributed and modified according to the terms of
9# the BSD 2-Clause license. Note that NO WARRANTY is provided.
10# See "LICENSE_BSD2.txt" for details.
11#
12# @TAG(DATA61_BSD)
13#
14
15'''
16Run pylint on a Jinja 2 template.
17'''
18
19from __future__ import absolute_import, division, print_function, \
20    unicode_literals
21
22import atexit, jinja2, os, shutil, subprocess, sys, tempfile
23
24# Clagged pieces from the runner.
25START_BLOCK = '/*-'
26END_BLOCK = '-*/'
27START_VARIABLE = '/*?'
28END_VARIABLE = '?*/'
29START_COMMENT = '/*#'
30END_COMMENT = '#*/'
31
32def main(argv, out, err):
33    if len(argv) < 2 or argv[1] in ['--help', '-?']:
34        err.write('%s file pylint_args...\n' % argv[0])
35        return -1
36
37    if not os.path.exists(argv[1]):
38        err.write('%s not found\n' % argv[1])
39        return -1
40
41    root, template = os.path.split(os.path.abspath(argv[1]))
42
43    # Construct a Jinja environment that matches that of the runner.
44    env = jinja2.Environment(
45        loader=jinja2.FileSystemLoader(root),
46        extensions=["jinja2.ext.do", "jinja2.ext.loopcontrols"],
47        block_start_string=START_BLOCK,
48        block_end_string=END_BLOCK,
49        variable_start_string=START_VARIABLE,
50        variable_end_string=END_VARIABLE,
51        comment_start_string=START_COMMENT,
52        comment_end_string=END_COMMENT)
53
54    # Compile the template requested to a temporary directory.
55    tmp = tempfile.mkdtemp()
56    atexit.register(shutil.rmtree, tmp)
57    out.write('compiling to %s...\n' % tmp)
58    env.compile_templates(tmp, filter_func=lambda x: x == template, zip=None,
59        ignore_errors=False)
60
61    # Find it and run pylint on it.
62    py = os.path.join(tmp, os.listdir(tmp)[0])
63    out.write('running pylint on %s...\n' % py)
64    return subprocess.call(['pylint', py] + argv[2:])
65
66if __name__ == '__main__':
67    sys.exit(main(sys.argv, sys.stdout, sys.stderr))
68