Commit 24c7171d authored by Rémy Coutable's avatar Rémy Coutable

Merge branch 'enforce-namespaced-classes' into 'master'

Create Cop to enforce the use of namespaced classes

See merge request gitlab-org/gitlab!51236
parents 7916beef 1808d12a
This diff is collapsed.
# frozen_string_literal: true
module RuboCop
module Cop
module Gitlab
# Cop that enforces use of namespaced classes in order to better identify
# high level domains within the codebase.
# @example
# # bad
# class MyClass
# end
#
# # good
# module MyDomain
# class MyClass
# end
# end
class NamespacedClass < RuboCop::Cop::Cop
MSG = 'Classes must be declared inside a module indicating a product domain namespace. For more info: https://gitlab.com/gitlab-org/gitlab/-/issues/212156'
def_node_matcher :compact_namespaced_class?, <<~PATTERN
(class (const (const ...) ...) ...)
PATTERN
def on_module(node)
@namespaced = true
end
def on_class(node)
return if @namespaced
add_offense(node) unless compact_namespaced_class?(node)
end
end
end
end
end
# frozen_string_literal: true
require 'fast_spec_helper'
require 'rubocop'
require 'rubocop/rspec/support'
require_relative '../../../../rubocop/cop/gitlab/namespaced_class'
RSpec.describe RuboCop::Cop::Gitlab::NamespacedClass do
subject(:cop) { described_class.new }
it 'flags a class definition without namespace' do
expect_offense(<<~SOURCE)
class MyClass
^^^^^^^^^^^^^ #{described_class::MSG}
end
SOURCE
end
it 'flags a class definition with inheritance without namespace' do
expect_offense(<<~SOURCE)
class MyClass < ApplicationRecord
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ #{described_class::MSG}
def some_method
true
end
end
SOURCE
end
it 'does not flag the class definition with namespace in separate lines' do
expect_no_offenses(<<~SOURCE)
module MyModule
class MyClass < ApplicationRecord
end
class MyOtherClass
def other_method
1 + 1
end
end
end
SOURCE
end
it 'does not flag the class definition with nested namespace in separate lines' do
expect_no_offenses(<<~SOURCE)
module TopLevelModule
module NestedModule
class MyClass
end
end
end
SOURCE
end
it 'does not flag the class definition nested inside namespaced class' do
expect_no_offenses(<<~SOURCE)
module TopLevelModule
class TopLevelClass
class MyClass
end
end
end
SOURCE
end
it 'does not flag a compact namespaced class definition' do
expect_no_offenses(<<~SOURCE)
class MyModule::MyClass < ApplicationRecord
end
SOURCE
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment