Skip to content

Instantly share code, notes, and snippets.

@oneamtu
Last active December 15, 2015 02:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oneamtu/5190673 to your computer and use it in GitHub Desktop.
Save oneamtu/5190673 to your computer and use it in GitHub Desktop.
post-checkout hook script to change database.yml config
#!/bin/bash
#
# This hook changes database name prefix in config/database.yml based on the branch
# being checked out. It expects the database name prefix to be on word followed
# by a dash.
# If the branch name has a dash, it will take the new database name prefix as the
# name of the branch before the first dash e.g. ihas-feature => ihas
# This allows multiple branches to use the same database.
#
# File checkouts are ignored. Checking out a remote branch or a different ref
# will leave the database.yml file unchanged.
#
# E.g. from branch master and database: master-fms_engine-dev
# git co ihas-fix
# will change the database to ihas-fms_engine-dev
#
# @author Octavian Neamtu, March 2013
# if $3 is 0, then the user checked out a file and not a branch; nothing to do
if [ $3 -eq 0 ]; then
exit
fi
db_config_filepath='config/database.yml'
if [ ! -f $db_config_filepath ]; then
echo 'Could not find database.yml in the config folder! Please create it by copying over database.example.yml.'
exit
fi
# if current db for development is ihas-dev-fms-engine, then the prefix is ihas
current_db_prefix=$(cat $db_config_filepath | grep database | head -1 | awk '{ print $2}' | cut -d- -f1 )
current_branch=$(git rev-parse --abbrev-ref HEAD)
if [ $current_branch == "HEAD" ]; then
echo "Checked out to a non-branch! The config/database.yml will stay unchanged! (right now set for $current_db_prefix)"
exit
fi
# cuts anything following a dash e.g. ihas-master => ihas
current_branch_prefix=$(echo $current_branch | cut -d- -f1)
$(perl -pi -e s,$current_db_prefix,$current_branch_prefix,g $db_config_filepath)
echo "Changed DB config from $current_db_prefix to $current_branch_prefix"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment