23

Git

A lot of time has passed since I was working with web projects on daily basis. However, from time to time I am still developing small web applications, mainly as a backend helpers for my iOS or OS X projects. Recently I figured out a very simple way for deploying those projects easily using git.

There is nothing sophisticated in this solution. Professional web developers probably already have better approach that gives more functionality. But for simple projects, it has everything to make deployment a fast and non-absorbing task.

The whole idea is that you can work on your project’s source managed by git locally. Whenever you need to deploy, you just push to the repository located on your web server. The remote files will be updated automatically. Any changes made on the sever that wasn’t committed, will be discarded. This include all files created in the project’s directory, but not added to the repository.

In order to use this solution you need a web server that you can connect to using SSH protocol. There needs to be git installed and ready to use. Having an SSH access is required for two reasons. You will need to create a repository on the host, and later you will add remote in your local repository like this:

git remote add webserver ssh://username@yourdomain.com:port/path/to/the/repo/

I have made simple script that initializes empty repository and do all required setup to provide functionality described above. You just need to connect to your web server using SSH and run this script:

#!/bin/sh

# Check if repository already exists
if [ -d ".git" ]; then
    exit
fi

# Create empty repository
git init

# Update configuration in order to allow pushing to the repository
git config receive.denyCurrentBranch ignore

# Create post-receive hook that discards not committed changes on the web server
POST_RECEIVE_HOOK_PATH=".git/hooks/post-receive"
cat << EOF > $POST_RECEIVE_HOOK_PATH
#!/bin/sh
cd ..
GIT_DIR='.git'
umask 002
git reset --hard
git clean -f
EOF
chmod +x $POST_RECEIVE_HOOK_PATH

From now on, you can start deploying web projects using git. Whenever you push to your newly created repository, the sources on the web server will be updated to match your local repository state. If you made some changes or added new files on the remote host, they will be discarded. That way you will be sure that all files on the remote server matches your repository state.