Skip to content

Instantly share code, notes, and snippets.

@lucascarvalho
Created July 25, 2014 13:43
Show Gist options
  • Save lucascarvalho/5046ec8197d3d006ad88 to your computer and use it in GitHub Desktop.
Save lucascarvalho/5046ec8197d3d006ad88 to your computer and use it in GitHub Desktop.
python flake8 git pre-commit hook
#!/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)
proc = subprocess.Popen(args, **kwargs)
out, err = proc.communicate()
return out
def main():
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)
output = system('flake8', '--ignore=E501', '.', cwd=tempdir)
shutil.rmtree(tempdir)
if output:
print output,
sys.exit(1)
if __name__ == '__main__':
main()
@lucascarvalho
Copy link
Author

pip install flake8

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