Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Migrated from shell pycodestyle checking to python module #4

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
37 changes: 14 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,38 +1,29 @@
PEP8 Git Commit Hook
====================

This is a pre-commit hook for Git that checks the code to be committed
for Python PEP8 style compliance. The hook will prevent the commit in
case style violations are detected.

Installation:
case style violations are detected. The script only checks for violations
in the changes, not the file as a whole.

1. Install the pycodestyle (formally called pep8) program: ```$ pip install pycodestyle```
2. Save pre-commit as your_project/.git/hooks/pre-commit
3. Mark pre-commit executable: ```$ chmod +x your_project/.git/hooks/pre-commit```
This code was forked from [https://github.com/cbrueffer/pep8-git-hook](https://github.com/cbrueffer/pep8-git-hook).

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

Currently, the following PEP8 codes are checked for:
Installation
====================

E111 indentation is not a multiple of four
E125 continuation line does not distinguish itself from next logical line
E203 whitespace before ':'
E261 at least two spaces before inline comment
E262 inline comment should start with '# '
E301 expected 1 blank line, found 0
E302 expected 2 blank lines, found 1
E303 too many blank lines (2)
E502 the backslash is redundant between brackets
E701 multiple statements on one line (colon)
E711 comparison to None should be 'if cond is None:'
W291 trailing whitespace
W293 blank line contains whitespace
1. Install the requirements ```$ pip install -r requirements.txt```
2. Save pre-commit as your_project/.git/hooks/pre-commit
3. Mark pre-commit executable: ```$ chmod +x your_project/.git/hooks/pre-commit```

In case you want to modify the list of codes to ignore, edit the
```ignore_codes``` list in the pre-commit file.
If you want to select only specific codes to scan for, use the
```select_codes``` list.
Additional arguments to the pycodestyle program (e.g., ```--max-line-length=120```) can be added to the ```overrides``` list.

This code was forked from [https://gist.github.com/810399](https://gist.github.com/810399).
Usage
====================
* The hook can be overridden: ```$ git commit --no-verify```
* If you want to modify the list of codes to ignore, edit the ```ignore_codes``` list in the pre-commit file.
* If you want to select only specific codes to scan for, use the ```select_codes``` list.
* Additional arguments to the pep8 program (e.g., ```--max-line-length=120```) can be added to the ```overrides``` list.
68 changes: 21 additions & 47 deletions pre-commit
Original file line number Diff line number Diff line change
@@ -1,61 +1,35 @@
#!/usr/bin/env python
#!/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
import pycodestyle

# don't fill in both of these
select_codes = []
ignore_codes = ["E121", "E122", "E123", "E124", "E125", "E126", "E127", "E128",
"E129", "E131", "E501"]
# Add things like "--max-line-length=120" below
overrides = []
def system(cmd, **kwargs):
kwargs.setdefault('stdout', subprocess.PIPE)
proc = subprocess.Popen(cmd, **kwargs)
return proc.communicate()[0]

def main():
pycheck = re.compile('.*.py')
git_args = ['git', '--no-pager', 'diff', '--cached']
diffs = pycodestyle.parse_udiff(system(git_args).decode("utf-8"))

def system(*args, **kwargs):
kwargs.setdefault('stdout', subprocess.PIPE)
proc = subprocess.Popen(args, **kwargs)
out, err = proc.communicate()
return out
files = diffs.keys()
files = [filename for filename in files if pycheck.match(filename)]

checker = pycodestyle.StyleGuide(
parse_argv=False,
config_file="setup.cfg",
reporter=pycodestyle.DiffReport, selected_lines=diffs)

def main():
modified = re.compile('^[AM]+\s+(?P<name>.*\.py$)', re.MULTILINE)
files = system('git', 'status', '--porcelain').decode("utf-8")
files = modified.findall(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"),)
report = checker.check_files(paths=files)

if report.total_errors != 0:
print('''PEP8 style violations have been detected. Please fix them
or force the commit with "git commit --no-verify".''')
sys.exit(1)


Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pycodestyle