pylint and git hook for pre-commit

Nov 13, 2014 • 1 minutes to read • Last Updated: Dec 24, 2015

A short description of a git hook would be a script that runs when some important actions occur in your git repository. There are different kinds of actions (pre-commit, post-commit, pre-update, post-update, etc…) where you can run your code. What we will concentrate on would be the pre-commit action.

A pre-commit action is something that runs before you commit files into your git repository. This particularly is my favorite area for running pylint since, it stops me from committing code that doesn’t follow the right python standards.

So first you need to install the following python packages from pip.

pip install pylint
pip install git-pylint-commit-hook==2.0.7

Next goto the git repository that you are working on and navigate to your .git/hooks/ directory. From the root directory of your project, run the following command to rename the pre-commit.sample file to pre-commit

cd .git/hooks/
mv pre-commit.sample pre-commit

Delete everything thats in there and paste this in the pre-commit file

#!/bin/sh
git-pylint-commit-hook

What this does is, it checks for updates in all the .py files from your last commit and runs pylint on it. If your code doesn’t pass the pylint rating then it won’t let your commit your changes.

Run pylint on example.py

pylint example.py

Fix the errors, warnings and suggestions you see from pylint. The git-pylint-commit-hook documentation can be found here. It lets you also configure your .pylintrc file in the git repository.

Pylint on Sublime Text 2/3

Installing a pylint package that helps you validate your code while typing would be a good time saver. So from your Sublime Text Package Control find a package that works best for you. If you don’t have package control then here’s a link for you to download it.