class DiffHighlight

Constants

EXTENSIONS
FILES
VERSION

Public Class Methods

new() click to toggle source
# File lib/diff_highlight.rb, line 29
def initialize
  @buffer = ""
end

Public Instance Methods

execute() click to toggle source
# File lib/diff_highlight.rb, line 33
def execute
  ARGF.each_line do |line|
    if line =~ /^diff --git/
      flush_buffer
      @language = type_from_filename(line.split.last)
    end

    if line =~ /^\+[^\+]/
      write_added_line(line)
    else
      flush_buffer
      write_other_line(line)
    end
  end

  flush_buffer
end

Private Instance Methods

bold(str) click to toggle source
# File lib/diff_highlight.rb, line 101
def bold(str)
  "\e[1m#{str}\e[22m"
end
flush_buffer() click to toggle source
# File lib/diff_highlight.rb, line 63
def flush_buffer
  if !@buffer.empty?
    write(CodeRay.highlight(@buffer, @language, {}, :term))
    @buffer.clear
  end
end
green(str) click to toggle source
# File lib/diff_highlight.rb, line 97
def green(str)
  "\e[32m#{str}\e[0m"
end
normal(str) click to toggle source
# File lib/diff_highlight.rb, line 105
def normal(str)
  "\e[0m#{str}"
end
red(str) click to toggle source
# File lib/diff_highlight.rb, line 93
def red(str)
  "\e[31m#{str}\e[0m"
end
type_from_filename(filename, default = :unknown) click to toggle source
# File lib/diff_highlight.rb, line 53
def type_from_filename(filename, default = :unknown)
  _, language = EXTENSIONS.find do |k, _|
    k.any? { |ext| ext == File.extname(filename) }
  end || FILES.find do |k, _|
    k.any? { |file_name| file_name == File.basename(filename) }
  end

  language || default
end
write(str) click to toggle source
# File lib/diff_highlight.rb, line 89
def write(str)
  $stdout.write(str) unless $stdout.closed?
end
write_added_line(line) click to toggle source
# File lib/diff_highlight.rb, line 70
def write_added_line(line)
  if @language == :unknown
    write(green(line))
  else
    @buffer += line
  end
end
write_other_line(line) click to toggle source

when a line is not an addition (e.g begins with a +)

# File lib/diff_highlight.rb, line 79
def write_other_line(line)
  if line =~ /^-[^-]/
    write(red(line))
  elsif line =~ /^(commit|Author|Date)/
    write(bold(line))
  else
    write(normal(line))
  end
end