Let’s grasp the idea how git hooks work
# SETTING UP A REPO $: mkdir ~/workspace/simple-hook && cd simple-hook $: git init Initialized empty Git repository in /home/workspace/simple-hook/.git/ $: ls .git HEAD config description hooks info objects refs
We are interested about hooks directory. That’s where all the magic happens. Let’s see content of the hooks directory:
$: ls -la .git/hooks -rwxr-xr-x 1 user user 478 May 19 21:20 applypatch-msg.sample -rwxr-xr-x 1 user user 896 May 19 21:20 commit-msg.sample -rwxr-xr-x 1 user user 189 May 19 21:20 post-update.sample -rwxr-xr-x 1 user user 424 May 19 21:20 pre-applypatch.sample -rwxr-xr-x 1 user user 1642 May 19 21:20 pre-commit.sample -rwxr-xr-x 1 user user 1348 May 19 21:20 pre-push.sample -rwxr-xr-x 1 user user 4898 May 19 21:20 pre-rebase.sample -rwxr-xr-x 1 user user 544 May 19 21:20 pre-receive.sample -rwxr-xr-x 1 user user 1492 May 19 21:20 prepare-commit-msg.sample -rwxr-xr-x 1 user user 3610 May 19 21:20 update.sample
Local deployment: using post-commit to deploy to local web server
We’ll use post-commit hook to deploy to local web server whenever a commit is being made. This hook is not for production use but just to demonstrate the idea how hook works. Let’s set up a web server for the demonstration.
# LINUX USER sudo apt-get update sudo apt-get install apache2 #DOCUMENT ROOT FOR THE WEB SERVER IS /var/www/html. # CHANGE OWNERSHIP FOR CURRENT USER. sudo chown -R `whoami`: `id -gn` /var/www/html #I'LL BE USING XAMPP ON MAC, AND IT'S DOCUMENT ROOT IS: /Applications/XAMPP/xamppfiles/htdocs/
As we are in the project directory, let’s create an ‘index.html’ file.
$: nano index.html # PASTE FOLLWING git hook deployment I'm deployed by a hook! # SAVE AND EXIT Cltr+o Cltr+x
Now before adding these changes and committing them, let’s configure our post-commit hook for this repository:
$: nano .git/hooks/post-commit #!/bin/bash unset GIT_INDEX_FILE git --work-tree=/Applications/XAMPP/xamppfiles/htdocs/simple-hook-deploy --git-dir=/Applications/XAMPP/xamppfiles/htdocs/simple-hook/.git checkout -f Cltr+o Cltr+x # MAKE POST-COMMIT EXECUTIBLE chmod +x .git/hooks/post-commit git add . git commit -m 'let's deploy!'
Now if we browse over localhost (if apache) or localhost/simple-hook-deploy from a web browser we should see: