Skip to content

Instantly share code, notes, and snippets.

@alexanderad
Forked from lentil/gist:810399
Last active December 20, 2015 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexanderad/6163219 to your computer and use it in GitHub Desktop.
Save alexanderad/6163219 to your computer and use it in GitHub Desktop.
GIT pre-commit hook for python project, which uses simplified pep8 checks and pyflakes checks. 0) pip install pyflakes && pip install pep8 1) download https://gist.github.com/alexanderad/6163219 2) mv <downloaded file name> .git/hooks/pre-commit 4) chmod +x .git/hooks/pre-commit 5) ... 6) PROFIT!
#!/usr/bin/python
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_ignore = 'E501,E261,E262'
"""
Set PEP8 to be less strict, we ignore:
* E501 line too long
* E261 at least two spaces before inline comment
* E262 inline comment should start with '# '
"""
pep8_out, pep8_err = system('pep8', '.', '--ignore=%s' % pep8_ignore, cwd=tempdir)
flakes_out, flakes_err = system('pyflakes', '.', cwd=tempdir)
shutil.rmtree(tempdir)
if pep8_out or flakes_out:
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 = raw_input("Commit anyway? [y/N] ")
sys.stdin = stdin
if data.lower() in ["y", "yes"]:
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