1
# Copyright (C) 2004 - 2006 Aaron Bentley
1
# Copyright (C) 2004 - 2006, 2008 Aaron Bentley, Canonical Ltd
2
2
# <aaron.bentley@utoronto.ca>
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
4
# This program is free software; you can redistribute it and/or modify
5
# it under the terms of the GNU General Public License as published by
6
# the Free Software Foundation; either version 2 of the License, or
7
# (at your option) any later version.
9
# This program is distributed in the hope that it will be useful,
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12
# GNU General Public License for more details.
14
# You should have received a copy of the GNU General Public License
15
# along with this program; if not, write to the Free Software
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20
class BinaryFiles(Exception):
22
def __init__(self, orig_name, mod_name):
23
self.orig_name = orig_name
24
self.mod_name = mod_name
25
Exception.__init__(self, 'Binary files section encountered.')
19
28
class PatchSyntax(Exception):
57
66
def get_patch_names(iter_lines):
59
68
line = iter_lines.next()
69
match = re.match('Binary files (.*) and (.*) differ\n', line)
71
raise BinaryFiles(match.group(1), match.group(2))
60
72
if not line.startswith("--- "):
61
73
raise MalformedPatchHeader("No orig name", line)
92
104
range = int(range)
93
105
return (pos, range)
96
108
def hunk_from_header(line):
97
if not line.startswith("@@") or not line.endswith("@@\n") \
99
raise MalformedHunkHeader("Does not start and end with @@.", line)
110
matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
112
raise MalformedHunkHeader("Does not match format.", line)
101
(orig, mod) = line[3:-4].split(" ")
114
(orig, mod) = matches.group(1).split(" ")
115
except (ValueError, IndexError), e:
103
116
raise MalformedHunkHeader(str(e), line)
104
117
if not orig.startswith('-') or not mod.startswith('+'):
105
118
raise MalformedHunkHeader("Positions don't start with + or -.", line)
107
120
(orig_pos, orig_range) = parse_range(orig[1:])
108
121
(mod_pos, mod_range) = parse_range(mod[1:])
122
except (ValueError, IndexError), e:
110
123
raise MalformedHunkHeader(str(e), line)
111
124
if mod_range < 0 or orig_range < 0:
112
125
raise MalformedHunkHeader("Hunk range is negative", line)
113
return Hunk(orig_pos, orig_range, mod_pos, mod_range)
126
tail = matches.group(3)
127
return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
162
176
return InsertLine(line[1:])
163
177
elif line.startswith("-"):
164
178
return RemoveLine(line[1:])
168
180
raise MalformedLine("Unknown line type", line)
173
def __init__(self, orig_pos, orig_range, mod_pos, mod_range):
185
def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
174
186
self.orig_pos = orig_pos
175
187
self.orig_range = orig_range
176
188
self.mod_pos = mod_pos
177
189
self.mod_range = mod_range
180
193
def get_header(self):
181
return "@@ -%s +%s @@\n" % (self.range_str(self.orig_pos,
183
self.range_str(self.mod_pos,
194
if self.tail is None:
197
tail_str = ' ' + self.tail
198
return "@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
200
self.range_str(self.mod_pos,
186
204
def range_str(self, pos, range):
187
205
"""Return a file range, special-casing for 1-line files.
274
class BinaryPatch(object):
258
275
def __init__(self, oldname, newname):
259
276
self.oldname = oldname
260
277
self.newname = newname
280
return 'Binary files %s and %s differ\n' % (self.oldname, self.newname)
283
class Patch(BinaryPatch):
285
def __init__(self, oldname, newname):
286
BinaryPatch.__init__(self, oldname, newname)
263
289
def __str__(self):
264
ret = self.get_header()
290
ret = self.get_header()
265
291
ret += "".join([str(h) for h in self.hunks])
268
294
def get_header(self):
269
295
return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
272
"""Return a string of patch statistics"""
297
def stats_values(self):
298
"""Calculate the number of inserts and removes."""
275
301
for hunk in self.hunks:
279
305
elif isinstance(line, RemoveLine):
307
return (inserts, removes, len(self.hunks))
310
"""Return a string of patch statistics"""
281
311
return "%i inserts, %i removes in %i hunks" % \
282
(inserts, removes, len(self.hunks))
284
314
def pos_in_mod(self, position):
285
315
newpos = position
309
339
def parse_patch(iter_lines):
310
(orig_name, mod_name) = get_patch_names(iter_lines)
311
patch = Patch(orig_name, mod_name)
312
for hunk in iter_hunks(iter_lines):
313
patch.hunks.append(hunk)
340
iter_lines = iter_lines_handle_nl(iter_lines)
342
(orig_name, mod_name) = get_patch_names(iter_lines)
343
except BinaryFiles, e:
344
return BinaryPatch(e.orig_name, e.mod_name)
346
patch = Patch(orig_name, mod_name)
347
for hunk in iter_hunks(iter_lines):
348
patch.hunks.append(hunk)
317
352
def iter_file_patch(iter_lines):
319
355
for line in iter_lines:
320
356
if line.startswith('=== ') or line.startswith('*** '):
322
358
if line.startswith('#'):
361
if line.startswith('-') or line.startswith(' '):
324
363
elif line.startswith('--- '):
325
364
if len(saved_lines) > 0:
326
365
yield saved_lines
367
elif line.startswith('@@'):
368
hunk = hunk_from_header(line)
369
orig_range = hunk.orig_range
328
370
saved_lines.append(line)
329
371
if len(saved_lines) > 0:
330
372
yield saved_lines
378
420
"""Iterate through a series of lines with a patch applied.
379
421
This handles a single file, and does exact, not fuzzy patching.
381
if orig_lines is not None:
382
orig_lines = orig_lines.__iter__()
423
patch_lines = iter_lines_handle_nl(iter(patch_lines))
424
get_patch_names(patch_lines)
425
return iter_patched_from_hunks(orig_lines, iter_hunks(patch_lines))
428
def iter_patched_from_hunks(orig_lines, hunks):
429
"""Iterate through a series of lines with a patch applied.
430
This handles a single file, and does exact, not fuzzy patching.
432
:param orig_lines: The unpatched lines.
433
:param hunks: An iterable of Hunk instances.
384
patch_lines = iter_lines_handle_nl(patch_lines.__iter__())
385
get_patch_names(patch_lines)
387
for hunk in iter_hunks(patch_lines):
437
if orig_lines is not None:
438
orig_lines = iter(orig_lines)
388
440
while line_no < hunk.orig_pos:
389
441
orig_line = orig_lines.next()
400
452
if isinstance(hunk_line, ContextLine):
403
assert isinstance(hunk_line, RemoveLine)
455
if not isinstance(hunk_line, RemoveLine):
456
raise AssertionError(hunk_line)
405
458
if orig_lines is not None:
406
459
for line in orig_lines: