Created
June 4, 2012 13:03
-
-
Save nqnwebs/2868239 to your computer and use it in GitHub Desktop.
pep8 and pyflake as git hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 <[email protected]> | |
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