free_mutant/lib/mutant/differ.rb

123 lines
2.1 KiB
Ruby
Raw Normal View History

# encoding: utf-8
2012-08-16 12:02:03 -04:00
module Mutant
2012-08-16 13:26:15 -04:00
# Class to create diffs from source code
2012-08-16 12:02:03 -04:00
class Differ
2013-07-02 13:06:03 -04:00
include Adamantium::Flat, Concord.new(:old, :new)
2013-06-28 17:33:53 -04:00
2013-04-17 23:31:21 -04:00
# Return source diff
2012-08-16 13:26:15 -04:00
#
# @return [String]
# if there is a diff
#
# @return [nil]
# otherwise
2012-08-16 13:26:15 -04:00
#
# @api private
#
2012-08-16 12:02:03 -04:00
def diff
2013-07-02 13:06:03 -04:00
case diffs.length
when 0
nil
when 1
2013-09-15 01:32:41 -04:00
Diff::LCS::Hunk.new(old, new, diffs.first, max_length, 0)
.diff(:unified) << "\n"
2013-07-02 13:06:03 -04:00
else
2013-07-28 12:57:52 -04:00
$stderr.puts(
'Mutation resulted in more than one diff, should not happen! ' +
'PLS report a bug!'
)
2013-07-05 05:48:10 -04:00
nil
2012-08-16 12:02:03 -04:00
end
end
memoize :diff
2013-04-17 23:31:21 -04:00
# Return colorized source diff
2012-08-16 13:26:15 -04:00
#
# @return [String]
# if there is a diff
#
# @return [nil]
# otherwise
2012-08-16 13:26:15 -04:00
#
# @api private
#
2012-08-16 12:02:03 -04:00
def colorized_diff
return unless diff
2012-08-16 12:02:03 -04:00
diff.lines.map do |line|
self.class.colorize_line(line)
end.join
end
memoize :colorized_diff
2013-07-02 13:06:03 -04:00
# Return new object
2012-08-16 13:26:15 -04:00
#
2013-04-17 23:31:21 -04:00
# @param [String] old
2012-08-16 13:26:15 -04:00
# @param [String] new
#
2013-07-02 13:06:03 -04:00
# @return [Differ]
2012-08-16 13:26:15 -04:00
#
# @api private
#
def self.build(old, new)
new(lines(old), lines(new))
2012-08-16 13:26:15 -04:00
end
2013-07-02 14:12:54 -04:00
# Break up source into lines
#
# @param [String] source
#
# @return [Array<String>]
#
# @api private
#
def self.lines(source)
source.lines.map { |line| line.chomp }
end
private_class_method :lines
2013-07-02 13:06:03 -04:00
private
# Return diffs
#
2013-07-02 13:06:03 -04:00
# @return [Array<Array>]
#
2013-07-02 13:06:03 -04:00
# @api private
#
def diffs
Diff::LCS.diff(old, new)
end
memoize :diffs
# Return max length
#
# @return [Fixnum]
#
# @api private
#
2013-07-02 13:06:03 -04:00
def max_length
2013-07-02 17:34:35 -04:00
[old, new].map(&:length).max
end
2012-08-16 13:26:15 -04:00
# Return colorized diff line
#
# @param [String] line
#
# @return [String]
#
# @api private
#
2012-08-16 12:02:03 -04:00
def self.colorize_line(line)
case line[0]
2012-08-16 12:02:03 -04:00
when '+'
Color::GREEN
when '-'
Color::RED
else
Color::NONE
end.format(line)
end
2013-06-14 14:54:02 -04:00
end # Differ
end # Mutant