Class: GitCrecord::Diff::Hunk

Inherits:
Difference show all
Defined in:
lib/git_crecord/diff/hunk.rb

Constant Summary

Constants inherited from Difference

Difference::REVERSE_SELECTED_MAP, Difference::SELECTED_MAP, Difference::SELECTION_MARKER_WIDTH

Instance Attribute Summary

Attributes inherited from Difference

#expanded, #subs, #y1, #y2

Instance Method Summary collapse

Methods inherited from Difference

#content_width, #max_height, #prefix, #prefix_style, #print, #selectable?, #selectable_subs, #selected, #selected=, #strings, #style

Constructor Details

#initialize(head, reverse: false) ⇒ Hunk

Returns a new instance of Hunk.



10
11
12
13
14
# File 'lib/git_crecord/diff/hunk.rb', line 10

def initialize(head, reverse: false)
  @head = head
  @expanded = true
  super(reverse: reverse)
end

Instance Method Details

#<<(line) ⇒ Object



24
25
26
27
# File 'lib/git_crecord/diff/hunk.rb', line 24

def <<(line)
  subs << Line.new(line, reverse: @reverse)
  self
end

#generate_diffObject



29
30
31
32
33
# File 'lib/git_crecord/diff/hunk.rb', line 29

def generate_diff
  return nil unless selected

  [generate_header, *subs.map(&:generate_diff).compact].join("\n")
end

#generate_headerObject



35
36
37
38
39
40
41
42
43
44
# File 'lib/git_crecord/diff/hunk.rb', line 35

def generate_header
  old_start, old_count, new_start, new_count = parse_header
  selectable_subs.each do |sub|
    next if sub.selected

    new_count -= 1 if sub.add?
    new_count += 1 if sub.del?
  end
  "@@ -#{old_start},#{old_count} +#{new_start},#{new_count} @@"
end

#parse_headerObject



46
47
48
49
50
51
# File 'lib/git_crecord/diff/hunk.rb', line 46

def parse_header
  match = @head.match(/@@ -(\d+)(,(\d+))? \+(\d+)(,(\d+))? @@/)
  raise "mismatching hunk-header - '#{@head}'" if match.nil?

  [match[1], match[3] || 1, match[4], match[6] || 1].map(&:to_i)
end

#to_sObject



16
17
18
# File 'lib/git_crecord/diff/hunk.rb', line 16

def to_s
  @head
end

#x_offsetObject



20
21
22
# File 'lib/git_crecord/diff/hunk.rb', line 20

def x_offset
  3
end