-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathpatches.rb
More file actions
76 lines (70 loc) · 1.89 KB
/
patches.rb
File metadata and controls
76 lines (70 loc) · 1.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
require 'delegate'
module GitDiffParser
# The array of patch
class Patches < DelegateClass(Array)
# @return [Patches<Patch>]
def self.[](*ary)
new(ary)
end
# @param contents [String] `git diff` result
#
# @return [Patches<Patch>] parsed object
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 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 %r{^\-\-\- a/(?<file_name>.*)}
file_name = Regexp.last_match[:file_name]
body = true
when %r{^\+\+\+ b/(?<file_name>.*)}
file_name = Regexp.last_match[:file_name]
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
# @return [Patches<Patch>]
def initialize(*args)
super Array.new(*args)
end
# @return [Array<String>] file path
def files
map(&:file)
end
# @return [Array<String>] target sha1 hash
def secure_hashes
map(&:secure_hash)
end
# @param file [String] file path
#
# @return [Patch, nil]
def find_patch_by_file(file)
find { |patch| patch.file == file }
end
# @param secure_hash [String] target sha1 hash
#
# @return [Patch, nil]
def find_patch_by_secure_hash(secure_hash)
find { |patch| patch.secure_hash == secure_hash }
end
end
end