Skip to content

Instantly share code, notes, and snippets.

@pjmartorell
Forked from sunny/git-checkout.rake
Last active September 9, 2016 11:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjmartorell/4562e6ad9d1075df9b92c6640ce719e2 to your computer and use it in GitHub Desktop.
Save pjmartorell/4562e6ad9d1075df9b92c6640ce719e2 to your computer and use it in GitHub Desktop.
Task to checkout a branch in rails and apply or rollback the migrations between the two.
# encoding: UTF-8
#
# $ rake checkout new_branch_name
#
# Via https://gist.github.com/jonlemmon/4076864
#
# 1. Roll back any migrations on your current branch which do not exist on the
# other branch
# 2. Discard any changes to the db/schema.rb file
# 3. Check out the other branch
# 4. Run any new migrations existing in the other branch
# 5. Update your test database
desc "Switch git branches and apply migrations"
task "checkout" do
# We can't checkout if we're dirty
unless `git diff --shortstat`.blank?
$stderr.puts "error: Your local changes would be overwritten by checkout."
$stderr.puts "Please, commit your changes or stash them before you can switch branches."
abort "Aborting"
end
# Last argument trick
# Via http://itshouldbeuseful.wordpress.com/2011/11/07/passing-parameters-to-a-rake-task/
task ARGV.last do ; end
branch_name = ARGV.last
# List migrations
changes = `git diff #{branch_name} --name-status`.lines
migrations = changes.map { |change|
match = /^A.*migrate\/([0-9]+)/.match(change)
match ? match[1] : nil
}.compact
# Drop it like it's hot
begin
should_reconnect = ActiveRecord::Base.connection_pool.active_connection?
migrations.sort.reverse.each do |migration|
ActiveRecord::Migrator.down(ActiveRecord::Migrator.migrations_path, migration.to_i)
end
# Switch
sh "git checkout db/schema.rb"
sh "git checkout #{branch_name}"
ActiveRecord::Migrator.migrate(ActiveRecord::Migrator.migrations_path)
ActiveRecord::Schema.verbose = false
ActiveRecord::Tasks::DatabaseTasks.load_schema_for ActiveRecord::Base.configurations['test'], :ruby, Rails.root.join('db','schema.rb')
ensure
if should_reconnect
ActiveRecord::Base.establish_connection(ActiveRecord::Base.configurations[ActiveRecord::Tasks::DatabaseTasks.env])
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment