Skip to content

Instantly share code, notes, and snippets.

@esynr3z
Last active December 18, 2020 05:25
Show Gist options
  • Save esynr3z/206e164023a794eb0c96d827de31bd49 to your computer and use it in GitHub Desktop.
Save esynr3z/206e164023a794eb0c96d827de31bd49 to your computer and use it in GitHub Desktop.
PEP8 Git Commit Hook

PEP8 Git Commit Hook

Based on pep8-git-hook.

Every staged Python file will be checked.

Installation:

  • Install the pycodestyle (formally called pep8) program: $ pip install pycodestyle
  • Save pre-commit as your_project/.git/hooks/pre-commit
  • Mark pre-commit executable: $ chmod +x your_project/.git/hooks/pre-commit

The hook can be overridden: $ git commit --no-verify

#!/usr/bin/env python3
"""
Forked from https://gist.github.com/810399
"""
from __future__ import with_statement, print_function
import os
import re
import shutil
import subprocess
import sys
import tempfile
# don't fill in both of these
select_codes = []
ignore_codes = ["W504", "E402", "E731", "C406", "E741"]
# Add things like "--max-line-length=120" below
overrides = ["--max-line-length=120"]
def system(*args, **kwargs):
kwargs.setdefault('stdout', subprocess.PIPE)
proc = subprocess.Popen(args, **kwargs)
out, err = proc.communicate()
return out
def main():
modified = re.compile('^[AM]+\s+(?P<name>.*\.py$)', re.MULTILINE)
files = system('git', 'status', '--porcelain').decode("utf-8")
files = modified.findall(files)
print('PEP8 will check files:', files)
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 open(filename, 'w') as f:
system('git', 'show', ':' + name, stdout=f)
args = ['pycodestyle']
if select_codes and ignore_codes:
print(u'Error: select and ignore codes are mutually exclusive')
sys.exit(1)
elif select_codes:
args.extend(('--select', ','.join(select_codes)))
elif ignore_codes:
args.extend(('--ignore', ','.join(ignore_codes)))
args.extend(overrides)
args.append('.')
output = system(*args, cwd=tempdir)
shutil.rmtree(tempdir)
if output:
print(u'PEP8 style violations have been detected. Please fix them\n'
'or force the commit with "git commit --no-verify".\n')
print(output.decode("utf-8"),)
sys.exit(1)
else:
print(u'OK. No PEP8 style violations have been detected.')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment