From 0896d6942d30e3cc743c85dcc8fe9699a2a02289 Mon Sep 17 00:00:00 2001 From: Sanad Liaquat Date: Fri, 21 Sep 2018 14:10:20 +0000 Subject: Fix leading slash in redirects and add cop --- rubocop/cop/avoid_route_redirect_leading_slash.rb | 52 +++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 rubocop/cop/avoid_route_redirect_leading_slash.rb (limited to 'rubocop/cop') diff --git a/rubocop/cop/avoid_route_redirect_leading_slash.rb b/rubocop/cop/avoid_route_redirect_leading_slash.rb new file mode 100644 index 00000000000..7ac1c881269 --- /dev/null +++ b/rubocop/cop/avoid_route_redirect_leading_slash.rb @@ -0,0 +1,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-ce/issues/50645 + # + # @example + # # bad + # root to: redirect('/-/instance/statistics/conversational_development_index') + # + # # good + # root to: redirect('-/instance/statistics/conversational_development_index') + # + + 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 -- cgit v1.2.3