Module: Tina4::Metrics

Defined in:
lib/tina4/metrics.rb

Constant Summary collapse

CACHE_TTL =
60
OPERATOR_TYPES =
%i[
  on_op
].freeze
OPERAND_TYPES =
%i[
  on_ident on_int on_float on_tstring_content
  on_const on_symbeg on_rational on_imaginary
].freeze

Class Method Summary collapse

Class Method Details

._count_halstead(tokens) ⇒ Object



678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
# File 'lib/tina4/metrics.rb', line 678

def self._count_halstead(tokens)
  stats = {
    operators: 0,
    operands: 0,
    unique_operators: Set.new,
    unique_operands: Set.new
  }

  # Need Set
  require 'set' unless defined?(Set)

  stats[:unique_operators] = Set.new
  stats[:unique_operands] = Set.new

  tokens.each do |(_pos, type, token)|
    case type
    when :on_op
      stats[:operators] += 1
      stats[:unique_operators].add(token)
    when :on_kw
      # Keywords that act as operators
      if %w[and or not defined? return yield raise].include?(token)
        stats[:operators] += 1
        stats[:unique_operators].add(token)
      end
    when :on_ident, :on_const
      stats[:operands] += 1
      stats[:unique_operands].add(token)
    when :on_int, :on_float, :on_rational, :on_imaginary
      stats[:operands] += 1
      stats[:unique_operands].add(token)
    when :on_tstring_content
      stats[:operands] += 1
      stats[:unique_operands].add(token[0, 50])
    end
  end

  stats
end

._cyclomatic_complexity_from_source(source) ⇒ Object



628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
# File 'lib/tina4/metrics.rb', line 628

def self._cyclomatic_complexity_from_source(source)
  cc = 1

  # Use Ripper tokens for accurate counting
  tokens = begin
    Ripper.lex(source)
  rescue StandardError
    return cc
  end

  tokens.each do |(_pos, type, token)|
    case type
    when :on_kw
      case token
      when 'if', 'elsif', 'unless', 'when', 'while', 'until', 'for', 'rescue'
        # Skip modifier forms by checking if it's the first keyword on the line
        # For simplicity, count all — modifiers still add a decision path
        cc += 1
      end
    when :on_op
      case token
      when '&&', '||'
        cc += 1
      when '?'
        # Ternary operator
        cc += 1
      end
    when :on_ident
      # 'and' and 'or' are parsed as identifiers in some contexts
      # but usually as keywords
    end

    # Check for 'and'/'or' as keywords
    if type == :on_kw && (token == 'and' || token == 'or')
      cc += 1
    end
  end

  cc
end

._detect_violations(functions, file_metrics) ⇒ Object



726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
# File 'lib/tina4/metrics.rb', line 726

def self._detect_violations(functions, file_metrics)
  violations = []

  functions.each do |f|
    if f["complexity"] > 20
      violations << {
        "type" => "error",
        "rule" => "high_complexity",
        "message" => "#{f['name']} has cyclomatic complexity #{f['complexity']} (max 20)",
        "file" => f["file"],
        "line" => f["line"]
      }
    elsif f["complexity"] > 10
      violations << {
        "type" => "warning",
        "rule" => "moderate_complexity",
        "message" => "#{f['name']} has cyclomatic complexity #{f['complexity']} (recommended max 10)",
        "file" => f["file"],
        "line" => f["line"]
      }
    end
  end

  file_metrics.each do |fm|
    if fm["loc"] > 500
      violations << {
        "type" => "warning",
        "rule" => "large_file",
        "message" => "#{fm['path']} has #{fm['loc']} LOC (recommended max 500)",
        "file" => fm["path"],
        "line" => 1
      }
    end

    if fm["functions"] > 20
      violations << {
        "type" => "warning",
        "rule" => "too_many_functions",
        "message" => "#{fm['path']} has #{fm['functions']} functions (recommended max 20)",
        "file" => fm["path"],
        "line" => 1
      }
    end

    if fm["maintainability"] < 20
      violations << {
        "type" => "error",
        "rule" => "low_maintainability",
        "message" => "#{fm['path']} has maintainability index #{fm['maintainability']} (min 20)",
        "file" => fm["path"],
        "line" => 1
      }
    elsif fm["maintainability"] < 40
      violations << {
        "type" => "warning",
        "rule" => "moderate_maintainability",
        "message" => "#{fm['path']} has maintainability index #{fm['maintainability']} (recommended min 40)",
        "file" => fm["path"],
        "line" => 1
      }
    end
  end

  violations.sort_by! { |v| [v["type"] == "error" ? 0 : 1, v["file"]] }
  violations
