-
Notifications
You must be signed in to change notification settings - Fork 16
Expand file tree
/
Copy pathpatches.rb
More file actions
90 lines (83 loc) · 2.29 KB
/
patches.rb
File metadata and controls
90 lines (83 loc) · 2.29 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
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 = ''
orig_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 = ''
orig_file_name = ''
end
body = false
when %r{^\-\-\- a/(?<file_name>.*)}
orig_file_name = Regexp.last_match[:file_name]
when %r{^\+\+\+ b/(?<file_name>.*)}
file_name = Regexp.last_match[:file_name]
body = true
when %r{^\+\+\+ /dev/null}
file_name = orig_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 = ''
orig_file_name = ''
end
end
end
parsed
end
# @return [String]
def scrub_string(line)
if RUBY_VERSION >= '2.1'
line.scrub
else
line.encode('UTF-8', 'binary', invalid: :replace, undef: :replace, replace: '')
end
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