Module: Holdify::Feedback::GitDiff

Defined in:
lib/holdify/feedback.rb

Overview

Methods enabling the git-diff feedback (no-color)

Instance Method Summary collapse

Instance Method Details

#create_tempfile(obj, type) ⇒ Object



86
87
88
89
90
91
# File 'lib/holdify/feedback.rb', line 86

def create_tempfile(obj, type)
  Tempfile.create.tap do |file|
    file.write(Store.hold_dump(obj).sub(/(?=\n)/, type))
    file.close
  end
end

#diffObject



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/holdify/feedback.rb', line 70

def diff
  @exp_path = create_tempfile(@expected, 'expected').path
  @act_path = create_tempfile(@actual, 'actual').path

  stdout, = Open3.capture3(git_command)
  regex   = /\A[^@]*\r?\n/m   # cleanup git headers
  lines   = stdout.sub(regex, '').split(/\r?\n/)

  process_lines(lines)
ensure
  # :nocov:
  File.unlink(@exp_path) if @exp_path
  File.unlink(@act_path) if @act_path
  # :nocov:
end

#git_commandObject



68
# File 'lib/holdify/feedback.rb', line 68

def git_command = "git diff --no-index --no-color --unified=1000 #{@exp_path} #{@act_path}"

#process_lines(lines) ⇒ Object



93
94
95
96
97
98
99
100
101
102
103
104
105
106
# File 'lib/holdify/feedback.rb', line 93

def process_lines(lines)
  width  = 0
  lineno = [@yaml_lno - 1]
  lines.map.with_index do |line, i|
    if i.zero? # @@ ... @@
      width, line = render_hunk(line)
      next line
    elsif i <= @diff_yaml_headers # ---
      next
    end

    render_line(line, lineno, width)
  end.compact
end

#render_hunk(line) ⇒ Object

Reduce the hunk lines by 1 and calculate the gutter width



109
110
111
112
113
114
115
116
117
118
119
# File 'lib/holdify/feedback.rb', line 109

def render_hunk(line)
  width = 0
  hunk  = line.gsub(/([-+]\d+),(\d+)\s+([-+]\d+),(\d+)/) do
            v1,   = $2.to_i - 1          # rubocop:disable Style/PerlBackrefs
            v2    = $4.to_i - 1          # rubocop:disable Style/PerlBackrefs
            width = (@yaml_lno + [v1, v2].max).to_s.length
            "#{$1},#{v1} #{$3},#{v2}"    # rubocop:disable Style/PerlBackrefs
          end

  [width, hunk]
end

#render_line(line, lineno, width) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/holdify/feedback.rb', line 121

def render_line(line, lineno, width)
  type   = line[0]
  line   = line[1..]
  gutter = if type == '+'
             ' ' * width
           else
             lineno[0] += 1
             lineno[0].to_s.rjust(width)
           end

  "#{type}#{gutter} #{line}"
end