Skip to content

Instantly share code, notes, and snippets.

@brysgo
Forked from skyriverbend/rails_switch_branch.py
Last active October 5, 2019 11:13
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save brysgo/9980344 to your computer and use it in GitHub Desktop.
Save brysgo/9980344 to your computer and use it in GitHub Desktop.
Post checkout hook for managing rails migrations and bundle install
CHECKING_OUT_BRANCH=$3
OLD_BRANCH=$1
NEW_BRANCH=$2
if [ $CHECKING_OUT_BRANCH -eq 1 ]
then
FILES_CHANGED=`git diff $OLD_BRANCH $NEW_BRANCH --name-status`
MIGRATIONS_REMOVED=`echo "$FILES_CHANGED" | egrep 'D\tdb/migrate/([0-9]+)' | sort -r`
MIGRATIONS_ADDED=`echo "$FILES_CHANGED" | egrep 'A\tdb/migrate/([0-9]+)'`
# CHECK IF WE NEED TO DO A BUNDLE
BUNDLE_CHANGED=`echo "$FILES_CHANGED" | egrep 'M\tGemfile.lock'`
if [ ! -z "$BUNDLE_CHANGED" ]; then
echo "Your Gemfile.lock has changed, running bundle"
bundle
fi
if [ ! -z "$MIGRATIONS_REMOVED" ]; then
echo "Rolling back missing migrations"
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
fi
if [ ! -z "$MIGRATIONS_ADDED" ]; then
echo "New migrations have been added running migrations"
bundle exec rake db:migrate db:test:prepare
fi
fi
Copy link

ghost commented Apr 4, 2014

@brysgo
Copy link
Author

brysgo commented Apr 4, 2014

Add this to .git/hooks/post-checkout and it will manage your migrations as you use git normally

@skyriverbend
Copy link

Awesome!

@brysgo
Copy link
Author

brysgo commented Apr 8, 2014

Thanks!

@brysgo
Copy link
Author

brysgo commented Apr 10, 2014

This grew out of a gist, it now lives at brysgo/git-rails

@fikriauliya
Copy link

Small note for readers:

After copying to .git/hooks/post-checkout, run
chmod u+x .git/hooks/post-checkout
to make it executable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment