#!/usr/bin/env python
import sys
import subprocess
import os
import re
def syscmd(*args, **kw):
fail_ok = kw.get('fail_ok', False)
p = subprocess.Popen(args, stdout=subprocess.PIPE)
out, _ = p.communicate()
if not fail_ok and p.returncode != 0:
raise RuntimeError('%s # failed: %s' % (' '.join(args), p.returncode))
return out
def checkline(line, report_error, ext=None):
if re.search(r'console\.log', line):
report_error('console.log: %s' % line)
if re.search(r'print[^\n]+', line):
report_error('print statement: %s' % line)
if ext in ('js', 'py'):
if re.search(r'\s$', line):
report_error('Trailing whitespace: %s' % line)
def checkfile(filename, report_error):
if filename.endswith('py'):
out = syscmd('bin/django-lint', '-e', filename)
if filename.startswith('media') and filename.endswith('js'):
p = subprocess.Popen(
['bin/jslint', filename],
stdout=subprocess.PIPE
)
out, _ = p.communicate()
if 'No problems found in' not in out:
report_error('JSlint errors', filename=filename)
print >> sys.stderr, out
def difflines():
diff = syscmd('git', 'diff', '--cached', '-M')
filename = None
lineno = None
for line in diff.split('\n'):
m = re.match(r'^diff --git a/(.*) b/\1$', line)
if m:
filename = m.group(1)
continue
m = re.match(r'@@ -\S+ \+(\d+)', line)
if m:
lineno = int(m.group(1)) - 1
continue
if line.startswith('+++'):
continue
if line.startswith(' '):
lineno += 1
continue
if line.startswith('+'):
lineno += 1
yield line, filename, lineno
def check(report_error):
if os.environ.get('SKIPCHECKS'):
sys.exit(0)
status = syscmd('git', 'status', fail_ok=True)
if 'Untracked files:' in status:
report_error('Untracked files')
filenames = set()
ext = None
for line, filename, lineno in difflines():
ext = filename.partition('.')[2]
filenames.add(filename)
checkline(line, lambda why: report_error(why, lineno, filename), ext)
if not os.environ.get('SKIPLINT'):
for filename in sorted(filenames):
checkfile(filename, report_error)
fail = False
def run():
def report_error(why, line=None, filename=None):
global fail
if not fail:
print >> sys.stderr, "*"
print >> sys.stderr, "* Errors found:"
print >> sys.stderr, "*"
print >> sys.stderr, "* %s" % why
if line or filename:
extra = '' + ('line %d ' % line if line else '') + \
('in %s' % filename if filename else '')
print >> sys.stderr, "* %s" % extra
print "*"
fail = True
check(report_error)
return int(fail)
sys.exit(run())