Welcome to mirror list, hosted at ThFree Co, Russian Federation.

versioned_migration_class.rb « migration « cop « rubocop - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: f2e4550c6919cfd22ff6ca7e931171dc1bb3e7d3 (plain)
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
51
52
53
54
55
56
# frozen_string_literal: true

require_relative '../../migration_helpers'

module RuboCop
  module Cop
    module Migration
      class VersionedMigrationClass < RuboCop::Cop::Cop
        include MigrationHelpers

        ENFORCED_SINCE = 2021_09_02_00_00_00

        MSG_INHERIT = 'Don\'t inherit from ActiveRecord::Migration but use Gitlab::Database::Migration[1.0] instead. See https://docs.gitlab.com/ee/development/migration_style_guide.html#migration-helpers-and-versioning.'
        MSG_INCLUDE = 'Don\'t include migration helper modules directly. Inherit from Gitlab::Database::Migration[1.0] instead. See https://docs.gitlab.com/ee/development/migration_style_guide.html#migration-helpers-and-versioning.'

        ACTIVERECORD_MIGRATION_CLASS = 'ActiveRecord::Migration'

        def_node_search :includes_helpers?, <<~PATTERN
        (send nil? :include
          (const
            (const
              (const nil? :Gitlab) :Database) :MigrationHelpers))
        PATTERN

        def on_class(node)
          return unless relevant_migration?(node)
          return unless activerecord_migration_class?(node)

          add_offense(node, location: :expression, message: MSG_INHERIT)
        end

        def on_send(node)
          return unless relevant_migration?(node)

          add_offense(node, location: :expression, message: MSG_INCLUDE) if includes_helpers?(node)
        end

        private

        def relevant_migration?(node)
          in_migration?(node) && version(node) >= ENFORCED_SINCE
        end

        def activerecord_migration_class?(node)
          superclass(node) == ACTIVERECORD_MIGRATION_CLASS
        end

        def superclass(class_node)
          _, *others = class_node.descendants

          others.find { |node| node.const_type? && node&.const_name != 'Types' }&.const_name
        end
      end
    end
  end
end