Class: RubynCode::Output::DiffRenderer

Inherits:
Object
  • Object
show all
Defined in:
lib/rubyn_code/output/diff_renderer.rb

Overview

rubocop:disable Metrics/ClassLength – LCS diff computation + hunk grouping + rendering

Defined Under Namespace

Classes: DiffLine, Hunk

Constant Summary collapse

MAX_LCS_CELLS =

The LCS table is O(N×M) in time and memory. Beyond this many cells (after prefix/suffix trimming) the middle section is rendered as a plain delete-all/add-all block instead of a minimal diff.

1_000_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(enabled: $stdout.tty?, context_lines: 3) ⇒ DiffRenderer

Returns a new instance of DiffRenderer.

Parameters:

  • enabled (Boolean) (defaults to: $stdout.tty?)

    whether color output is enabled

  • context_lines (Integer) (defaults to: 3)

    number of context lines around changes



27
28
29
30
# File 'lib/rubyn_code/output/diff_renderer.rb', line 27

def initialize(enabled: $stdout.tty?, context_lines: 3)
  @pastel = Pastel.new(enabled: enabled)
  @context_lines = context_lines
end

Instance Attribute Details

#pastelObject (readonly)

Returns the value of attribute pastel.



23
24
25
# File 'lib/rubyn_code/output/diff_renderer.rb', line 23

def pastel
  @pastel
end

Instance Method Details

#render(old_text, new_text, filename: 'file') ⇒ String

Renders a unified diff between old_text and new_text.

Parameters:

  • old_text (String)

    the original text

  • new_text (String)

    the modified text

  • filename (String) (defaults to: 'file')

    the filename to display in the diff header

Returns:

  • (String)

    the rendered, colorized diff output



38
39
40
41
42
43
44
45
46
47
48
# File 'lib/rubyn_code/output/diff_renderer.rb', line 38

def render(old_text, new_text, filename: 'file')
  old_lines = old_text.lines.map(&:chomp)
  new_lines = new_text.lines.map(&:chomp)

  hunks = compute_hunks(old_lines, new_lines)
  return pastel.dim('No differences found.') if hunks.empty?

  result = assemble_output(hunks, filename)
  $stdout.puts(result)
  result
end