Class: RuboCop::Cop::Homebrew::SingleUseMethod Private
- Includes:
- ProjectIndexHelp
- Defined in:
- rubocops/single_use_method.rb
Overview
This class is part of a private API. This class may only be used in the Homebrew/brew repository. Third parties should avoid using this class if possible, as it may be removed or changed without warning.
Checks for methods that are only called once and so can be inlined into their caller.
Formula classes are self-contained, so only references in the same file are counted. Elsewhere, only non-public methods are checked and the project index must contain no other definition of or reference to the method name, including a symbol or symbol hash key.
Any other mention of the method name in the file, e.g. a symbol passed to send or the
name inside a string, counts as a reference.
Methods using return, yield, super, on_* blocks, memoisation or a block parameter are
skipped as they cannot be moved into their caller unchanged. So are methods with a rescue or
ensure called in a condition or rescuing into a variable name the caller already uses, and
methods whose enclosing methods or blocks would then exceed an enabled Metrics length,
ABC size, complexity or nesting limit.
Example
# bad
def install
system "make", *make_args
end
def make_args
["PREFIX=#{prefix}"]
end
# good
def install
system "make", "PREFIX=#{prefix}"
end
Defined Under Namespace
Classes: BlockNestingScore, CyclomaticComplexityScore, PerceivedComplexityScore
Constant Summary collapse
- MSG =
This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.
"Inline `%<method>s` into its only caller."- IDENTIFIER_PATTERN =
This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.
/[a-zA-Z_]\w*[?!=]?/- NAME_PREFIX_PATTERN =
This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.
/[a-zA-Z_]\w*\z/- SYMBOL_PATTERN =
This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.
A symbol, e.g.
receive(:name), or a symbol hash key, e.g.receive_messages(name: value). /(?<![:\w]):"?([a-zA-Z_]\w*[?!=]?)|(?<![:\w])([a-zA-Z_]\w*[?!]?):(?!:)/- FORMULA_HOOK_METHODS =
This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.
Homebrew also calls these formula methods by name, so they must stay methods.
[:caveats, :fetch, :install, :post_install, :test].freeze
Class Attribute Summary collapse
-
.cached_index_name_counts ⇒ Array<(Rubydex::Graph, Hash{String => Integer}, Hash{String => Integer}, Set<String>)>?
private
Counting names across the project index is shared by every file checked against it.
Instance Method Summary collapse
- #on_def(node) ⇒ void private
Methods included from ProjectIndexHelp
Class Attribute Details
.cached_index_name_counts ⇒ Array<(Rubydex::Graph, Hash{String => Integer}, Hash{String => Integer}, Set<String>)>?
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
Counting names across the project index is shared by every file checked against it.
75 76 77 |
# File 'rubocops/single_use_method.rb', line 75 def cached_index_name_counts @cached_index_name_counts end |
Instance Method Details
#on_def(node) ⇒ void
This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.
This method returns an undefined value.
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 |
# File 'rubocops/single_use_method.rb', line 79 def on_def(node) return if node.each_ancestor(:any_def, :any_block, :sclass).any? # These behave differently once moved into the caller. return if node.each_descendant(:return, :yield, :super, :zsuper).any? # `FormulaAudit/OnSystemConditionals` disallows `on_*` blocks in e.g. `install`. return if node.each_descendant(:block).any? { |block| block.method_name.start_with?("on_") } # Memoised values are kept between calls, e.g. from a loop, so must stay in a method. return if node.each_descendant(:or_asgn).any? { |assignment| assignment.children.first.ivasgn_type? } # A block parameter has no equivalent once the method is inlined. return if node.arguments.any?(&:blockarg_type?) || node.each_descendant(:send).any? { |send| send.method?(:block_given?) } namespace = node.each_ancestor(:class, :module).first return if namespace.nil? return if FORMULA_HOOK_METHODS.include?(node.method_name) && formula_class?(namespace) name = node.method_name references = processed_source.ast&.each_node(:call, :def, :sym, :str, :dstr, :dsym)&.select do |reference| next false if reference.equal?(node) if reference.is_a?(RuboCop::AST::DefNode) || reference.is_a?(RuboCop::AST::SendNode) reference.method?(name) elsif reference.is_a?(RuboCop::AST::SymbolNode) reference.value == name elsif reference.dstr_type? || reference.dsym_type? # `send(:"format_#{type}")` may call any method starting with `format_`. first = reference.children.first # Matching raises on string literals with invalid byte sequences. prefix = first.value.scrub[NAME_PREFIX_PATTERN] if first.is_a?(RuboCop::AST::StrNode) prefix.present? && name.start_with?(prefix) elsif reference.is_a?(RuboCop::AST::StrNode) reference.value.scrub.scan(IDENTIFIER_PATTERN).include?(name.to_s) end end return if references&.length != 1 call = references.first return unless call.is_a?(RuboCop::AST::SendNode) return if call.receiver && !call.receiver&.self_type? return unless call.each_ancestor(:class, :module).first.equal?(namespace) return if call.each_ancestor(:def).include?(node) # A method-level `rescue` or `ensure` needs a `begin` block once inlined, which reads badly in a condition. in_condition = [call, *call.each_ancestor].each_cons(2) .take_while { |_, parent| !parent.type?(:any_def, :any_block) } .any? do |child, parent| next true if parent.operator_keyword? parent.type?(:if, :while, :until, :case) && parent.children.first.equal?(child) end return if in_condition && node.body&.type?(:rescue, :ensure) # `Naming/RescuedExceptionsVariableName` stops renaming a rescued variable the caller already uses. rescued_names = node.each_descendant(:resbody).filter_map { |resbody| resbody.children[1]&.children&.first } caller_names = call.each_ancestor(:any_def, :any_block).to_a.last &.each_descendant(:lvasgn, :argument)&.map { |local| local.children.first } return if caller_names&.intersect?(rescued_names) return if !formula_class?(namespace) && !single_use_in_project_index?(namespace, name) # Inlining should not push any enclosing method or block over an enabled `Metrics` limit # that would then need suppressing. return if call.each_ancestor(:any_def, :any_block).any? do |scope| if scope.is_a?(RuboCop::AST::BlockNode) next !scope.class_constructor? && inlining_exceeds_length?("Metrics/BlockLength", scope, node) end next false unless scope.is_a?(RuboCop::AST::DefNode) next true if inlining_exceeds_length?("Metrics/MethodLength", scope, node) max_abc = enabled_metrics_max("Metrics/AbcSize", scope) discount_repeated_attributes = !config.for_cop("Metrics/AbcSize")["CountRepeatedAttributes"] abc = [scope, node].sum do |method| Metrics::Utils::AbcSizeCalculator.calculate(method, discount_repeated_attributes:).first end next true if max_abc && abc > max_abc { "Metrics/CyclomaticComplexity" => CyclomaticComplexityScore, "Metrics/PerceivedComplexity" => PerceivedComplexityScore, }.any? do |cop_name, score_class| max_complexity = enabled_metrics_max(cop_name, scope) next false if max_complexity.nil? score = score_class.new(config) complexity = [scope, node].sum do |method| score.reset_repeated_csend body = method.body body ? score.complexity(body) : 1 end # Each method starts from a score of 1 but the inlined result only has one. complexity - 1 > max_complexity end end max_nesting = config.for_enabled_cop("Metrics/BlockNesting")["Max"] if max_nesting nesting = BlockNestingScore.new(config) nests = ->(nested) { nesting.consider_node?(nested) && nesting.count_if_block?(nested) } method_nesting = node.each_descendant.select(&nests).map do |nested| nested.each_ancestor.take_while { |ancestor| !ancestor.equal?(node) }.count(&nests) + 1 end.max.to_i return if call.each_ancestor.count(&nests) + method_nesting > max_nesting end add_offense(node.loc.keyword.join(node.loc.name), message: format(MSG, method: name)) end |