Automatic deploy web application with GIT

I save up some useful link on this topic a long long while back: https://truongan.name.vn/automated-deploying-using-git/ but never got around to finish the story. My situation is: I have this web application project that I collaborated with some colleague. We have one repository  hosting on our team server.  I want to use that same server to host our web application, both the development and production branch of it (on different domains).

Now whenever we made change to the code base, I want those change to be automatically deploy on the server with a simple git push. At first we simply make the repository working tree available to apache and consider it done. However as the code base grew bigger the deployment process require more change. Both our team have [code].env[/code] file with system specific settings like file path, database configuration, v.v.. that is not portable and the server has its own settings as well. Those files must be ignore by git and left alone by the deployment process.

So I googled around to see how’s others doing their deployment, and landed on this page: http://gitolite.com/deploy.html,  It laid out 4 rules of deployment:

  1. All files in the branch being deployed should be copied to the deployment directory.
  2. Files that were deleted in the git repo since the last deployment should get deleted from the deployment directory.
  3. Any changes to tracked files in the deployment directory after the last deployment should be ignored when following rules 1 and 2. However, sometimes you might want to detect such changes and abort if you found any.
  4. Untracked files in the deploy directory should be left alone

Rule 1 and 3 is pretty much overlap each other and it’s easy to achieve. The most important rule for me is rule 2 and 4. So I follow his method and make some improvisation of my own.
First step is create a hook in the repository.

 cd myrepo.git/hooks
 vim post-receive

Now if you have a bare repo, you will file the director name hooks inside it. If your repo directory contain a Working tree, it will have a directory named .git (this folder is hidden by default on Unix-like OS) the hooks directory will reside there.

Now the this post-receive script will run after some one push into the repository and do all the heavy lifting in deployment. This script should be modified to best suit each need, there is no single-work-for-all formula here.

My hooks look like this:

#!/bin/sh

WORK_TREE="../public_html"
GIT_DIR="./checkup.git"

echo "-------- DEPLOYING HEAD ----------"
git --work-tree=$WORK_TREE --git-dir=$GIT_DIR checkout -f

This script is simple and it work fine for many simple project. At the first time deployment I still have to do stuff like populate the config file, set up database, etc… but afterward a simple git push will be enough to update the live project.