class Nanoc::CLI::CompileListeners::DiffGenerator::Differ

Public Class Methods

new(path, str_a, str_b) click to toggle source
# File lib/nanoc/cli/compile_listeners/diff_generator.rb, line 6
def initialize(path, str_a, str_b)
  @path = path
  @str_a = str_a
  @str_b = str_b
end

Public Instance Methods

call() click to toggle source
# File lib/nanoc/cli/compile_listeners/diff_generator.rb, line 12
def call
  run
end

Private Instance Methods

run() click to toggle source
# File lib/nanoc/cli/compile_listeners/diff_generator.rb, line 18
def run
  lines_a = @str_a.lines.map(&:chomp)
  lines_b = @str_b.lines.map(&:chomp)

  diffs = Diff::LCS.diff(lines_a, lines_b)

  output = +''
  output << "--- #{@path}\n"
  output << "+++ #{@path}\n"

  prev_hunk = hunk = nil
  file_length_difference = 0
  diffs.each do |piece|
    begin
      hunk = Diff::LCS::Hunk.new(lines_a, lines_b, piece, 3, file_length_difference)
      file_length_difference = hunk.file_length_difference

      next unless prev_hunk
      next if hunk.merge(prev_hunk)

      output << prev_hunk.diff(:unified) << "\n"
    ensure
      prev_hunk = hunk
    end
  end
  last = prev_hunk.diff(:unified)
  output << last << "\n"

  output
end