end

._extract_functions(source, tokens, lines) ⇒ Object



514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/tina4/metrics.rb', line 514

def self._extract_functions(source, tokens, lines)
  functions = []
  # Track class/module nesting for method names
  context_stack = []
  i = 0

  while i < lines.length
    stripped = lines[i].strip

    # Track class/module context
    if stripped.match?(/\A(class|module)\s+(\S+)/)
      m = stripped.match(/\A(class|module)\s+(\S+)/)
      class_name = m[2].to_s.split('<').first.to_s.strip
      context_stack.push(class_name) unless class_name.empty?
    end

    # Detect method definitions
    if stripped.match?(/\Adef\s+/)
      method_match = stripped.match(/\Adef\s+(self\.)?(\S+?)(\(.*\))?\s*$/)
      if method_match
        prefix = method_match[1] ? 'self.' : ''
        method_name = prefix + method_match[2]

        # Build full name with class context
        full_name = if context_stack.any?
                      "#{context_stack.last}.#{method_name}"
                    else
                      method_name
                    end

        # Extract arguments
        args = []
        if method_match[3]
          arg_str = method_match[3].gsub(/[()]/, '')
          arg_str.split(',').each do |arg|
            arg = arg.strip.split('=').first.strip.gsub(/^[*&]+/, '')
            args << arg unless arg == 'self' || arg.empty?
          end
        end

        # Find method end and calculate LOC
        method_start = i
        method_end = _find_method_end(lines, i)
        method_loc = method_end - method_start + 1

        # Calculate complexity for this method's body
        method_lines = lines[method_start..method_end]
        method_source = method_lines.join("\n")
        cc = _cyclomatic_complexity_from_source(method_source)

        functions << {
          "name" => full_name,
          "line" => i + 1,
          "complexity" => cc,
          "loc" => method_loc,
          "args" => args
        }
      end
    end

    # Track end keywords for context popping
    if stripped == 'end'
      # Check if this closes a class/module
      # Simple heuristic: count def/class/module opens vs end closes
      # We only pop context when we're back at the class/module level
      indent = lines[i].length - lines[i].lstrip.length
      if indent == 0 && context_stack.any?
        context_stack.pop
      end
    end

    i += 1
  end

  functions
end

._extract_imports(lines) ⇒ Object



499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/tina4/metrics.rb', line 499

def self._extract_imports(lines)
  imports = []
  lines.each do |line|
    stripped = line.strip
    if stripped.match?(/\Arequire\s+/)
      m = stripped.match(/\Arequire\s+['"]([^'"]+)['"]/)
      imports << m[1] if m
    elsif stripped.match?(/\Arequire_relative\s+/)
      m = stripped.match(/\Arequire_relative\s+['"]([^'"]+)['"]/)
      imports << m[1] if m
    end
  end
  imports
end

._files_hash(root) ⇒ Object



484
485
486
487
488
489
490
491
492
493
494
495
496
497
# File 'lib/tina4/metrics.rb', line 484

def self._files_hash(root)
  md5 = Digest::MD5.new
  root_path = Pathname.new(root)
  if root_path.directory?
    Dir.glob(root_path.join('**', '*.rb')).sort.each do |f|
      begin
        md5.update("#{f}:#{File.mtime(f).to_f}")
      rescue StandardError
        # ignore
      end
    end
  end
  md5.hexdigest
end

._find_method_end(lines, start_index) ⇒ Object



591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# File 'lib/tina4/metrics.rb', line 591

