One of the more interesting features of Git is hooks. With hooks, you can tie an arbitrary script to various Git events. Whenever a particular event, such as a git commit or git push, occurs, the script attached to that event gets executed.
Typically, an event consists of several steps, and a script can be attached to each of these steps. The most common steps are pre-event and post-event, with pre hooks executed before the event and post hooks after the event. A pre hook, such as pre-commit, is generally used to cross-check the updates and can approve or reject an actual event. A post hook is used to execute additional activities after an event, such as start a built process when a new push is received or a notification sent.
Every Git repository consists of a .git/hooks directory with sample scripts. You can start using those hooks by removing the .sample extension from the script name. Additionally, the hook scripts belong to a single repository instance and do not get copied with the repository clone. So, if you add some hooks to your local repository and then push changes to the remote, the hooks will not get replicated on the remote. You will need to manually copy those scripts on the remote system. Built-in sample hooks generally use the shell scripts, but you can use any scripting language, such as Python or even PHP.
In this recipe, we will learn how to use Git hooks. We will create our own post-commit hook that deploys to a local web server.
Getting ready
We will need a local web server installed. I have used an Apache installation; feel free to use your favorite server:
Set up a new virtual host under Apache and enable it:
$ cd /var/www/
$ sudo mkdir git-hooks-demo
$ sudo chown ubuntu:ubuntu git-hooks-demo
$ cd git-hooks-demo
Create index.html and add the following contents to it:
$ vi index.html