Created
August 24, 2017 12:20
-
-
Save olly/d538fe2f4bfa5c7d817cb7de449ff824 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
#!/usr/bin/env ruby | |
# | |
# usage: rails-merge-db-schema <current-file> <base-file> <other-file> <marker-size> | |
# | |
# install: | |
# | |
# $ git config --global merge.railsschema.name "newer Rails schema version" | |
# $ git config --global merge.railsschema.driver "rails-merge-db-schema %A %O %B %L" | |
exit 1 if ARGV.size != 4 | |
current_file, base_file, other_file, marker_size, _ = ARGV | |
# perform a standard git merge | |
system('git', 'merge-file', "--marker-size=#{marker_size}", current_file, base_file, other_file) | |
# build a regular expression which matches a schema defintion merge | |
# conflict. Example: | |
# | |
# <<<<<<< .merge_file_p2F2ih | |
# ActiveRecord::Schema.define(version: 20161011162735) do | |
# ======= | |
# ActiveRecord::Schema.define(version: 20161006133305) do | |
# >>>>>>> .merge_file_nfurhQ | |
# | |
MERGE_CONFLICT_START = /<{#{marker_size}} #{current_file}/ | |
MERGE_CONFLICT_SEPERATOR = /={#{marker_size}}/ | |
MERGE_CONFLICT_END = />{#{marker_size}} #{other_file}/ | |
SCHEMA_DEFINITION = /ActiveRecord::Schema\.define\(version: (\d+)\) do/ | |
SCHEMA_DEFINITION_CONFLICT_MATCHER = / | |
#{MERGE_CONFLICT_START} | |
#{SCHEMA_DEFINITION} | |
#{MERGE_CONFLICT_SEPERATOR} | |
#{SCHEMA_DEFINITION} | |
#{MERGE_CONFLICT_END} | |
/ | |
# resolve a schema definition merge conflict by choosing the latest | |
# version number | |
merge = File.read(current_file).sub!(SCHEMA_DEFINITION_CONFLICT_MATCHER) do | |
a, b = Integer($1), Integer($2) | |
latest_version = [a, b].max | |
"\nActiveRecord::Schema.define(version: #{latest_version}) do\n" | |
end | |
# write the resulting merge back to the current file | |
File.open(current_file, 'w') do |f| | |
f.write(merge) | |
end | |
# if there are other merge conflicts remaining, exit with code 1 | |
if merge =~ MERGE_CONFLICT_START | |
exit 1 | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment