← Back to blog home

Using git to deploy to live server based on branch aka how to git push to server

02 Dec

I often see people asking how to push their changes to the dev or live server. I agree with the common sentiment that you should probably use a proper deployment script, but I also think for most simple sites git is fairly sufficient.

To accomplish this I made a git hooks script that executes a pull from the appropriate web root depending on the branch.

For this we're going to be using the post-update hook. To create a post-update hook simply go to the hooks directory of your bare repository and rename 'post-update.sample' to 'post-update' (remove .sample) and chmod it +x to make it executable.

Once that is done open it in your favorite text editor and add the following code:

 

#determine the branch
BRANCH=`echo $1 | cut -d '/' -f 3`
#needed for "dumb servers" google if you need more explanation
git update-server-info
#check for null. If we don't have a branch name lets quit
if [[ -z "$BRANCH" ]]; then
    echo 'could not determine branch.'
    exit 1
fi

#if branch is master use the dev path
if [ "$BRANCH" == 'master' ]; then
    PUSH_PATH=/path/to/dev/server/doc/root
fi

#if branch is live use the live path
if [ "$BRANCH" == 'live' ]; then
    PUSH_PATH=/path/to/live/server/doc/root
fi

#check for null and make sure the path exists
# then execute a pull from that repository
if [[  -n "$PUSH_PATH"  &&  -d "$PUSH_PATH" ]]; then
    cd $PUSH_PATH
    unset GIT_DIR
    git --git-dir $PUSH_PATH/.git pull origin $BRANCH
else
    echo 'Push path for '$PUSH_PATH' not found'
fi

What this code does is quite simple. First it uses the linux cut command to separate out the branch name from the arguments. Then there is an if statement for each branch to tell it where to go. Any branch that isn't explicitly listed in the if statements won't do anything. This allows you to freely create other branches and only when you push master or live will it go to the server. Also, you could use any branch name instead of master if you prefer.

Warning: This makes it really easy (probably too easy) to push live. This means it's easy to accidentally push changes live. If you are accidentally on the "live" branch and make some changes then commit and push them without thinking those changes will be live before you even realize what happened. So I guess I'm just saying be careful.

 
No Comments

Posted in Guides

 

Tags: ,

Leave a Reply

Notify me of future comments

(I don't spam or share your e-mail. Unsubscribing is as easy as clicking the "unsubscribe" link in the notifications)