post-receive.git-hook 2.02 KB
#!/bin/bash
# 
# Continuous Deployment
# ---------------------
#
# This file is a post-receive hook to be installed in the
# ./hooks/ dir of a bare git repository.
#
# When pushing to that repo from outside (a dev machine,
# or a jenkins/gitlab ci_cd rule), it updates a working dir previously
# set by cd to ${TARGET} and get the latest code .

# How to set it up:
# -----------------
#
# On the server to deploy:
#
# 1- create a bare repository and set hook
#    git clone url-to-central-repo deploy-repo.git
#    cp post-receive.git-hook deploy-repo.git/hooks/post-receive 
#    
# 2- set a working dir and configure
#    cd /var/www/
#    git clone  deploy-repo.git your-app-dir
#    do_any_config_tasks
#
#
# On the desktop computer:
# 
# 1- add the server as a remote source
#    git remote add deploy url-to-deploy-repo.git
# 
# 2- try it out
#    git push deploy HEAD:BRANCH_NAME 

#
#    $TARGET: is the working dir you want to update at last
#    $BRANCH: is the branch you want to update from
#
TARGET="/var/www/aroma-db"
BRANCH="DEV"

while read oldrev newrev ref
do
	# only checking out the branch you would like to deploy
	if [ "$ref" = "refs/heads/$BRANCH" ];
	then
		echo "Ref $ref received. Deploying ${BRANCH} branch to production..."
        cd $TARGET || exit
        unset GIT_DIR
        git stash # remove any modification, sorry guy.
        git checkout ${BRANCH} # set branch if not done yet, sorry guy
        git pull origin ${BRANCH} # get latest modifications, assumes  remote origin previously set
        touch *wsgi # now, trigger wsgidaemons restarting
        /bin/sh scripts/post-deploy.sh
		exec git update-server-info
	else
		echo "Ref $ref received. Doing nothing: only the ${BRANCH} branch may be deployed on this server."
	fi
done

# Alternately, it is possible to just update a
# working tree without any git meta data in it with the
# following instruction:
#    $GIT_DIR: is the directory of current bare repo
# GIT_DIR="/home/richard/aroma-db.git/"
# git --work-tree=$TARGET --git-dir=$GIT_DIR checkout -f $BRANCH

# vim: ft=sh