Skip to content

Instantly share code, notes, and snippets.

@danaspiegel
Created July 13, 2012 16:19
Show Gist options
  • Save danaspiegel/3105761 to your computer and use it in GitHub Desktop.
Save danaspiegel/3105761 to your computer and use it in GitHub Desktop.
Git pre-commit hook to check pep8 and pyflakes
#!/usr/bin/python
# borrowed from https://github.com/lbolla/dotfiles/blob/master/githooks/pre-commit
import os
import sys
import re
import subprocess
devnull = open(os.devnull, 'w')
def call(cmd):
p = subprocess.Popen(cmd.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
out, err = p.communicate()
return out.decode('utf-8'), err.decode('utf-8'), p.returncode
def execute(cmd, silent=False):
if silent:
params = {
'stdout': devnull,
'stderr': devnull,
}
else:
params = {}
retcode = subprocess.call(cmd.split(), **params)
return retcode
def exists(cmd):
return execute('which %s' % cmd, silent=True) == 0
def get_modified(ext):
modified = re.compile('^(?:M|A).(?P<name>.*\.%s)' % ext)
out, _, _ = call('git status --porcelain')
modifieds = []
for line in out.splitlines():
match = modified.match(line.strip())
if (match):
modifieds.append(match.group('name'))
return modifieds
def output(prg, out, err):
print(' * %s:\n%s\n%s' % (prg, out, err))
def die(msg):
print(msg)
sys.exit(1)
def check_python():
modifieds = get_modified('py')
if not modifieds:
return
has_pep8 = exists('pep8')
has_pyflakes = exists('pyflakes')
if not has_pep8:
die('Install PEP8!')
if not has_pyflakes:
die('Install PyFlakes!')
rrcode = 0
for file in modifieds:
out, err, _ = call(
'pep8 %s --ignore=E501,E121,E126,E127,E201,E202,E225' % file)
if out or err:
output('pep8', out, err)
rrcode = rrcode | 1
retcode = execute('pyflakes %s' % file)
rrcode = retcode | rrcode
if rrcode != 0:
sys.exit(rrcode)
def main():
check_python()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment