Created
December 19, 2023 19:34
-
-
Save willdowglas/7e56f2190b2a8c08dbffef6210c4b82c to your computer and use it in GitHub Desktop.
Checks rails migrations bewteen branches, rollbacks them and checkout to target branch
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
| # Formats output to a bold, green text | |
| def puts(*) # Formats output | |
| print("\e[1m\e[32m") # formats text to bold, green | |
| super | |
| print("\e[22m\e[0m") # clear format | |
| end | |
| # Outputs error message and exits program with failure(1) | |
| def fail(message) | |
| Kernel.puts "\e[1m\e[31m#{message}\e[22m\e[0m" # bold, red | |
| exit false | |
| end | |
| puts '$ git fetch --all' | |
| system 'git fetch --all' | |
| default_branch = 'master' | |
| current_branch = `git rev-parse --abbrev-ref HEAD`.strip | |
| input_branch = ARGV[0] | |
| target_branch = input_branch || default_branch | |
| if input_branch | |
| `git show-ref #{input_branch}` | |
| fail('Input Branch not found') if $?.exitstatus == 1 | |
| end | |
| puts "Finding Diff migrations between" \ | |
| "\n\tCurrent -> #{current_branch}" \ | |
| "\n\tTarget -> #{target_branch}" | |
| migrations = `git diff #{target_branch} --name-status | egrep db/migrate` | |
| migrations = migrations.split("\n").map{ |str| str.delete_prefix("A\tdb/migrate/") } | |
| if migrations.any? | |
| puts | |
| migrations.each { |migration| puts " #{migration}" } | |
| puts | |
| puts 'Rollbacking "LIFO"...' | |
| migrations.reverse.each do |migration| | |
| version = migration.gsub(/[^\d]/, '') | |
| `bundle exec rake db:migrate:down VERSION=#{version}` | |
| puts "#{version} Down." | |
| end | |
| puts 'Rollback Done.' | |
| `git restore db/schema.rb` | |
| else | |
| puts 'No migrations to rollback.' | |
| end | |
| puts "Checking out to #{target_branch}..." | |
| puts "$ git checkout #{target_branch}" | |
| `git checkout #{target_branch}` | |
| fail('Checkout failed. Please check error message above.') if $?.exitstatus == 1 | |
| puts "Done." |
Author
Author
$ ruby checkout_and_rollback.rb
Output
$ git fetch --all
Fetching origin
Finding Diff migrations between
Current -> w...
Target -> master
20231122194358_a...ms.rb
20231123125739_a...ns.rb
20231123134454_a...ds.rb
20231127141011_a...es.rb
Rollbacking "LIFO"...
20231127141011 Down.
20231123134454 Down.
20231123125739 Down.
20231122194358 Down.
Rollback Done.
Checking out to master...
$ git checkout master
Switched to branch 'master'
Done.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
If no arg is passed, it will assume
masteras target branch.If you use
maininstead ofmaster, changedefault_branchvariable at L17.Compatibility
Made and using with Ruby 2.5.1.