comparison vendor/plugins/coderay-0.9.2/lib/coderay/encoders/statistic.rb @ 0:513646585e45

* Import Redmine trunk SVN rev 3859
author Chris Cannam
date Fri, 23 Jul 2010 15:52:44 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:513646585e45
1 module CodeRay
2 module Encoders
3
4 # Makes a statistic for the given tokens.
5 class Statistic < Encoder
6
7 include Streamable
8 register_for :stats, :statistic
9
10 attr_reader :type_stats, :real_token_count
11
12 protected
13
14 TypeStats = Struct.new :count, :size
15
16 def setup options
17 @type_stats = Hash.new { |h, k| h[k] = TypeStats.new 0, 0 }
18 @real_token_count = 0
19 end
20
21 def generate tokens, options
22 @tokens = tokens
23 super
24 end
25
26 def text_token text, kind
27 @real_token_count += 1 unless kind == :space
28 @type_stats[kind].count += 1
29 @type_stats[kind].size += text.size
30 @type_stats['TOTAL'].size += text.size
31 @type_stats['TOTAL'].count += 1
32 end
33
34 # TODO Hierarchy handling
35 def block_token action, kind
36 @type_stats['TOTAL'].count += 1
37 @type_stats['open/close'].count += 1
38 end
39
40 STATS = <<-STATS
41
42 Code Statistics
43
44 Tokens %8d
45 Non-Whitespace %8d
46 Bytes Total %8d
47
48 Token Types (%d):
49 type count ratio size (average)
50 -------------------------------------------------------------
51 %s
52 STATS
53 # space 12007 33.81 % 1.7
54 TOKEN_TYPES_ROW = <<-TKR
55 %-20s %8d %6.2f %% %5.1f
56 TKR
57
58 def finish options
59 all = @type_stats['TOTAL']
60 all_count, all_size = all.count, all.size
61 @type_stats.each do |type, stat|
62 stat.size /= stat.count.to_f
63 end
64 types_stats = @type_stats.sort_by { |k, v| [-v.count, k.to_s] }.map do |k, v|
65 TOKEN_TYPES_ROW % [k, v.count, 100.0 * v.count / all_count, v.size]
66 end.join
67 STATS % [
68 all_count, @real_token_count, all_size,
69 @type_stats.delete_if { |k, v| k.is_a? String }.size,
70 types_stats
71 ]
72 end
73
74 end
75
76 end
77 end