Skip to content

Instantly share code, notes, and snippets.

@splaice
Created February 8, 2012 07:04
Show Gist options
  • Save splaice/1766244 to your computer and use it in GitHub Desktop.
Save splaice/1766244 to your computer and use it in GitHub Desktop.
PEP8 pre-commit hook in Python
#!/usr/bin/env python
from __future__ import with_statement
import os
import shutil
import subprocess
import sys
import tempfile
def system(*args, **kwargs):
kwargs.setdefault('stdout', subprocess.PIPE)
try:
proc = subprocess.Popen(args, **kwargs)
out, err = proc.communicate()
except OSError, e:
print "error: could not execute %r" % "".join(args)
sys.exit(1)
return out
def main():
fail=False
files = (file for file in system('git', 'diff', '--name-only', '--staged', '--diff-filter=AM').splitlines() if file.endswith('.py'))
tempdir = tempfile.mkdtemp()
for name in files:
filename = os.path.join(tempdir, name)
filepath = os.path.dirname(filename)
if not os.path.exists(filepath):
os.makedirs(filepath)
with file(filename, 'w') as f:
system('git', 'show', ':' + name, stdout=f)
# run pep8
print "running hook - pep8"
output = system('pep8', '.', cwd=tempdir)
if output:
fail=True
print output,
print "running hook - pyflakes"
output = system('pyflakes', '.', cwd=tempdir)
if output:
fail=True
print output,
shutil.rmtree(tempdir)
if fail:
sys.exit(1)
else:
sys.exit(0)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment