class NdrDevSupport::Rubocop::RangeFinder

Produces diffs, and parses from them the file/hunk boundaries

Public Instance Methods

diff_expr(expr) click to toggle source
# File lib/ndr_dev_support/rubocop/range_finder.rb, line 25
def diff_expr(expr)
  file_change_locations_from git_diff(expr)
end
diff_files(files) click to toggle source
# File lib/ndr_dev_support/rubocop/range_finder.rb, line 9
def diff_files(files)
  file_change_locations_from git_diff(files * ' ')
end
diff_head() click to toggle source
# File lib/ndr_dev_support/rubocop/range_finder.rb, line 13
def diff_head
  file_change_locations_from git_diff('HEAD')
end
diff_staged() click to toggle source
# File lib/ndr_dev_support/rubocop/range_finder.rb, line 17
def diff_staged
  file_change_locations_from git_diff('--staged')
end
diff_unstaged() click to toggle source
# File lib/ndr_dev_support/rubocop/range_finder.rb, line 21
def diff_unstaged
  file_change_locations_from git_diff('')
end

Private Instance Methods

file_change_locations_from(diff, changes = file_changes_hash) click to toggle source
# File lib/ndr_dev_support/rubocop/range_finder.rb, line 50
def file_change_locations_from(diff, changes = file_changes_hash)
  current_file = nil
  diff.each_line do |line|
    if line.start_with?('+++')
      current_file = line[4..-1].strip
    elsif line.start_with?('@@')
      range = hunk_range_from(line)
      changes[current_file].push(range) unless range.end.zero?
    end
  end

  changes
end
file_changes_hash() click to toggle source
# File lib/ndr_dev_support/rubocop/range_finder.rb, line 46
def file_changes_hash
  Hash.new { |hash, file| hash[file] = [] }
end
git_diff(args) click to toggle source
# File lib/ndr_dev_support/rubocop/range_finder.rb, line 31
      def git_diff(args)
        diff_cmd = 'git diff --no-prefix --unified=0 '
        diff_cmd << Shellwords.escape(args) unless args.empty?
        stdout, stderr, status = Open3.capture3(diff_cmd)

        return stdout if status.success?

        fail Rainbow(<<-MSG).red
Failed to generate diff from:
  #{diff_cmd}

#{stderr}
        MSG
      end
hunk_range_from(line) click to toggle source
# File lib/ndr_dev_support/rubocop/range_finder.rb, line 64
def hunk_range_from(line)
  match_data = line.match(/\A@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/)
  start_line = match_data[1].to_i
  new_lines  = match_data[2].to_i
  end_line   = new_lines.zero? ? start_line : start_line + new_lines - 1

  start_line..end_line
end