Module: AllInRuby::Diff

Defined in:
lib/all_in_ruby/diff.rb

Overview

Builds unified diffs for dry-run previews. The installer only ever makes one contiguous edit per file (appending or removing a single block), so a common prefix/suffix comparison finds the exact changed region.

Constant Summary collapse

CONTEXT_LINES =
3
NO_NEWLINE_MARKER =
"\\ No newline at end of file"

Class Method Summary collapse

Class Method Details

.unified(old_content, new_content, path) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/all_in_ruby/diff.rb', line 11

def self.unified(old_content, new_content, path)
  old_lines = (old_content || "").lines
  new_lines = new_content.lines

  prefix = common_prefix_length(old_lines, new_lines)
  suffix = common_suffix_length(old_lines, new_lines, prefix)

  removed = old_lines[prefix...(old_lines.length - suffix)]
  added = new_lines[prefix...(new_lines.length - suffix)]
  lead = [prefix, CONTEXT_LINES].min
  trail = [suffix, CONTEXT_LINES].min

  output = []
  output << "--- #{old_content ? path : File::NULL}"
  output << "+++ #{path}"
  output << hunk_header(prefix, lead, trail, removed.length, added.length)
  old_lines[prefix - lead, lead].each { |line| append(output, " ", line) }
  removed.each { |line| append(output, "-", line) }
  added.each { |line| append(output, "+", line) }
  old_lines[old_lines.length - suffix, trail].each { |line| append(output, " ", line) }
  "#{output.join("\n")}\n"
end