Automate your development with git hooks


Have you ever mistakenly pushed your code directly into master branch instead of a branch you were meaning to push to? Or have you ever forgotten to run your tests and introduced a bug with your pull request? If you have been coding for a while now, it is quite likely that you have run into these situations. It is quite easy to forget to perform these necessary but annoying tasks.

We have avoided these mistakes at Jana by using git hooks. Git hooks are simple yet powerful tools that allow you to automate menial tasks. These tools can be automatically triggered by different git events. Based on your needs, you can create different executables to run before and after events like commit, merge and push. Please check here for a full list of events that can trigger your git-hook scripts. These scripts are fully customizable and can be written in scripting language of your choice.

Git hooks come free with git. In this blog post I will show you how to setup a simple git hook that prevents you from committing your code in master branch. First lets create a simple executable that returns 0 only if current branch is not master. We will name this script and add it to githooks folder in your project root.

This script simply checks if the branch is master and return 0 if it is not master. Git will not allow you to commit your code if the script returns anything other than 0. Now lets configure this script to be run as your pre-commit git hook. Before doing this, I strongly encourage you to take a look at the contents of .git/hooks folder in your repository. There you can see sample git hook files for different events. In this case, we are only concerned with pre-commit event. Therefore, we will create a symlink with the name pre-commit that will link to the python script that we just wrote.ln -s ../../githooks/ pre-commit That is all we need for setting up a git hook that prevents engineers from commiting directly to master branch! Git will automatically look for the script and run it next time you make a commit.


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