Skip to content

Instantly share code, notes, and snippets.

@nqnwebs
Created June 4, 2012 13:03
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nqnwebs/2868239 to your computer and use it in GitHub Desktop.
Save nqnwebs/2868239 to your computer and use it in GitHub Desktop.
pep8 and pyflake as git hook
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
An script to run pep8 and pyflakes via git's pre-commit hook
based on https://github.com/lbolla/dotfiles/blob/master/githooks/pre-commit
modified by Martin Gaitán <mgaitan@machinalis.com>
Install:
copy it as your REPO/.git/hooks/pre-commit given execute permission
Usage:
just commit your changes as usual. When python files were modified, it
run pep8 and pyflakes. If no errors, the commit is done, else it exist given
useful output
To skip the hook you should use:
$ git commit -n
"""
import os
import sys
import re
import subprocess
MAX_LINE_LENGHT = 90
devnull = open(os.devnull, 'w')
def call(cmd, cwd=None):
p = subprocess.Popen(cmd.split(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
cwd=cwd)
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():
has_pep8 = exists('pep8')
has_pyflakes = exists('pyflakes')
if not (has_pep8 or has_pyflakes):
die('Install PEP8 and PyFlakes!')
modifieds = get_modified('py')
if not modifieds:
return
rrcode = 0
for file in modifieds:
out, err, _ = call('pep8 --max-line-length=%d %s' %
(MAX_LINE_LENGHT, 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