class Unparser::Diff

Class to create diffs from source code

def self.build(old, new)

Returns:
  • (Diff) -

Parameters:
  • new (String) --
  • old (String) --
def self.build(old, new)
  new(lines(old), lines(new))
end

def self.colorize_line(line)

def self.colorize_line(line)
  case line[0]
  when ADDITION
    Color::GREEN
  when DELETION
    Color::RED
  else
    Color::NONE
  end.format(line)
end

def self.lines(source)

Returns:
  • (Array) -

Parameters:
  • source (String) --
def self.lines(source)
  source.lines.map(&:chomp)
end

def colorized_diff

Returns:
  • (nil) -
  • (String) -
def colorized_diff
  return unless diff
  diff.lines.map(&self.class.method(:colorize_line)).join
end

def diff

Returns:
  • (nil) -
  • (String) -
def diff
  return if diffs.empty?
  minimized_hunk.diff(:unified) + NEWLINE
end

def diffs

def diffs
  ::Diff::LCS.diff(old, new)
end

def hunks

def hunks
  diffs.map do |diff|
    ::Diff::LCS::Hunk.new(old.map(&:dup), new, diff, max_length, 0)
  end
end

def max_length

def max_length
  [old, new].map(&:length).max
end

def minimized_hunk

def minimized_hunk
  head, *tail = hunks
  tail.reduce(head) do |left, right|
    right.merge(left)
    right
  end
end