File: migration_collision_checker.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (50 lines) | stat: -rw-r--r-- 1,246 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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
# frozen_string_literal: true

require 'pathname'
require 'open3'

# Checks for class name collisions between Database migrations and Elasticsearch migrations
class MigrationCollisionChecker
  MIGRATION_FOLDERS = %w[db/migrate/*.rb db/post_migrate/*.rb ee/elastic/migrate/*.rb].freeze

  CLASS_MATCHER = /^\s*class\s+:*([A-Z][A-Za-z0-9_]+\S+)/

  ERROR_CODE = 1

  Result = Struct.new(:error_code, :error_message)

  def initialize
    @collisions = Hash.new { |h, k| h[k] = [] }
  end

  def check
    check_for_collisions

    return if collisions.empty?

    Result.new(ERROR_CODE, "\e[31mError: Naming collisions were found between migrations\n\n#{message}\e[0m")
  end

  private

  attr_reader :collisions

  def check_for_collisions
    MIGRATION_FOLDERS.each do |migration_folder|
      Dir.glob(base_path.join(migration_folder)).each do |migration_path|
        klass_name = CLASS_MATCHER.match(File.read(migration_path))[1]
        collisions[klass_name] << migration_path
      end
    end

    collisions.select! { |_, v| v.size > 1 }
  end

  def message
    collisions.map { |klass_name, paths| "#{klass_name}: #{paths.join(', ')}\n" }.join('')
  end

  def base_path
    Pathname.new(File.expand_path('../../', __dir__))
  end
end