Skip to content

Instantly share code, notes, and snippets.

@gaker
Forked from lentil/gist:810399
Created August 29, 2011 16:42
Show Gist options
  • Save gaker/1178794 to your computer and use it in GitHub Desktop.
Save gaker/1178794 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 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
def ignore_file(filename):
ignored = ['/migrations/', 'manage.py']
match = False
for i in ignored:
if i in filename:
match = True
return match
def main():
modified = re.compile('^[AM]+\s+(?P<name>.*\.py)', re.MULTILINE)
files = system('git', 'status', '--porcelain')
files = modified.findall(files)
tempdir = tempfile.mkdtemp()
for name in files:
filename = os.path.join(tempdir, name)
if not ignore_file(filename):
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)
output = system('pep8', '.', cwd=tempdir)
shutil.rmtree(tempdir)
if output:
print output,
sys.exit(1)
if __name__ == '__main__':
main()
@gaker
Copy link
Author

gaker commented Aug 29, 2011

Updating to ignore Django's mange.py file as well as South migrations files.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment