Git and Rails : Switch your database.yml when changing branch

Posted by Antonin AMAND Wed, 09 Jul 2008 10:01:00 GMT

As a lot of people, I think, I have different database.yml file according to git branch I’m working on. I was constantly switching it manually until I discovered that git has more hooks that I thought.

I set up a post-checkout hooks script to automagically switch my database.yml when checking out a branch.

It is a simple script that recover the branch name a do a symlink.

if i checkout branch master it will look for a file named config/database.master.yml and create a symlink to config/database.yml

here it is :


#! /bin/sh
#
# .git/hooks/post-checkout

BRANCH=`git symbolic-ref HEAD 2> /dev/null | sed -e 's/^.*\///'`
GITPATH="`git rev-parse --git-dir 2>/dev/null`/.."

if [ "$BRANCH" == "" ]; then
        echo "no branch name. do nothing"
        exit 0
fi

if [ -f "$GITPATH/config/database.yml" ] && [ ! -L "$GITPATH/config/database.yml" ]; then
        echo "database.yml exists and not a symlink. do nothing."
        exit 0
fi

echo "look for $GITPATH/config/database.$BRANCH.yml"

if [ -f "$GITPATH/config/database.$BRANCH.yml" ]; then
        echo "switch database configuration file to config/database.$BRANCH.yml"
        rm -f "$GITPATH/config/database.yml";
        ln -s "$GITPATH/config/database.$BRANCH.yml" \
        "$GITPATH/config/database.yml"
fi
 

or on Pastie