Skip to content

Instantly share code, notes, and snippets.

@oubiwann
Forked from lentil/gist:810399
Created August 17, 2012 18:44
Show Gist options
  • Save oubiwann/3381472 to your computer and use it in GitHub Desktop.
Save oubiwann/3381472 to your computer and use it in GitHub Desktop.
Unit tests, PEP8, PyFlakes pre-commit hook in Python (with interactive support!)
#!/usr/bin/env python3
import os
import re
import shutil
import subprocess
import sys
import tempfile
def system(*args, **kwargs):
kwargs.setdefault('stdout', subprocess.PIPE)
proc = subprocess.Popen(args, **kwargs)
out, err = proc.communicate()
return ((out or b"").decode("utf-8"), err)
def main():
modified = re.compile('^[AM]+\s+(?P<name>.*\.py)', re.MULTILINE)
files, file_err = system('git', 'status', '--porcelain')
files = modified.findall(files)
tempdir = tempfile.mkdtemp()
print("Scanning modified files...")
for name in files:
print("\t%s" % name)
filename = os.path.join(tempdir, name)
filepath = os.path.dirname(filename)
if not os.path.exists(filepath):
os.makedirs(filepath)
with open(filename, 'w') as f:
system('git', 'show', ':' + name, stdout=f)
pep8_out, pep8_err = system('pep8', '.', cwd=tempdir)
flakes_out, flakes_err = system('pyflakes', '.', cwd=tempdir)
test_status = "OK"
try:
subprocess.check_call(['make', 'check'])
except subprocess.CalledProcessError:
test_status = "FAIL"
shutil.rmtree(tempdir)
if pep8_out or flakes_out or test_status == "FAIL":
print("\nTest status: %s" % test_status)
if pep8_out:
print("\nThe following PEP8 violations were found:\n")
print(pep8_out)
else:
print("\nPEP8 Status: OK\n")
if flakes_out:
print("The following Python flakes were found:\n")
print(flakes_out)
else:
print("\nPython Flakes Status: OK\n"
stdin = sys.stdin
sys.stdin = open('/dev/tty')
data = input("Commit anyway? [y/N] ")
sys.stdin = stdin
if data.lower() == "y":
print("Committing ...")
sys.exit(0)
print("Aborting commit ...")
sys.exit(1)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment