Class: GitDiffParser::Patches

Inherits:
Array
  • Object
show all
Defined in:
lib/git_diff_parser/patches.rb

Overview

The array of patch

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ Patches<Patch>



55
56
57
# File 'lib/git_diff_parser/patches.rb', line 55

def initialize(*args)
  super Array.new(*args)
end

Class Method Details

.[](*ary) ⇒ Patches<Patch>

Returns:



6
7
8
# File 'lib/git_diff_parser/patches.rb', line 6

def self.[](*ary)
  new(ary)
end

.parse(contents) ⇒ Patches<Patch>

Returns parsed object.

Parameters:

  • contents (String)

    ‘git diff` result

Returns:



13
14
15
16
17
18
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
# File 'lib/git_diff_parser/patches.rb', line 13

def self.parse(contents)
  body = false
  file_name = ''
  patch = []
  lines = contents.lines
  line_count = lines.count
  parsed = new
  lines.each_with_index do |line, count|
    case parsed.scrub_string(line.chomp)
    when /^diff/
      unless patch.empty?
        parsed << Patch.new(patch.join("\n") + "\n", file: file_name)
        patch.clear
        file_name = ''
      end
      body = false
    when /^\-\-\-/
    when %r{^\+\+\+ b/(?<file_name>.*)}
      file_name = Regexp.last_match[:file_name].rstrip
      body = true
    when /^(?<body>[\ @\+\-\\].*)/
      patch << Regexp.last_match[:body] if body
      if !patch.empty? && body && line_count == count + 1
        parsed << Patch.new(patch.join("\n") + "\n", file: file_name)
        patch.clear
        file_name = ''
      end
    end
  end
  parsed
end

Instance Method Details

#filesArray<String>

Returns file path.

Returns:

  • (Array<String>)

    file path



60
61
62
# File 'lib/git_diff_parser/patches.rb', line 60

def files
  map(&:file)
end

#find_patch_by_file(file) ⇒ Patch?

Parameters:

  • file (String)

    file path

Returns:



72
73
74
# File 'lib/git_diff_parser/patches.rb', line 72

def find_patch_by_file(file)
  find { |patch| patch.file == file }
end

#find_patch_by_secure_hash(secure_hash) ⇒ Patch?

Parameters:

  • secure_hash (String)

    target sha1 hash

Returns:



79
80
81
# File 'lib/git_diff_parser/patches.rb', line 79

def find_patch_by_secure_hash(secure_hash)
  find { |patch| patch.secure_hash == secure_hash }
end

#scrub_string(line) ⇒ String

Returns:

  • (String)


46
47
48
49
50
51
52
# File 'lib/git_diff_parser/patches.rb', line 46

def scrub_string(line)
  if RUBY_VERSION >= '2.1'
    line.scrub
  else
    line.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
  end
end

#secure_hashesArray<String>

Returns target sha1 hash.

Returns:

  • (Array<String>)

    target sha1 hash



65
66
67
# File 'lib/git_diff_parser/patches.rb', line 65

def secure_hashes
  map(&:secure_hash)
end