alexrothenberg-metric_fu 1.0.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (47) hide show
  1. data/HISTORY +119 -0
  2. data/MIT-LICENSE +22 -0
  3. data/Manifest.txt +25 -0
  4. data/README +1 -0
  5. data/Rakefile +46 -0
  6. data/TODO +14 -0
  7. data/lib/base/base_template.rb +134 -0
  8. data/lib/base/configuration.rb +187 -0
  9. data/lib/base/generator.rb +156 -0
  10. data/lib/base/md5_tracker.rb +52 -0
  11. data/lib/base/report.rb +100 -0
  12. data/lib/generators/churn.rb +86 -0
  13. data/lib/generators/flay.rb +33 -0
  14. data/lib/generators/flog.rb +131 -0
  15. data/lib/generators/rcov.rb +80 -0
  16. data/lib/generators/reek.rb +36 -0
  17. data/lib/generators/roodi.rb +30 -0
  18. data/lib/generators/saikuro.rb +216 -0
  19. data/lib/generators/stats.rb +43 -0
  20. data/lib/metric_fu.rb +20 -0
  21. data/lib/templates/standard/churn.html.erb +30 -0
  22. data/lib/templates/standard/default.css +64 -0
  23. data/lib/templates/standard/flay.html.erb +33 -0
  24. data/lib/templates/standard/flog.html.erb +52 -0
  25. data/lib/templates/standard/index.html.erb +38 -0
  26. data/lib/templates/standard/rcov.html.erb +42 -0
  27. data/lib/templates/standard/reek.html.erb +41 -0
  28. data/lib/templates/standard/roodi.html.erb +28 -0
  29. data/lib/templates/standard/saikuro.html.erb +83 -0
  30. data/lib/templates/standard/standard_template.rb +26 -0
  31. data/lib/templates/standard/stats.html.erb +54 -0
  32. data/spec/base/base_template_spec.rb +140 -0
  33. data/spec/base/configuration_spec.rb +303 -0
  34. data/spec/base/generator_spec.rb +182 -0
  35. data/spec/base/md5_tracker_spec.rb +57 -0
  36. data/spec/base/report_spec.rb +139 -0
  37. data/spec/generators/churn_spec.rb +152 -0
  38. data/spec/generators/flay_spec.rb +101 -0
  39. data/spec/generators/flog_spec.rb +200 -0
  40. data/spec/generators/reek_spec.rb +59 -0
  41. data/spec/generators/saikuro_spec.rb +63 -0
  42. data/spec/generators/stats_spec.rb +74 -0
  43. data/spec/spec_helper.rb +28 -0
  44. data/tasks/metric_fu.rake +15 -0
  45. data/tasks/railroad.rake +39 -0
  46. data/vendor/saikuro/saikuro.rb +1214 -0
  47. metadata +113 -0
