Module: RubyLLM::Toolbox::TextDiff
- Defined in:
- lib/ruby_llm/toolbox/text_diff.rb
Overview
Line-based diff via longest-common-subsequence. Produces a readable diff (‘-’/‘+’/‘ ’ prefixes) with long unchanged runs elided. Pure stdlib.
Class Method Summary collapse
- .diff_ops(a, b) ⇒ Object
- .emit_context(out, run, context) ⇒ Object
- .render(ops, old_label, new_label, context) ⇒ Object
- .unified(old_text, new_text, old_label: "old", new_label: "new", context: 3) ⇒ Object
Class Method Details
.diff_ops(a, b) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/ruby_llm/toolbox/text_diff.rb', line 19 def diff_ops(a, b) n = a.size m = b.size lcs = Array.new(n + 1) { Array.new(m + 1, 0) } (n - 1).downto(0) do |i| (m - 1).downto(0) do |j| lcs[i][j] = a[i] == b[j] ? lcs[i + 1][j + 1] + 1 : [lcs[i + 1][j], lcs[i][j + 1]].max end end ops = [] i = 0 j = 0 while i < n && j < m if a[i] == b[j] ops << [:eq, a[i]] i += 1 j += 1 elsif lcs[i + 1][j] >= lcs[i][j + 1] ops << [:del, a[i]] i += 1 else ops << [:add, b[j]] j += 1 end end ops.concat(a[i..].map { |line| [:del, line] }) if i < n ops.concat(b[j..].map { |line| [:add, line] }) if j < m ops end |
.emit_context(out, run, context) ⇒ Object
70 71 72 73 74 75 76 77 78 |
# File 'lib/ruby_llm/toolbox/text_diff.rb', line 70 def emit_context(out, run, context) if run.size > (context * 2) + 1 run.first(context).each { |line| out << " #{line.chomp}" } out << " ⋮ (#{run.size - (context * 2)} unchanged lines)" run.last(context).each { |line| out << " #{line.chomp}" } else run.each { |line| out << " #{line.chomp}" } end end |
.render(ops, old_label, new_label, context) ⇒ Object
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/ruby_llm/toolbox/text_diff.rb', line 50 def render(ops, old_label, new_label, context) out = ["--- #{old_label}", "+++ #{new_label}"] i = 0 while i < ops.size type, line = ops[i] if type == :eq run = [] while i < ops.size && ops[i][0] == :eq run << ops[i][1] i += 1 end emit_context(out, run, context) else out << "#{type == :del ? '-' : '+'} #{line.chomp}" i += 1 end end out.join("\n") end |
.unified(old_text, new_text, old_label: "old", new_label: "new", context: 3) ⇒ Object
10 11 12 13 14 15 16 17 |
# File 'lib/ruby_llm/toolbox/text_diff.rb', line 10 def unified(old_text, new_text, old_label: "old", new_label: "new", context: 3) a = old_text.to_s.lines b = new_text.to_s.lines ops = diff_ops(a, b) return "(no differences)" if ops.all? { |type, _| type == :eq } render(ops, old_label, new_label, context) end |