def self._find_method_end(lines, start_index)
  depth = 0
  i = start_index
  base_indent = lines[i].length - lines[i].lstrip.length

  while i < lines.length
    stripped = lines[i].strip

    unless stripped.empty? || stripped.start_with?('#')
      # Count block openers
      if stripped.match?(/\b(def|class|module|if|unless|case|while|until|for|begin|do)\b/) &&
         !stripped.match?(/\bend\b/) &&
         !stripped.end_with?(' if ', ' unless ', ' while ', ' until ') &&
         !(stripped.match?(/\bif\b|\bunless\b|\bwhile\b|\buntil\b/) && i != start_index && _is_modifier?(stripped))
        depth += 1
      end

      if stripped == 'end' || stripped.start_with?('end ') || stripped.start_with?('end;')
        depth -= 1
        return i if depth <= 0
      end
    end

    i += 1
  end

  # If we never found the end, return last line
  lines.length - 1
end

._has_matching_test(rel_path) ⇒ Object



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/tina4/metrics.rb', line 426

def self._has_matching_test(rel_path)
  require 'set'

  name = File.basename(rel_path, '.rb')
  # Parent directory name (e.g. "database" from "database/sqlite3_adapter.rb")
  parent_dir = File.dirname(rel_path)
  parent_module = (parent_dir != '.' && !parent_dir.empty?) ? File.basename(parent_dir) : ''

  # Stage 1: Filename matching — name_spec, name_test, test_name patterns
  test_dirs = ['spec', 'spec/tina4', 'test', 'tests']
  test_dirs.each do |td|
    patterns = [
      "#{td}/#{name}_spec.rb",
      "#{td}/#{name}s_spec.rb",
      "#{td}/#{name}_test.rb",
      "#{td}/test_#{name}.rb",
    ]
    # Also check parent-named tests (spec/database_spec.rb covers database/sqlite3_adapter.rb)
    if parent_module && !parent_module.empty? && parent_module != name
      patterns << "#{td}/#{parent_module}_spec.rb"
      patterns << "#{td}/#{parent_module}s_spec.rb"
      patterns << "#{td}/#{parent_module}_test.rb"
      patterns << "#{td}/test_#{parent_module}.rb"
    end
    return true if patterns.any? { |p| File.exist?(p) }
  end

  # Build a dotted/slashed require path for import matching
  # e.g. "lib/tina4/database/sqlite3_adapter.rb" → "tina4/database/sqlite3_adapter"
  path_without_ext = rel_path.sub(/\.rb$/, '')
  # Strip leading lib/ prefix if present
  require_path = path_without_ext.sub(%r{^lib/}, '')

  # Build CamelCase class name from snake_case module name
  # e.g. "sqlite3_adapter" → "Sqlite3Adapter"
  class_name = name.split('_').map(&:capitalize).join

  # Stage 2+3: Content scan — check if any spec/test file references this module
  scan_dirs = ['spec', 'test', 'tests']
  scan_dirs.each do |td|
    next unless Dir.exist?(td)
    Dir.glob(File.join(td, '**', '*.rb')).each do |test_file|
      content = begin
        File.read(test_file, encoding: 'utf-8')
      rescue StandardError
        next
      end
      # Stage 2: require/require_relative path matching
      return true if !require_path.empty? && content.include?(require_path)
      # Stage 3: class name or module name mention
      return true if content.match?(/\b#{Regexp.escape(class_name)}\b/)
      return true if content.match?(/\b#{Regexp.escape(name)}\b/i)
    end
  end

  false
end

._is_modifier?(line) ⇒ Boolean

Returns:

  • (Boolean)


621
622
623
624
625
626
# File 'lib/tina4/metrics.rb', line 621

def self._is_modifier?(line)
  # A rough check: if the keyword is not at the start of the meaningful content,
  # it's likely a modifier (e.g., "return x if condition")
  stripped = line.strip
  !stripped.match?(/\A(if|unless|while|until)\b/)
end

._maintainability_index(halstead_volume, avg_cc, loc) ⇒ Object



718
719
720
721
722
723
724
# File 'lib/tina4/metrics.rb', line 718

def self._maintainability_index(halstead_volume, avg_cc, loc)
  return 100.0 if loc <= 0

  v = [halstead_volume, 1].max
  mi = 171 - 5.2 * Math.log(v) - 0.23 * avg_cc - 16.2 * Math.log(loc)
  [[0.0, mi * 100.0 / 171].max, 100.0].min
end

._resolve_root(root = 'src') ⇒ Object

Pick the right directory to scan.

If the root dir has Ruby files, scan the user’s project code. Otherwise, scan the framework itself — so the bubble chart is never empty.



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/tina4/metrics.rb', line 33

def self._resolve_root(root = 'src')
  root_path = Pathname.new(root)
  if root_path.directory? && !Dir.glob(root_path.join('**', '*.rb')).empty?
    @last_scan_root = File.expand_path(root)
    return root
  end
  # Fallback: scan the framework package itself
  fw_dir = File.dirname(__FILE__)
  @last_scan_root = fw_dir
  fw_dir
end

.file_detail(file_path) ⇒ Object

── File Detail ─────────────────────────────────────────────



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
# File 'lib/tina4/metrics.rb', line 358

def self.file_detail(file_path)
  unless File.exist?(file_path)
    # Try resolving relative to the last scan root (framework mode)
    if @last_scan_root && !@last_scan_root.empty?
      candidate = File.join(@last_scan_root, file_path)
      if File.exist?(candidate)
        file_path = candidate
      end
    end
  end
  unless File.exist?(file_path)
    return { "error" => "File not found: #{file_path}" }
  end

  source = begin
    File.read(file_path, encoding: 'utf-8')
  rescue StandardError => e
    return { "error" => "Read error: #{e.message}" }
  end

  tokens = begin
    Ripper.lex(source)
  rescue StandardError => e
    return { "error" => "Syntax error: #{e.message}" }
  end

  lines = source.lines.map(&:chomp)
  loc = lines.count { |l| !l.strip.empty? && !l.strip.start_with?('#') }

  functions = _extract_functions(source, tokens, lines)
  functions.sort_by! { |f| -f["complexity"] }

  classes = lines.count { |l| l.strip.match?(/\A(class|module)\s+/) }
  imports = _extract_imports(lines)

  warnings = []
  functions.each do |f|
    if f["loc"] <= 1
      warnings << { "type" => "empty_method", "message" => "Method '#{f["name"]}' appears to be empty", "line" => f["line"] }
    end
  end
  if classes > 0 && functions.empty? && loc <= 1
    warnings << { "type" => "empty_class", "message" => "Class/module appears to be empty", "line" => 1 }
  end

  {
    "path" => file_path,
    "loc" => loc,
    "total_lines" => lines.length,
    "classes" => classes,
    "functions" => functions.map { |f|
      {
        "name" => f["name"],
        "line" => f["line"],
        "complexity" => f["complexity"],
        "loc" => f["loc"],
        "args" => f["args"]
      }
    },
    "imports" => imports,
    "warnings" => warnings
  }
end

.full_analysis(root = 'src') ⇒ Object

── Full Analysis (Ripper-based) ────────────────────────────



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/tina4/metrics.rb', line 215

def self.full_analysis(root = 'src')
  # Check if the requested directory exists before falling back
  root_path = Pathname.new(root)
  return { "error" => "Directory not found: #{root}" } unless root_path.directory?

  root = _resolve_root(root)
  root_path = Pathname.new(root)

  current_hash = _files_hash(root)
  now = Time.now.to_f

  if @full_cache_hash == current_hash && !@full_cache_data.nil? && (now - @full_cache_time) < CACHE_TTL
    return @full_cache_data
  end

  rb_files = Dir.glob(root_path.join('**', '*.rb'))

  all_functions = []
  file_metrics = []
  import_graph = {}
  reverse_graph = {}

  rb_files.each do |f|
    source = begin
      File.read(f, encoding: 'utf-8')
    rescue StandardError
      next
    end

    tokens = begin
      Ripper.lex(source)
    rescue StandardError
      next
    end

    rel_path = begin
      Pathname.new(f).relative_path_from(root_path).to_s
    rescue ArgumentError
      f
    end

    lines = source.lines.map(&:chomp)
    loc = lines.count { |l| !l.strip.empty? && !l.strip.start_with?('#') }

    # Extract imports (require/require_relative)
    imports = _extract_imports(lines)
    import_graph[rel_path] = imports

    imports.each do |imp|
      reverse_graph[imp] ||= []
      reverse_graph[imp] << rel_path
    end

    # Parse functions/methods and their complexity
    file_functions = _extract_functions(source, tokens, lines)
    file_complexity = 0

    file_functions.each do |func_info|
      func_info["file"] = rel_path
      all_functions << func_info
      file_complexity += func_info["complexity"]
    end

    # Halstead metrics from tokens
    halstead = _count_halstead(tokens)
    n1 = halstead[:unique_operators].length
    n2 = halstead[:unique_operands].length
    n_total_1 = halstead[:operators]
    n_total_2 = halstead[:operands]
    vocabulary = n1 + n2
    length = n_total_1 + n_total_2
    volume = vocabulary > 0 ? length * Math.log2(vocabulary) : 0.0

    # Maintainability index
    avg_cc = file_functions.empty? ? 0 : file_complexity.to_f / file_functions.length
    mi = _maintainability_index(volume, avg_cc, loc)

    # Coupling
    ce = imports.length
    ca = (reverse_graph[rel_path] || []).length
    instability = (ca + ce) > 0 ? ce.to_f / (ca + ce) : 0.0

    file_metrics << {
      "path" => rel_path,
      "loc" => loc,
      "complexity" => file_complexity,
      "avg_complexity" => avg_cc.round(2),
      "functions" => file_functions.length,
      "maintainability" => mi.round(1),
      "halstead_volume" => volume.round(1),
      "coupling_afferent" => ca,
      "coupling_efferent" => ce,
      "instability" => instability.round(3),
      "has_tests" => _has_matching_test(rel_path),
      "dep_count" => imports.length
    }
  end

  # Update afferent coupling now that all files are processed
  file_metrics.each do |fm|
    fm["coupling_afferent"] = (reverse_graph[fm["path"]] || []).length
    ca = fm["coupling_afferent"]
    ce = fm["coupling_efferent"]
    fm["instability"] = (ca + ce) > 0 ? (ce.to_f / (ca + ce)).round(3) : 0.0
  end

  all_functions.sort_by! { |f| -f["complexity"] }
  file_metrics.sort_by! { |f| f["maintainability"] }

  violations = _detect_violations(all_functions, file_metrics)

  total_cc = all_functions.sum { |f| f["complexity"] }
  avg_cc = all_functions.empty? ? 0 : total_cc.to_f / all_functions.length
  total_mi = file_metrics.sum { |f| f["maintainability"] }
  avg_mi = file_metrics.empty? ? 0 : total_mi.to_f / file_metrics.length

  # Detect if we're scanning framework or project
  framework_dir = File.expand_path(File.dirname(__FILE__))
  resolved_root = File.expand_path(root_path.to_s)
  scanning_framework = resolved_root == framework_dir || resolved_root.start_with?(framework_dir + '/')

  result = {
    "files_analyzed" => file_metrics.length,
    "total_functions" => all_functions.length,
    "avg_complexity" => avg_cc.round(2),
    "avg_maintainability" => avg_mi.round(1),
    "most_complex_functions" => all_functions.first(15),
    "file_metrics" => file_metrics,
    "violations" => violations,
    "dependency_graph" => import_graph,
    "scan_mode" => scanning_framework ? "framework" : "project",
    "scan_root" => resolved_root
  }

  @full_cache_hash = current_hash
  @full_cache_data = result
  @full_cache_time = now

  result
end

.last_scan_rootObject



45
46
47
# File 'lib/tina4/metrics.rb', line 45

def self.last_scan_root
  @last_scan_root
end

.quick_metrics(root = 'src') ⇒ Object

── Quick Metrics ───────────────────────────────────────────



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# File 'lib/tina4/metrics.rb', line 51

def self.quick_metrics(root = 'src')
  # Check if the requested directory exists before falling back
  root_path = Pathname.new(root)
  return { "error" => "Directory not found: #{root}" } unless root_path.directory?

  root = _resolve_root(root)
  root_path = Pathname.new(root)

  rb_files = Dir.glob(root_path.join('**', '*.rb'))
  twig_files = Dir.glob(root_path.join('**', '*.twig')) + Dir.glob(root_path.join('**', '*.erb'))

  migrations_path = Pathname.new('migrations')
  sql_files = if migrations_path.directory?
                Dir.glob(migrations_path.join('**', '*.sql')) + Dir.glob(migrations_path.join('**', '*.rb'))
              else
                []
              end

  scss_files = Dir.glob(root_path.join('**', '*.scss')) + Dir.glob(root_path.join('**', '*.css'))

  total_loc = 0
  total_blank = 0
  total_comment = 0
  total_classes = 0
  total_functions = 0
  file_details = []

  rb_files.each do |f|
    source = begin
      File.read(f, encoding: 'utf-8')
    rescue StandardError
      next
    end

    lines = source.lines.map(&:chomp)
    loc = 0
    blank = 0
    comment = 0
    in_heredoc = false
    heredoc_id = nil
    in_block_comment = false

    lines.each do |line|
      stripped = line.strip

      if stripped.empty?
        blank += 1
        next
      end

      # =begin/=end block comments
      if in_block_comment
        comment += 1
        in_block_comment = false if stripped.start_with?('=end')
        next
      end

      if stripped.start_with?('=begin')
        comment += 1
        in_block_comment = true
        next
      end

      # Heredoc tracking (simplified)
      if in_heredoc
        if stripped == heredoc_id
          in_heredoc = false
        end
        loc += 1
        next
      end

      if stripped.match?(/<<[~-]?['"]?(\w+)['"]?/)
        m = stripped.match(/<<[~-]?['"]?(\w+)['"]?/)
        heredoc_id = m[1]
        in_heredoc = true unless stripped.include?(heredoc_id + stripped[-1].to_s)
        loc += 1
        next
      end

      if stripped.start_with?('#')
        comment += 1
        next
      end

      loc += 1
    end

    # Count classes and methods via simple pattern matching
    classes = lines.count { |l| l.strip.match?(/\A(class|module)\s+/) }
    functions = lines.count { |l| l.strip.match?(/\Adef\s+/) }

    total_loc += loc
    total_blank += blank
    total_comment += comment
    total_classes += classes
    total_functions += functions

    rel_path = begin
      Pathname.new(f).relative_path_from(root_path).to_s
    rescue ArgumentError
      f
    end

    file_details << {
      "path" => rel_path,
      "loc" => loc,
      "blank" => blank,
      "comment" => comment,
      "classes" => classes,
      "functions" => functions
    }
  end

  file_details.sort_by! { |d| -d["loc"] }

  # Route and ORM counts
  route_count = 0
  orm_count = 0
  begin
    if defined?(Tina4::Router) && Tina4::Router.respond_to?(:routes)
      route_count = Tina4::Router.routes.length
    elsif defined?(Tina4::Router) && Tina4::Router.instance_variable_defined?(:@routes)
      route_count = Tina4::Router.instance_variable_get(:@routes).length
    end
  rescue StandardError
    # ignore
  end

  begin
    if defined?(Tina4::ORM)
      orm_count = ObjectSpace.each_object(Class).count { |c| c < Tina4::ORM }
    end
  rescue StandardError
    # ignore
  end

  breakdown = {
    "ruby" => rb_files.length,
    "templates" => twig_files.length,
    "migrations" => sql_files.length,
    "stylesheets" => scss_files.length
  }

  {
    "file_count" => rb_files.length,
    "total_loc" => total_loc,
    "total_blank" => total_blank,
    "total_comment" => total_comment,
    "lloc" => total_loc,
    "classes" => total_classes,
    "functions" => total_functions,
    "route_count" => route_count,
    "orm_count" => orm_count,
    "template_count" => twig_files.length,
    "migration_count" => sql_files.length,
    "avg_file_size" => rb_files.empty? ? 0 : (total_loc.to_f / rb_files.length).round(1),
    "largest_files" => file_details.first(10),
    "breakdown" => breakdown
  }
end