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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
|
# Copyright (C) 2004, 2005 Aaron Bentley
# <aaron.bentley@utoronto.ca>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
import sys
class PatchSyntax(Exception):
def __init__(self, msg):
Exception.__init__(self, msg)
class MalformedPatchHeader(PatchSyntax):
def __init__(self, desc, line):
self.desc = desc
self.line = line
msg = "Malformed patch header. %s\n%s" % (self.desc, self.line)
PatchSyntax.__init__(self, msg)
class MalformedHunkHeader(PatchSyntax):
def __init__(self, desc, line):
self.desc = desc
self.line = line
msg = "Malformed hunk header. %s\n%s" % (self.desc, self.line)
PatchSyntax.__init__(self, msg)
class MalformedLine(PatchSyntax):
def __init__(self, desc, line):
self.desc = desc
self.line = line
msg = "Malformed line. %s\n%s" % (self.desc, self.line)
PatchSyntax.__init__(self, msg)
def get_patch_names(iter_lines):
try:
line = iter_lines.next()
if line.startswith("*** "):
line = iter_lines.next()
if not line.startswith("--- "):
raise MalformedPatchHeader("No orig name", line)
else:
orig_name = line[4:].rstrip("\n")
except StopIteration:
raise MalformedPatchHeader("No orig line", "")
try:
line = iter_lines.next()
if not line.startswith("+++ "):
raise PatchSyntax("No mod name")
else:
mod_name = line[4:].rstrip("\n")
except StopIteration:
raise MalformedPatchHeader("No mod line", "")
return (orig_name, mod_name)
def parse_range(textrange):
"""Parse a patch range, handling the "1" special-case
:param textrange: The text to parse
:type textrange: str
:return: the position and range, as a tuple
:rtype: (int, int)
"""
tmp = textrange.split(',')
if len(tmp) == 1:
pos = tmp[0]
range = "1"
else:
(pos, range) = tmp
pos = int(pos)
range = int(range)
return (pos, range)
def hunk_from_header(line):
if not line.startswith("@@") or not line.endswith("@@\n") \
or not len(line) > 4:
raise MalformedHunkHeader("Does not start and end with @@.", line)
try:
(orig, mod) = line[3:-4].split(" ")
except Exception, e:
raise MalformedHunkHeader(str(e), line)
if not orig.startswith('-') or not mod.startswith('+'):
raise MalformedHunkHeader("Positions don't start with + or -.", line)
try:
(orig_pos, orig_range) = parse_range(orig[1:])
(mod_pos, mod_range) = parse_range(mod[1:])
except Exception, e:
raise MalformedHunkHeader(str(e), line)
if mod_range < 0 or orig_range < 0:
raise MalformedHunkHeader("Hunk range is negative", line)
return Hunk(orig_pos, orig_range, mod_pos, mod_range)
class HunkLine:
def __init__(self, contents):
self.contents = contents
def get_str(self, leadchar):
if self.contents == "\n" and leadchar == " " and False:
return "\n"
return leadchar + self.contents
def invert(self):
return self
class ContextLine(HunkLine):
def __init__(self, contents):
HunkLine.__init__(self, contents)
def __str__(self):
return self.get_str(" ")
class InsertLine(HunkLine):
def __init__(self, contents):
HunkLine.__init__(self, contents)
def __str__(self):
return self.get_str("+")
def invert(self):
return RemoveLine(self.contents)
class RemoveLine(HunkLine):
def __init__(self, contents):
HunkLine.__init__(self, contents)
def __str__(self):
return self.get_str("-")
def invert(self):
return InsertLine(self.contents)
__pychecker__="no-returnvalues"
def parse_line(line):
if line.startswith("\n"):
return ContextLine(line)
elif line.startswith(" "):
return ContextLine(line[1:])
elif line.startswith("+"):
return InsertLine(line[1:])
elif line.startswith("-"):
return RemoveLine(line[1:])
else:
raise MalformedLine("Unknown line type", line)
__pychecker__=""
class Hunk:
def __init__(self, orig_pos, orig_range, mod_pos, mod_range):
self.orig_pos = orig_pos
self.orig_range = orig_range
self.mod_pos = mod_pos
self.mod_range = mod_range
self.lines = []
def get_header(self):
return "@@ -%s +%s @@\n" % (self.range_str(self.orig_pos,
self.orig_range),
self.range_str(self.mod_pos,
self.mod_range))
def range_str(self, pos, range):
"""Return a file range, special-casing for 1-line files.
:param pos: The position in the file
:type pos: int
:range: The range in the file
:type range: int
:return: a string in the format 1,4 except when range == pos == 1
"""
if range == 1:
return "%i" % pos
else:
return "%i,%i" % (pos, range)
def __str__(self):
lines = [self.get_header()]
for line in self.lines:
lines.append(str(line))
return "".join(lines)
def shift_to_mod(self, pos):
if pos < self.orig_pos-1:
return 0
elif pos > self.orig_pos+self.orig_range:
return self.mod_range - self.orig_range
else:
return self.shift_to_mod_lines(pos)
def shift_to_mod_lines(self, pos):
assert (pos >= self.orig_pos-1 and pos <= self.orig_pos+self.orig_range)
position = self.orig_pos-1
shift = 0
for line in self.lines:
if isinstance(line, InsertLine):
shift += 1
elif isinstance(line, RemoveLine):
if position == pos:
return None
shift -= 1
position += 1
elif isinstance(line, ContextLine):
position += 1
if position > pos:
break
return shift
def invert(self):
clone = Hunk(self.mod_pos, self.mod_range, self.orig_pos, self.orig_range)
for line in self.lines:
clone.lines.append(line.invert())
return clone
def iter_hunks(iter_lines):
hunk = None
for line in iter_lines:
if line.startswith("@@"):
if hunk is not None:
yield hunk
hunk = hunk_from_header(line)
else:
hunk.lines.append(parse_line(line))
if hunk is not None:
yield hunk
class Patch:
def __init__(self, oldname, newname):
self.oldname = oldname
self.newname = newname
self.hunks = []
def __str__(self):
ret = "--- %s\n+++ %s\n" % (self.oldname, self.newname)
ret += "".join([str(h) for h in self.hunks])
return ret
def invert(self):
clone = Patch(self.newname, self.oldname)
for hunk in self.hunks:
clone.hunks.append(hunk.invert())
return clone
def stats_str(self):
"""Return a string of patch statistics"""
removes = 0
inserts = 0
for hunk in self.hunks:
for line in hunk.lines:
if isinstance(line, InsertLine):
inserts+=1;
elif isinstance(line, RemoveLine):
removes+=1;
return "%i inserts, %i removes in %i hunks" % \
(inserts, removes, len(self.hunks))
def pos_in_mod(self, position):
newpos = position
for hunk in self.hunks:
shift = hunk.shift_to_mod(position)
if shift is None:
return None
newpos += shift
return newpos
def iter_inserted(self):
"""Iteraties through inserted lines
:return: Pair of line number, line
:rtype: iterator of (int, InsertLine)
"""
for hunk in self.hunks:
pos = hunk.mod_pos - 1;
for line in hunk.lines:
if isinstance(line, InsertLine):
yield (pos, line)
pos += 1
if isinstance(line, ContextLine):
pos += 1
def parse_patch(iter_lines):
(orig_name, mod_name) = get_patch_names(iter_lines)
patch = Patch(orig_name, mod_name)
for hunk in iter_hunks(iter_lines):
patch.hunks.append(hunk)
return patch
def parse_patches(iter_lines):
def parse(lines):
if len(lines) > 0:
return [ parse_patch(lines.__iter__()) ]
else:
return []
patches = []
saved_lines = []
while True:
try: line = iter_lines.next()
except StopIteration:
patches.extend(parse(saved_lines))
break
if line.startswith('*** '):
patches.extend(parse(saved_lines))
saved_lines = []
continue
elif line.startswith('--- ') and len(saved_lines) > 1:
patches.extend(parse(saved_lines))
saved_lines = [ line ]
continue
saved_lines.append(line)
return patches
|