Skip to content

Instantly share code, notes, and snippets.

@floriandejonckheere
Created January 7, 2022 14:47
Show Gist options
  • Save floriandejonckheere/a116eaecb4bb9ce6dba150a125cdf2e8 to your computer and use it in GitHub Desktop.
Save floriandejonckheere/a116eaecb4bb9ce6dba150a125cdf2e8 to your computer and use it in GitHub Desktop.
Resolve schema migration merge conflicts
#!/usr/bin/env ruby
# frozen_string_literal: true
#
# This script automatically resolves merge conflicts in the schema migrations
# part of structure.sql. It sorts, deduplicates and reformats all migration
# entries in the file.
#
# Example:
#
# ('20211222080000'),
# ('20211222120729'),
# ('20211223150854'),
# <<<<<<< HEAD
# ('20220104100925'),
# =======
# ('20211223181009'),
# >>>>>>> e16b8ffc8 (Add started_at column to session)
# ('20220106134342');
#
# Will result in:
#
# ('20211222120729'),
# ('20211223150854'),
# ('20211223181009'),
# ('20220104100925'),
# ('20220106134342');
#
# Read structure.sql
structure = File.readlines("db/structure.sql")
# Find schema_migrations line
index = structure.index { |l| l.start_with?("INSERT INTO \"schema_migrations\"") }
abort("Merge conflict found before schema migrations. Please resolve the conflicts and rerun this script.") if structure[..index].any? { |l| l.start_with?("<<<<<<<", "=======", ">>>>>>>") }
migrations = structure[(index + 1)..]
# Drop trailing empty lines
migrations.reject!(&:empty?)
# Drop git conflict delimiters
migrations.reject! { |l| l.start_with?("<<<<<<<", "=======", ">>>>>>>") }
# Replace semicolons with commas
migrations.map! { |l| l.tr(";", ",") }
# Sort and deduplicate
migrations.sort!
migrations.uniq!
# Add semicolon to last statement
migrations[-1].tr!(",", ";")
# Write structure.sql
File.write("db/structure.sql", (structure[..index] + migrations).join)
puts "Resolved merge conflicts in db/structure.sql"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment