Class: RebaseMigrations

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_rebase_migrations.rb

Constant Summary collapse

SKIP_REBASE =
'_skip_rebase_'
MIGRATIONS_DIR =
'db/migrate/'
MIGRATION_NAME_RE =
/\A(\d+)(.*)\z/
TIME_FORMAT =
'%Y%m%d%H%M%S'

Instance Method Summary collapse

Instance Method Details

#mainObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rails_rebase_migrations.rb', line 16

def main
  ref, options = parse_args

  out = subprocess('git', 'ls-files', '--', MIGRATIONS_DIR)
  all_migrations = out.lines(chomp: true).to_a.sort

  out = subprocess('git', 'ls-tree', '--name-only', ref, '--', MIGRATIONS_DIR)
  ref_migrations = out.lines(chomp: true).to_a.sort

  starting_index = ref_migrations.length

  basename = File.basename(ref_migrations.last)
  match = MIGRATION_NAME_RE.match(basename)
  last_timestamp = match[1]
  now = [Time.now.utc, Time.strptime("#{last_timestamp}Z", "#{TIME_FORMAT}%Z")].max.to_i

  all_migrations.each do |path|
    next if ref_migrations.include?(path)

    basename = File.basename(path)
    match = MIGRATION_NAME_RE.match(File.basename(path))
    migration_timestamp = match[1]
    migration_name_base = match[2]
    next if migration_name_base.start_with?(SKIP_REBASE)

    if options[:check]
      index = all_migrations.index(path)
      if index < starting_index
        skip_migration_name = "#{migration_timestamp}#{SKIP_REBASE}#{migration_name_base[1..]}"

        warn <<~MSG
          Migration #{basename} is out of order. It should come after
          pre-existing migrations. To fix, run the command:

            $ bundle exec rebase-migrations

          If the migration is intentionally out of order, add the magic
          string "#{SKIP_REBASE}" to the beginning of the migration name:

            $ git mv #{path} #{MIGRATIONS_DIR}#{skip_migration_name}
        MSG

        exit 1
      end
    else
      # Add 120s so the new migrations maintain the same order and provides
      # room between the migrations to inject new ones.
      now += 120

      new_timestamp = Time.at(now, in: 'Z').strftime(TIME_FORMAT)
      new_migration_name = "#{new_timestamp}#{migration_name_base}"
      subprocess('git', 'mv', path, "#{MIGRATIONS_DIR}#{new_migration_name}")
    end
  end

  return if options[:check]

  # Regenerate db/schema.rb
  system('rails', 'db:drop', 'db:create', 'db:migrate', exception: true)
  subprocess('git', 'add', 'db/schema.rb')
end