File: ruby-metrics-abc.rb

package info (click to toggle)
gitlab 17.6.5-19
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 629,368 kB
  • sloc: ruby: 1,915,304; javascript: 557,307; sql: 60,639; xml: 6,509; sh: 4,567; makefile: 1,239; python: 406
file content (62 lines) | stat: -rwxr-xr-x 1,807 bytes parent folder | download
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
#!/usr/bin/env ruby
# frozen_string_literal: true

require "rubocop"

# Shows ABC size of methods and blocks for passed files.
#
# See https://docs.rubocop.org/rubocop/cops_metrics.html#metricsabcsize
#
# Usage: scripts/ruby-metrics-abc.rb <ruby file> ...
#   Example: scripts/ruby-metrics-abc.rb app/models/project.rb app/models/user.rb

module Tooling
  class MetricsABC
    extend RuboCop::AST::NodePattern::Macros
    include RuboCop::AST::Traversal

    def run(source)
      version = RUBY_VERSION[/^(\d+\.\d+)/, 1].to_f
      ast = RuboCop::AST::ProcessedSource.new(source, version).ast

      walk(ast)
    end

    def on_def(node)
      print_abc("def #{node.method_name}", node)
    end

    def on_defs(node)
      print_abc("def self.#{node.method_name}", node)
    end

    def on_block(node)
      return unless node.parent&.send_type?

      method_name = node.parent.method_name
      arguments = node.parent.arguments.select { |n| n.sym_type? || n.str_type? }.map(&:source)

      print_abc("#{method_name}(#{arguments.join(', ')})", node)
    end

    private

    def print_abc(prefix, node)
      # https://www.rubydoc.info/gems/rubocop/RuboCop/Cop/Metrics/Utils/AbcSizeCalculator#calculate-instance_method
      abc_score, abc_vector = RuboCop::Cop::Metrics::Utils::AbcSizeCalculator
        .calculate(node, discount_repeated_attributes: true) # rubocop:disable CodeReuse/ActiveRecord -- This is not AR
      puts format("  %d: %s: %.2f %s", node.first_line, prefix, abc_score, abc_vector)
    end
  end

  if ARGV.empty?
    puts "Usage: scripts/ruby-metrics-abc.rb <ruby file> ..."
    puts "  Example: scripts/ruby-metrics-abc.rb app/models/project.rb app/models/user.rb"
  end

  ARGV.each do |file|
    puts "Checking #{file}:"

    MetricsABC.new.run(File.read(file))
  end
end