@@ -0,0 +1,156 @@
1
+ module MetricFu
2
+
3
+ # = Generator
4
+ #
5
+ # The Generator class is an abstract class that provides the
6
+ # skeleton for producing different types of metrics.
7
+ #
8
+ # It drives the production of the metrics through a template
9
+ # method - #generate_report(options={}). This method calls
10
+ # #emit, #analyze and #to_h in order to produce the metrics.
11
+ #
12
+ # To implement a concrete class to generate a metric, therefore,
13
+ # the class must implement those three methods.
14
+ #
15
+ # * #emit should take care of running the metric tool and
16
+ # gathering its output.
17
+ # * #analyze should take care of manipulating the output from
18
+ # #emit and making it possible to store it in a programmatic way.
19
+ # * #to_h should provide a hash representation of the output from
20
+ # #analyze ready to be serialized into yaml at some point.
21
+ #
22
+ # == Pre-conditions
23
+ #
24
+ # Based on the class name of the concrete class implementing a
25
+ # Generator, the Generator class will create a 'metric_directory'
26
+ # named after the class under the MetricFu.scratch_directory, where
27
+ # any output from the #emit method should go.
28
+ #
29
+ # It will also create the MetricFu.output_directory if neccessary, and
30
+ # in general setup the directory structure that the MetricFu system
31
+ # expects.
32
+ class Generator
33
+ attr_reader :report, :template
34
+
35
+ def initialize(options={})
36
+ self.class.verify_dependencies!
37
+ create_metric_dir_if_missing
38
+ create_output_dir_if_missing
39
+ end
40
+
41
+ # Creates a new generator and returns the output of the
42
+ # #generate_report method. This is the typical way to
43
+ # generate a new MetricFu report. For more information see
44
+ # the #generate_report instance method.
45
+ #
46
+ # @params options Hash
47
+ # A currently unused hash to configure the Generator
48
+ #
49
+ # @see generate_report
50
+ def self.generate_report(options={})
51
+ generator = self.new(options)
52
+ generator.generate_report
53
+ rescue RuntimeError=>e
54
+ puts "*** #{e.message}"
55
+ {}
56
+ end
57
+
58
+ # Provides the unqualified class name of an implemented concrete
59
+ # class, as a string. For example:
60
+ #
61
+ # class Flay < Generator; end
62
+ # klass = Flay.new
63
+ # klass.class_name
64
+ # > "flay"
65
+ #
66
+ # @return String
67
+ # The unqualified class name of this concrete class, returned
68
+ # as a string.
69
+ def self.class_name
70
+ self.to_s.split('::').last.downcase
71
+ end
72
+
73
+ # Returns the directory where the Generator will write any output
74
+ def self.metric_directory
75
+ File.join(MetricFu.scratch_directory, class_name)
76
+ end
77
+
78
+ def create_metric_dir_if_missing #:nodoc:
79
+ unless File.directory?(metric_directory)
80
+ FileUtils.mkdir_p(metric_directory, :verbose => false)
81
+ end
82
+ end
83
+
84
+ def create_output_dir_if_missing #:nodoc:
85
+ unless File.directory?(MetricFu.output_directory)
86
+ FileUtils.mkdir_p(MetricFu.output_directory, :verbose => false)
87
+ end
88
+ end
89
+
90
+ # @return String
91
+ # The path of the metric directory this class is using.
92
+ def metric_directory
93
+ self.class.metric_directory
94
+ end
95
+
96
+
97
+ # Defines some hook methods for the concrete classes to hook into.
98
+ %w[emit analyze].each do |meth|
99
+ define_method("before_#{meth}".to_sym) {}
100
+ define_method("after_#{meth}".to_sym) {}
101
+ end
102
+ define_method("before_to_h".to_sym) {}
103
+
104
+ # Provides a template method to drive the production of a metric
105
+ # from a concrete implementation of this class. Each concrete
106
+ # class must implement the three methods that this template method
107
+ # calls: #emit, #analyze and #to_h. For more details, see the
108
+ # class documentation.
109
+ #
110
+ # This template method also calls before_emit, after_emit... etc.
111
+ # methods to allow extra hooks into the processing methods, and help
112
+ # to keep the logic of your Generators clean.
113
+ def generate_report
114
+ %w[emit analyze].each do |meth|
115
+ send("before_#{meth}".to_sym)
116
+ send("#{meth}".to_sym)
117
+ send("after_#{meth}".to_sym)
118
+ end
119
+ before_to_h()
120
+ to_h()
121
+ end
122
+
123
+ def round_to_tenths(decimal)
124
+ (decimal * 10).round / 10.0
125
+ end
126
+
127
+ # Allows subclasses to check for required gems
128
+ def self.verify_dependencies!
129
+ true
130
+ end
131
+
132
+ def emit #:nodoc:
133
+ raise <<-EOF
134
+ This method must be implemented by a concrete class descending
135
+ from Generator. See generator class documentation for more
136
+ information.
137
+ EOF
138
+ end
139
+
140
+ def analyze #:nodoc:
141
+ raise <<-EOF
142
+ This method must be implemented by a concrete class descending
143
+ from Generator. See generator class documentation for more
144
+ information.
145
+ EOF
146
+ end
147
+
148
+ def to_h #:nodoc:
149
+ raise <<-EOF
150
+ This method must be implemented by a concrete class descending
151
+ from Generator. See generator class documentation for more
152
+ information.
153
+ EOF
154
+ end
155
+ end
156
+ end
@@ -0,0 +1,52 @@
1
+ require 'digest/md5'
2
+ require 'fileutils'
3
+
4
+ module MetricFu
5
+ class MD5Tracker
6
+
7
+ @@unchanged_md5s = []
8
+
9
+ class << self
10
+ def md5_dir(path_to_file, base_dir)
11
+ File.join(base_dir,
12
+ path_to_file.split('/')[0..-2].join('/'))
13
+ end
14
+
15
+ def md5_file(path_to_file, base_dir)
16
+ File.join(md5_dir(path_to_file, base_dir),
17
+ path_to_file.split('/').last.sub(/\.[a-z]+/, '.md5'))
18
+ end
19
+
20
+ def track(path_to_file, base_dir)
21
+ md5 = Digest::MD5.hexdigest(File.read(path_to_file))
22
+ FileUtils.mkdir_p(md5_dir(path_to_file, base_dir), :verbose => false)
23
+ f = File.new(md5_file(path_to_file, base_dir), "w")
24
+ f.puts(md5)
25
+ f.close
26
+ md5
27
+ end
28
+
29
+ def file_changed?(path_to_file, base_dir)
30
+ orig_md5_file = md5_file(path_to_file, base_dir)
31
+ return !!track(path_to_file, base_dir) unless File.exist?(orig_md5_file)
32
+
33
+ current_md5 = ""
34
+ file = File.open(orig_md5_file, 'r')
35
+ file.each_line { |line| current_md5 << line }
36
+ file.close
37
+ current_md5.chomp!
38
+
39
+ new_md5 = Digest::MD5.hexdigest(File.read(path_to_file))
40
+ new_md5.chomp!
41
+
42
+ @@unchanged_md5s << path_to_file if new_md5 == current_md5
43
+
44
+ return new_md5 != current_md5
45
+ end
46
+
47
+ def file_already_counted?(path_to_file)
48
+ return @@unchanged_md5s.include?(path_to_file)
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,100 @@
1
+ module MetricFu
2
+
3
+ # MetricFu.report memoizes access to a Report object, that will be
4
+ # used throughout the lifecycle of the MetricFu app.
5
+ def self.report
6
+ @report ||= Report.new
7
+ end
8
+
9
+ # = Report
10
+ #
11
+ # The Report class is responsible two things:
12
+ #
13
+ # It adds information to the yaml report, produced by the system
14
+ # as a whole, for each of the generators used in this test run.
15
+ #
16
+ # It also handles passing the information from each generator used
17
+ # in this test run out to the template class set in
18
+ # MetricFu::Configuration.
19
+ class Report
20
+
21
+ # Renders the result of the report_hash into a yaml serialization
22
+ # ready for writing out to a file.
23
+ #
24
+ # @return YAML
25
+ # A YAML object containing the results of the report generation
26
+ # process
27
+ def to_yaml
28
+ report_hash.to_yaml
29
+ end
30
+
31
+
32
+ def report_hash #:nodoc:
33
+ @report_hash ||= {}
34
+ end
35
+
36
+ # Instantiates a new template class based on the configuration set
37
+ # in MetricFu::Configuration, or through the MetricFu.config block
38
+ # in your rake file (defaults to the included StandardTemplate) and
39
+ # assigns the report_hash to the report_hash to the template and
40
+ # asks itself to write itself out.
41
+ def save_templatized_report
42
+ @template = MetricFu.template_class.new
43
+ @template.report = report_hash
44
+ @template.write
45
+ end
46
+
47
+ # Adds a hash from a passed report, produced by one of the Generator
48
+ # classes to the aggregate report_hash managed by this hash.
49
+ #
50
+ # @param report_type Hash
51
+ # The hash to add to the aggregate report_hash
52
+ def add(report_type)
53
+ clazz = MetricFu.const_get(report_type.to_s.capitalize)
54
+ report_hash.merge!(clazz.generate_report)
55
+ end
56
+
57
+ # Saves the passed in content to the passed in directory. If
58
+ # a filename is passed in it will be used as the name of the
59
+ # file, otherwise it will default to 'index.html'
60
+ #
61
+ # @param content String
62
+ # A string containing the content (usually html) to be written
63
+ # to the file.
64
+ #
65
+ # @param dir String
66
+ # A dir containing the path to the directory to write the file in.
67
+ #
68
+ # @param file String
69
+ # A filename to save the path as. Defaults to 'index.html'.
70
+ #
71
+ def save_output(content, dir, file='index.html')
72
+ open("#{dir}/#{file}", "w") do |f|
73
+ f.puts content
74
+ end
75
+ end
76
+
77
+ # Checks to discover whether we should try and open the results
78
+ # of the report in the browser on this system. We only try and open
79
+ # in the browser if we're on OS X and we're not running in a
80
+ # CruiseControl.rb environment. See MetricFu.configuration for more
81
+ # details about how we make those guesses.
82
+ #
83
+ # @return Boolean
84
+ # Should we open in the browser or not?
85
+ def open_in_browser?
86
+ MetricFu.configuration.platform.include?('darwin') &&
87
+ ! MetricFu.configuration.is_cruise_control_rb?
88
+ end
89
+
90
+ # Shows 'index.html' from the passed directory in the browser
91
+ # if we're able to open the browser on this platform.
92
+ #
93
+ # @param dir String
94
+ # The directory path where the 'index.html' we want to open is
95
+ # stored
96
+ def show_in_browser(dir)
97
+ system("open #{dir}/index.html") if open_in_browser?
98
+ end
99
+ end
100
+ end
@@ -0,0 +1,86 @@
1
+ require 'chronic'
2
+ require 'generator'
3
+ module MetricFu
4
+
5
+ class Churn < Generator
6
+
7
+ def initialize(options={})
8
+ super
9
+ if File.exist?(".git")
10
+ @source_control = Git.new(MetricFu.churn[:start_date])
11
+ elsif File.exist?(".svn")
12
+ @source_control = Svn.new(MetricFu.churn[:start_date])
13
+ else
14
+ raise "Churning requires a subversion or git repo"
15
+ end
16
+ @minimum_churn_count = MetricFu.churn[:minimum_churn_count] || 5
17
+ end
18
+
19
+ def emit
20
+ @changes = parse_log_for_changes.reject {|file, change_count| change_count < @minimum_churn_count}
21
+ end
22
+
23
+ def analyze
24
+ @changes = @changes.to_a.sort {|x,y| y[1] <=> x[1]}
25
+ @changes = @changes.map {|change| {:file_path => change[0], :times_changed => change[1] }}
26
+ end
27
+
28
+ def to_h
29
+ {:churn => {:changes => @changes}}
30
+ end
31
+
32
+ private
33
+
34
+ def parse_log_for_changes
35
+ changes = {}
36
+
37
+ logs = @source_control.get_logs
38
+ logs.each do |line|
39
+ changes[line] ? changes[line] += 1 : changes[line] = 1
40
+ end
41
+ changes
42
+ end
43
+
44
+
45
+ class SourceControl
46
+ def initialize(start_date=nil)
47
+ @start_date = start_date
48
+ end
49
+ end
50
+
51
+ class Git < SourceControl
52
+ def get_logs
53
+ `git log #{date_range} --name-only --pretty=format:`.split(/\n/).reject{|line| line == ""}
54
+ end
55
+
56
+ private
57
+ def date_range
58
+ if @start_date
59
+ date = Chronic.parse(@start_date)
60
+ "--after=#{date.strftime('%Y-%m-%d')}"
61
+ end
62
+ end
63
+
64
+ end
65
+
66
+ class Svn < SourceControl
67
+ def get_logs
68
+ `svn log #{date_range} --verbose`.split(/\n/).map { |line| clean_up_svn_line(line) }.compact
69
+ end
70
+
71
+ private
72
+ def date_range
73
+ if @start_date
74
+ date = Chronic.parse(@start_date)
75
+ "--revision {#{date.strftime('%Y-%m-%d')}}:{#{Time.now.strftime('%Y-%m-%d')}}"
76
+ end
77
+ end
78
+
79
+ def clean_up_svn_line(line)
80
+ m = line.match(/\W*[A,M]\W+(\/.*)\b/)
81
+ m ? m[1] : nil
82
+ end
83
+ end
84
+
85
+ end
86
+ end
@@ -0,0 +1,33 @@
1
+ require 'generator'
2
+ module MetricFu
3
+
4
+ class Flay < Generator
5
+
6
+ def self.verify_dependencies!
7
+ raise "Missing flay gem. Please 'gem install flay'" unless system('flay --help')
8
+ end
9
+
10
+ def emit
11
+ files_to_flay = MetricFu.flay[:dirs_to_flay].map{|dir| Dir[File.join(dir, "**/*.rb")] }
12
+ @output = `flay #{files_to_flay.join(" ")}`
13
+ end
14
+
15
+ def analyze
16
+ @matches = @output.chomp.split("\n\n").map{|m| m.split("\n ") }
17
+ end
18
+
19
+ def to_h
20
+ target = []
21
+ total_score = @matches.shift.first.split('=').last.strip
22
+ @matches.each do |problem|
23
+ reason = problem.shift.strip
24
+ lines_info = problem.map do |full_line|
25
+ name, line = full_line.split(":")
26
+ {:name => name.strip, :line => line.strip}
27
+ end
28
+ target << [:reason => reason, :matches => lines_info]
29
+ end
30
+ {:flay => {:total_score => total_score, :matches => target.flatten}}
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,131 @@
1
+ module MetricFu
2
+
3
+ class Flog < Generator
4
+ attr_reader :pages
5
+
6
+ def self.verify_dependencies!
7
+ raise "Missing flog gem. Please 'gem install flog'" unless system('flog --help')
8
+ end
9
+
10
+ SCORE_FORMAT = "%0.2f"
11
+ METHOD_LINE_REGEX = /(\d+\.\d+):\s+([A-Za-z:]+#.*)/
12
+ OPERATOR_LINE_REGEX = /\s*(\d+\.\d+):\s(.*)$/
13
+
14
+ def emit
15
+ metric_dir = MetricFu::Flog.metric_directory
16
+ MetricFu.flog[:dirs_to_flog].each do |directory|
17
+ Dir.glob("#{directory}/**/*.rb").each do |filename|
18
+ output_dir = "#{metric_dir}/#{filename.split("/")[0..-2].join("/")}"
19
+ mkdir_p(output_dir, :verbose => false) unless File.directory?(output_dir)
20
+ if MetricFu::MD5Tracker.file_changed?(filename, metric_dir)
21
+ `flog -ad #{filename} > #{metric_dir}/#{filename.split('.')[0]}.txt`
22
+ end
23
+ end
24
+ end
25
+ rescue LoadError
26
+ if RUBY_PLATFORM =~ /java/
27
+ puts 'running in jruby - flog tasks not available'
28
+ else
29
+ puts 'sudo gem install flog # if you want the flog tasks'
30
+ end
31
+ end
32
+
33
+ def parse(text)
34
+ summary, methods_summary = text.split "\n\n"
35
+ score, average = summary.split("\n").map {|line| line[OPERATOR_LINE_REGEX, 1]}
36
+ return nil unless score && methods_summary
37
+ page = Flog::Page.new(score, average)
38
+ methods_summary.each_line do |method_line|
39
+ if match = method_line.match(METHOD_LINE_REGEX)
40
+ page.scanned_methods << ScannedMethod.new(match[2], match[1])
41
+ elsif match = method_line.match(OPERATOR_LINE_REGEX)
42
+ return if page.scanned_methods.empty?
43
+ page.scanned_methods.last.operators << Operator.new(match[1], match[2])
44
+ end
45
+ end
46
+ page
47
+ end
48
+
49
+ def analyze
50
+ @pages = []
51
+ flog_results.each do |path|
52
+ page = parse(open(path, "r") { |f| f.read })
53
+ if page
54
+ page.path = path.sub(metric_directory, "").sub(".txt", ".rb")
55
+ @pages << page
56
+ end
57
+ end
58
+ end
59
+
60
+ def to_h
61
+ number_of_methods = @pages.inject(0) {|count, page| count += page.scanned_methods.size}
62
+ total_flog_score = @pages.inject(0) {|total, page| total += page.score}
63
+ sorted_pages = @pages.sort_by {|page| page.score }.reverse
64
+ {:flog => { :total => total_flog_score,
65
+ :average => round_to_tenths(total_flog_score/number_of_methods),
66
+ :pages => sorted_pages.map {|page| page.to_h}}}
67
+ end
68
+
69
+ def flog_results
70
+ Dir.glob("#{metric_directory}/**/*.txt")
71
+ end
72
+
73
+ class Operator
74
+ attr_accessor :score, :operator
75
+
76
+ def initialize(score, operator)
77
+ @score = score.to_f
78
+ @operator = operator
79
+ end
80
+
81
+ def to_h
82
+ {:score => @score, :operator => @operator}
83
+ end
84
+ end
85
+
86
+ class ScannedMethod
87
+ attr_accessor :name, :score, :operators
88
+
89
+ def initialize(name, score, operators = [])
90
+ @name = name
91
+ @score = score.to_f
92
+ @operators = operators
93
+ end
94
+
95
+ def to_h
96
+ {:name => @name,
97
+ :score => @score,
98
+ :operators => @operators.map {|o| o.to_h}}
99
+ end
100
+ end
101
+
102
+ end
103
+
104
+ class Flog::Page < MetricFu::Generator
105
+ attr_accessor :path, :score, :scanned_methods, :average_score
106
+
107
+ def initialize(score, average_score, scanned_methods = [])
108
+ @score = score.to_f
109
+ @scanned_methods = scanned_methods
110
+ @average_score = average_score.to_f
111
+ end
112
+
113
+ def filename
114
+ File.basename(path, ".txt")
115
+ end
116
+
117
+ def to_h
118
+ {:score => @score,
119
+ :scanned_methods => @scanned_methods.map {|sm| sm.to_h},
120
+ :highest_score => highest_score,
121
+ :average_score => average_score,
122
+ :path => path}
123
+ end
124
+
125
+ def highest_score
126
+ scanned_methods.inject(0) do |highest, m|
127
+ m.score > highest ? m.score : highest
128
+ end
129
+ end
130
+ end
131
+ end