Created
October 24, 2016 03:51
-
-
Save olivierbuffon/bdc4325fc3b99cfdc26bf71d39385bf4 to your computer and use it in GitHub Desktop.
Git post-checkout hook: migrations & bundle autorun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
RED='\033[0;31m' | |
GREEN='\033[0;32m' | |
YELLOW='\033[0;33m' | |
NO_COLOR='\033[0m' | |
CHECKING_OUT_BRANCH=$3 | |
OLD_BRANCH=$1 | |
NEW_BRANCH=$2 | |
function ask_yes_or_no(){ | |
exec < /dev/tty | |
while true; do | |
read | |
if [ "$REPLY" = "" ]; then | |
REPLY='y' | |
fi | |
case $(echo $REPLY | tr '[A-Z]' '[a-z]') in | |
y|yes) echo "yes"; break;; | |
*) echo "no" ; break;; | |
esac | |
done | |
} | |
if [ $CHECKING_OUT_BRANCH -eq 1 ] | |
then | |
FILES_CHANGED=`git diff $OLD_BRANCH $NEW_BRANCH --name-status` | |
BUNDLE_CHANGED=`echo "$FILES_CHANGED" | egrep 'M\tGemfile.lock'` | |
if [ ! -z "$BUNDLE_CHANGED" ]; then | |
echo "\n ===> ⚠️ ${YELLOW}Your ${RED}Gemfile.lock ${YELLOW}has changed. Run 'bundle install'? [Y/n]${NO_COLOR}" | |
if [[ 'yes' == $(ask_yes_or_no) ]]; then | |
bundle | |
else | |
echo " ===> ⚠️ ${YELLOW} 'bundle install' skipped!${NO_COLOR}\n" | |
fi | |
fi | |
MIGRATIONS_REMOVED=`echo "$FILES_CHANGED" | egrep 'D\tdb/migrate/([0-9]+)' | sort -r` | |
MIGRATIONS_ADDED=`echo "$FILES_CHANGED" | egrep 'A\tdb/migrate/([0-9]+)'` | |
if [ ! -z "$MIGRATIONS_REMOVED" ]; then | |
echo "\n ===> 🌀 ${YELLOW}Some migrations need to be rolled back. Run migrations? [Y/n]${NO_COLOR}" | |
if [[ 'yes' == $(ask_yes_or_no) ]]; then | |
echo " ===> 🌀 ${GREEN}Running migrations...${NO_COLOR}\n" | |
for migration in $MIGRATIONS_REMOVED | |
do | |
if [ $migration == "D" ]; then | |
continue | |
fi | |
git checkout "$OLD_BRANCH" -- "$migration" | |
VERSION=`echo "$migration" | cut -d'_' -f1 | cut -d'/' -f3` | |
bundle exec rake db:migrate:down VERSION="$VERSION" | |
git reset | |
rm "$migration" | |
done | |
bundle exec rake db:test:prepare | |
git checkout db/schema.rb | |
else | |
echo " ===> ⚠️ ${YELLOW} Migrations skipped!${NO_COLOR}" | |
fi | |
fi | |
if [ ! -z "$MIGRATIONS_ADDED" ]; then | |
echo "\n ===> 🌀 ${YELLOW}New migrations have been added. Run migrations? [Y/n]${NO_COLOR}" | |
if [[ 'yes' == $(ask_yes_or_no) ]]; then | |
echo " ===> 🌀 ${GREEN}Running migrations...${NO_COLOR}\n" | |
bundle exec rake db:migrate db:test:prepare | |
else | |
echo " ===> ⚠️ ${YELLOW} Migrations skipped!${NO_COLOR}" | |
fi | |
fi | |
echo "\n ===> ✅ ${GREEN} You're good to go!!!${NO_COLOR} 🍺\n" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment