free_mutant/lib/mutant/differ.rb

101 lines
1.8 KiB
Ruby
Raw Normal View History

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
include Adamantium::Flat
2012-08-16 12:02:03 -04:00
2012-08-16 13:26:15 -04:00
# Return source diff
#
# @return [String]
#
# @api private
#
2012-08-16 12:02:03 -04:00
def diff
output = ''
@diffs.each do |piece|
2012-08-16 13:42:09 -04:00
hunk = Diff::LCS::Hunk.new(@old, @new, piece, CONTEXT_LINES, length_difference)
2012-08-16 13:26:15 -04:00
output << hunk.diff(FORMAT)
2012-08-16 12:02:03 -04:00
output << "\n"
end
output
end
memoize :diff
2012-08-16 13:26:15 -04:00
# Return colorized source diff
#
# @return [String]
#
# @api private
#
2012-08-16 12:02:03 -04:00
def colorized_diff
diff.lines.map do |line|
self.class.colorize_line(line)
end.join
end
memoize :colorized_diff
2012-08-16 13:26:15 -04:00
private
FORMAT = :unified
CONTEXT_LINES = 3
# Initialize differ object
#
# @param [String] old
# @param [String] new
#
# @return [undefined]
#
# @api private
#
def initialize(old, new)
2012-08-16 13:42:09 -04:00
@old, @new = self.class.lines(old), self.class.lines(new)
2012-08-16 13:26:15 -04:00
@diffs = Diff::LCS.diff(@old, @new)
end
2012-08-16 13:42:09 -04:00
# Return length difference
#
# @return [Fixnum]
#
# @api private
#
def length_difference
@new.size - @old.size
end
# Break up source into lines
#
# @param [String] source
#
# @return [Array<String>]
#
# @api private
#
def self.lines(source)
source.lines.map { |line| line.chomp }
end
2012-08-16 13:26:15 -04:00
# Return colorized diff line
#
# @param [String] line
#
# @return [String]
# returns colorized line
#
# @api private
#
2012-08-16 12:02:03 -04:00
def self.colorize_line(line)
case line[0].chr
when '+'
Color::GREEN
when '-'
Color::RED
when '@'
line[1].chr == '@' ? Color::BLUE : Color::NONE
else
Color::NONE
end.format(line)
end
end
end