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

project_path_helper.rb « cop « rubocop - gitlab.com/gitlab-org/gitlab-foss.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 0d12f2d2b12c06bd2ba0fe76e7c288db226910e1 (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
    class ProjectPathHelper < RuboCop::Cop::Cop
      MSG = 'Use short project path helpers without explicitly passing the namespace: ' \
        '`foo_project_bar_path(project, bar)` instead of ' \
        '`foo_namespace_project_bar_path(project.namespace, project, bar)`.'

      METHOD_NAME_PATTERN = /\A([a-z_]+_)?namespace_project(?:_[a-z_]+)?_(?:url|path)\z/.freeze

      def on_send(node)
        return unless method_name(node).to_s =~ METHOD_NAME_PATTERN

        namespace_expr, project_expr = arguments(node)
        return unless namespace_expr && project_expr

        return unless namespace_expr.type == :send
        return unless method_name(namespace_expr) == :namespace
        return unless receiver(namespace_expr) == project_expr

        add_offense(node, location: :selector)
      end

      def autocorrect(node)
        helper_name = method_name(node).to_s.sub('namespace_project', 'project')

        arguments = arguments(node)
        arguments.shift # Remove namespace argument

        replacement = "#{helper_name}(#{arguments.map(&:source).join(', ')})"

        lambda do |corrector|
          corrector.replace(node.source_range, replacement)
        end
      end

      private

      def receiver(node)
        node.children[0]
      end

      def method_name(node)
        node.children[1]
      end

      def arguments(node)
        node.children[2..]
      end
    end
  end
end