JM (Jason Meridth)

JM (Jason Meridth)

Learn, Converse, Share

27 Feb 2010

Git post-merge hook to auto-fire rails migrations

I saw Scott Bellware recently write on twitter:

for christmas, i really want a git hook to detect if an update has changes in the db/migrations folder

Cory Foy, Aaron Jensen, and [myself]({{ site.twitter.url }}) all responded in turn. I think Cory and I were quickly searching for which git hook could be used for this idea. Cory found it first and it was the post-merge/post-rebase hooks. I researched the post-merge hook (scroll down to post-merge) and noticed it has no params that we could work with to find out if the last commit had migrations (aka changes/additions to db/migrations folder in a rails project) I came up with the following

#!/usr/bin/env ruby
`rake db:migrate && rake db:test:prepare` if `git diff --name-only HEAD@{1} HEAD`.index("db/migrations")

This will grab the previous diff and look for “db/migrations” in the text. If it’s present, it would auto-run rake db:migrate && rake db:test:migrate. In other words, it will migrate the development database schema, then the test database schema.

Tags