Skip to content

Commit

Permalink
Change to color all hunks in one pass
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrmurach committed Jul 27, 2020
1 parent b67220e commit 4f1dadd
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions lib/tty/file/compare_files.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,11 @@ def call(file_a, file_b, file_a_path, file_b_path)
end

output << "\n" unless hunks =~ /\A\n+@@/
output << color_diff_lines(hunks, color: @color, format: @format)
output << hunks
while !file_a.eof? && !file_b.eof?
output << differ.(file_a.read(block_size), file_b.read(block_size))
end
output.join
color_diff_lines(output.join, color: @color, format: @format)
end

private
Expand All @@ -53,9 +53,17 @@ def color_diff_lines(hunks, color: true, format: :unified)
return hunks unless color && format == :unified

newline = "\n"
hunks.gsub(/^(\+[^+].*?)\n/, decorate("\\1", :green) + newline)
.gsub(/^(\-[^-].*?)\n/, decorate("\\1", :red) + newline)
.gsub(/^(@.+?)\n/, decorate("\\1", :cyan) + newline)
hunks.lines.map do |line|
if matched = line.to_s.match(/^(\+[^+]*?)\n/)
decorate(matched[1], :green) + newline
elsif matched = line.to_s.match(/^(\-[^-].*?)\n/)
decorate(matched[1], :red) + newline
elsif matched = line.to_s.match(/^(@@.+?@@)\n/)
decorate(matched[1], :cyan) + newline
else
line
end
end.join
end

def decorate(*args)
Expand Down

0 comments on commit 4f1dadd

Please sign in to comment.