1#!/usr/bin/env python
2
3helpdoc = """
4A simple utility that verifies the syntax for python scripts.
5The checks it does are :
6  * Check for 'tab' characters in .py files
7  * Compile errors in py sources
8Usage:
9  python syntax_checker.py <python_source_file> [<python_source_file> ..]
10"""
11import py_compile
12import sys
13import os
14import re
15
16tabs_search_rex = re.compile("^\s*\t+",re.MULTILINE|re.DOTALL)
17
18if __name__ == "__main__":
19    if len(sys.argv) < 2:
20        print "Error: Unknown arguments"
21        print helpdoc
22        sys.exit(1)
23    for fname in sys.argv[1:]:
24        if not os.path.exists(fname):
25            print "Error: Cannot recognize %s as a file" % fname
26            sys.exit(1)
27        if fname.split('.')[-1] != 'py':
28            print "Note: %s is not a valid python file. Skipping." % fname
29            continue
30        fh = open(fname)
31        strdata = fh.readlines()
32        lineno = 0
33        tab_check_status = True
34        for linedata in strdata:
35            lineno += 1
36            if len(tabs_search_rex.findall(linedata)) > 0 :
37                print "Error: Found a TAB character at %s:%d" % (fname, lineno)
38                tab_check_status = False
39        if tab_check_status == False:
40            print "Error: Syntax check failed. Please fix the errors and try again."
41            sys.exit(1)
42        #now check for error in compilation
43        try:
44            compile_result = py_compile.compile(fname, cfile="/dev/null", doraise=True)
45        except py_compile.PyCompileError as exc:
46            print str(exc)
47            print "Error: Compilation failed. Please fix the errors and try again."
48            sys.exit(1)
49        print "Success: Checked %s. No syntax errors found." % fname
50    sys.exit(0)
51
52