forked from rubocop/rubocop
-
Notifications
You must be signed in to change notification settings - Fork 0
/
method_complexity.rb
70 lines (57 loc) · 1.68 KB
/
method_complexity.rb
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# frozen_string_literal: true
module RuboCop
module Cop
# @api private
#
# This module handles measurement and reporting of complexity in methods.
module MethodComplexity
include ConfigurableMax
include IgnoredMethods
include Metrics::Utils::RepeatedCsendDiscount
extend NodePattern::Macros
def on_def(node)
return if ignored_method?(node.method_name)
check_complexity(node, node.method_name)
end
alias on_defs on_def
def on_block(node)
define_method?(node) do |name|
return if ignored_method?(name)
check_complexity(node, name)
end
end
private
def_node_matcher :define_method?, <<~PATTERN
(block
(send nil? :define_method ({sym str} $_))
args
_)
PATTERN
def check_complexity(node, method_name)
# Accepts empty methods always.
return unless node.body
max = cop_config['Max']
reset_repeated_csend
complexity, abc_vector = complexity(node.body)
return unless complexity > max
msg = format(self.class::MSG,
method: method_name,
complexity: complexity,
abc_vector: abc_vector,
max: max)
add_offense(node, message: msg) do
self.max = complexity.ceil
end
end
def complexity(body)
body.each_node(:lvasgn, *self.class::COUNTED_NODES).reduce(1) do |score, node|
if node.lvasgn_type?
reset_on_lvasgn(node)
next score
end
score + complexity_score_for(node)
end
end
end
end
end