summaryrefslogtreecommitdiff
path: root/rubocop
diff options
context:
space:
mode:
authorDouwe Maan <douwe@selenight.nl>2017-07-04 18:57:13 -0500
committerDouwe Maan <douwe@selenight.nl>2017-07-05 11:12:00 -0500
commit873b40555b582638992e7cdeb2081c29d08cae05 (patch)
treee0bef2f35e1c5a44c83b7680dfa1d4c05797048d /rubocop
parentfe13f110412d85c05dc68e5ee1db499f681bf722 (diff)
downloadgitlab-ce-873b40555b582638992e7cdeb2081c29d08cae05.tar.gz
Add ProjectPathHelper cop
Diffstat (limited to 'rubocop')
-rw-r--r--rubocop/cop/project_path_helper.rb51
-rw-r--r--rubocop/rubocop.rb1
2 files changed, 52 insertions, 0 deletions
diff --git a/rubocop/cop/project_path_helper.rb b/rubocop/cop/project_path_helper.rb
new file mode 100644
index 00000000000..3e1ce71ac06
--- /dev/null
+++ b/rubocop/cop/project_path_helper.rb
@@ -0,0 +1,51 @@
+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)`.'.freeze
+
+ 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, :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..-1]
+ end
+ end
+ end
+end
diff --git a/rubocop/rubocop.rb b/rubocop/rubocop.rb
index 55d7708fa8c..69b4b29507c 100644
--- a/rubocop/rubocop.rb
+++ b/rubocop/rubocop.rb
@@ -3,6 +3,7 @@ require_relative 'cop/gem_fetcher'
require_relative 'cop/activerecord_serialize'
require_relative 'cop/redirect_with_status'
require_relative 'cop/polymorphic_associations'
+require_relative 'cop/project_path_helper'
require_relative 'cop/migration/add_column'
require_relative 'cop/migration/add_column_with_default_to_large_table'
require_relative 'cop/migration/add_concurrent_foreign_key'