summaryrefslogtreecommitdiff
path: root/rubocop/cop/avoid_route_redirect_leading_slash.rb
blob: d66e434dc9c61086611092e30d3626b5e61b4c17 (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
# frozen_string_literal: true

module RuboCop
  module Cop
    # Checks for a leading '/' in route redirects
    # For more information see: https://gitlab.com/gitlab-org/gitlab-foss/issues/50645
    #
    # @example
    #   # bad
    #   root to: redirect('/-/instance/statistics/dev_ops_score')
    #
    #   # good
    #   root to: redirect('-/instance/statistics/dev_ops_score')
    #

    class AvoidRouteRedirectLeadingSlash < RuboCop::Cop::Cop
      MSG = 'Do not use a leading "/" in route redirects'

      def_node_matcher :leading_slash_in_redirect?, <<~PATTERN
        (send nil? :redirect (str #has_leading_slash?))
      PATTERN

      def on_send(node)
        return unless in_routes?(node)
        return unless leading_slash_in_redirect?(node)

        add_offense(node)
      end

      def has_leading_slash?(str)
        str.start_with?("/")
      end

      def in_routes?(node)
        path = node.location.expression.source_buffer.name
        dirname = File.dirname(path)
        filename = File.basename(path)
        dirname.end_with?('config/routes') || filename.end_with?('routes.rb')
      end

      def autocorrect(node)
        lambda do |corrector|
          corrector.replace(node.loc.expression, remove_leading_slash(node))
        end
      end

      def remove_leading_slash(node)
        node.source.sub('/', '')
      end
    end
  end
end