-
-
Save tomoguisuru/b5d88094f6bf35879241 to your computer and use it in GitHub Desktop.
This file contains hidden or 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/bash | |
#!/usr/local/bin/python | |
""" | |
To use this script, you must be in the root directory of a Rails project that | |
is using git. You should also make sure that your directory does not contain any | |
uncommitted changes. Then run: | |
$ python rails_switch_branch.py name_of_another_branch | |
Running the above will do the following: | |
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 | |
TODO: | |
- Check if git directory is dirty. If so, do not run. | |
""" | |
import sys | |
import subprocess | |
import re | |
BRANCH_NAME = sys.argv[1] | |
sh_command = "git status" | |
is_dirty = True if re.search("nothing to commit", subprocess.check_output(sh_command.split())) == None else False | |
if is_dirty: | |
print "*** There are un committed changes. Aborting *** " | |
sys.exit() | |
print "*** Switching from current branch to: " + BRANCH_NAME | |
files_changed = subprocess.check_output(("git diff " + BRANCH_NAME + " --name-status").split()) | |
migrations = re.findall("A\\tdb/migrate/([0-9]+)", files_changed) | |
for migration in reversed(migrations): | |
sh_command = "bundle exec rake db:migrate:down VERSION=" + migration | |
print "*** Running: " + sh_command | |
subprocess.call(sh_command.split()) | |
print "*** Discarding any changes to db/schema.rb" | |
subprocess.call("git reset --hard".split()) | |
subprocess.call(("git switch " + BRANCH_NAME).split()) | |
print "*** Running: bundle install" | |
subprocess.call("bundle install".split()) | |
print "*** Running: bundle exec rake db:migrate" | |
subprocess.call("bundle exec rake db:migrate".split()) | |
print "*** Clear the temp directory and log files" | |
subprocess.call("bundle exec rake tmp:clear".split()) | |
subprocess.call("bundle exec rake log:clear".split()) | |
print "*** Running: test migration" | |
subprocess.call("rake db:test:prepare".split()) | |
print "*** Discarding any changes to db/schema.rb" | |
subprocess.call("git reset --hard".split()) | |
print '*** Successfully switched branches and migrated to "' + BRANCH_NAME + '"' | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment