Skip to content

Instantly share code, notes, and snippets.

@nivbend
Last active January 7, 2020 13:21
Show Gist options
  • Save nivbend/7e0e306a98138916b3c9 to your computer and use it in GitHub Desktop.
Save nivbend/7e0e306a98138916b3c9 to your computer and use it in GitHub Desktop.
A simple git pre-commit hook to run pylint on all python scripts changed.
#! /usr/bin/env python
"""Git pre-commit hook to run pylint on python files.
To install:
wget https://gist.github.com/nivbend/7e0e306a98138916b3c9#file-run_pylint-py -O .git/hooks/pre-commit
"""
from __future__ import print_function
from subprocess import check_output, CalledProcessError
from sys import stderr
from os.path import isfile
(SUCCESS,
GIT_DIFF_ERROR,
PYLINT_ERRORS) = range(3)
PYLINTRC = ".pylintrc"
def _print_error(message):
"""Print an error message to stderr."""
print(message, file = stderr)
def _is_python_script(filename):
"""Return true for *.py files and python scripts ("#! /path/to/python")."""
if not isfile(filename):
return False
if not filename.endswith(".py"):
try:
with open(filename, "rb") as contents:
first_line = contents.readline()
except OSError:
return False
# Check shebang.
if not (first_line.startswith("#!") and "python" in first_line):
return False
return True
def run():
"""Verify changed python files using pylint."""
# Get all changed files' paths.
try:
changed_files = check_output(["git", "diff", "--staged", "--name-only", "HEAD", ])
except CalledProcessError:
_print_error("Couldn't get list of changed files")
return GIT_DIFF_ERROR
# Limit checks to python scripts only.
changed_files = [
filename for filename
in changed_files.splitlines()
if _is_python_script(filename)]
if changed_files:
try:
check_output(["pylint", "--rcfile={}".format(PYLINTRC), ] + changed_files)
except CalledProcessError as error:
_print_error(error.output)
_print_error("pylint returned errors, aborting commit.")
return PYLINT_ERRORS
return SUCCESS
if __name__ == "__main__":
exit(run())
@ahookom
Copy link

ahookom commented Feb 3, 2018

This installation instruction didn't work for me. The problem may be just that it should be run_pylint.py instead of run_pylint-py but I suspect it should at least also be file= instead of file-

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment