summaryrefslogtreecommitdiff
path: root/rubocop/cop/api/base.rb
blob: 85b19e9a83383eb8a5ea6f2f3a1a1dbd44c54ed8 (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
# frozen_string_literal: true

module RuboCop
  module Cop
    module API
      class Base < RuboCop::Cop::Cop
        # This cop checks that APIs subclass API::Base.
        #
        # @example
        #
        # # bad
        # module API
        #   class Projects < Grape::API
        #   end
        # end
        #
        # module API
        #   class Projects < Grape::API::Instance
        #   end
        # end
        #
        # # good
        # module API
        #   class Projects < ::API::Base
        #   end
        # end
        MSG = 'Inherit from ::API::Base instead of Grape::API::Instance or Grape::API. ' \
              'For more details check https://gitlab.com/gitlab-org/gitlab/-/issues/215230.'

        def_node_matcher :grape_api, '(const (const {nil? (cbase)} :Grape) :API)'
        def_node_matcher :grape_api_definition, <<~PATTERN
          (class
            (const _ _)
            {#grape_api (const #grape_api :Instance)}
            ...
          )
        PATTERN

        def on_class(node)
          grape_api_definition(node) do
            add_offense(node.children[1])
          end
        end

        def autocorrect(node)
          lambda do |corrector|
            corrector.replace(node, '::API::Base')
          end
        end
      end
    end
  end
end