Git pre-commit hook

When I got repeated reviews about code not passing flake8 checking bob mentioned about using hooks. It was then a new term to me. After checking a couple of webpages I found it very interesting. I wrote a git pre-commit-hook using shell scripting.My script checks two case

1: Check if the current branch is a master branch.
2: Check for python file for checking python syntax errors

What are git hooks?
git can trigger some import actions before you perform an important function like commit, rebase etc. A pre-commit hook is triggered before a commit occurs. Git hooks are stored in hooks directory of .git

Step 1

cd .git/hooks
vi pre- commit

Step 2: Copy the code

(git diff --cached --name-only

git diff–cached is used to find the difference between latest commit and files added for staging.
–name-only list only names of the that have changed.

(git diff --cached --name-only --diff-filter=ACM | grep -e '\.py$'

This list all the python files.

flake8 $file --ignore=E501

This ignores E501(line too long).

Step3: Make the file executable

chmod +x pre-commit-hook

And that’s it. Now every time when you commit your code, git will run flake8 for you. Also you may not fear about accidentally committing your master branch.


2 thoughts on “Git pre-commit hook

  1. For small projects (or large but modular ones), I often use a pre-commit hook to do some basic validation… run a build, run unit tests, and if those fail, block the commit. I can disable the hook if for some reason I need to commit broken code, but it can be a useful safety net.

    Of course, it’s not much use if you’re dealing with a project where that hook would take more than 5-10 seconds to complete.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s