14
14
# You should have received a copy of the GNU General Public License
15
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
18
from __future__ import absolute_import
20
from bzrlib.errors import (
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32
binary_files_re = 'Binary files (.*) and (.*) differ\n'
20
class PatchSyntax(Exception):
21
def __init__(self, msg):
22
Exception.__init__(self, msg)
25
class MalformedPatchHeader(PatchSyntax):
26
def __init__(self, desc, line):
29
msg = "Malformed patch header. %s\n%r" % (self.desc, self.line)
30
PatchSyntax.__init__(self, msg)
33
class MalformedHunkHeader(PatchSyntax):
34
def __init__(self, desc, line):
37
msg = "Malformed hunk header. %s\n%r" % (self.desc, self.line)
38
PatchSyntax.__init__(self, msg)
41
class MalformedLine(PatchSyntax):
42
def __init__(self, desc, line):
45
msg = "Malformed line. %s\n%s" % (self.desc, self.line)
46
PatchSyntax.__init__(self, msg)
49
class PatchConflict(Exception):
50
def __init__(self, line_no, orig_line, patch_line):
51
orig = orig_line.rstrip('\n')
52
patch = str(patch_line).rstrip('\n')
53
msg = 'Text contents mismatch at line %d. Original has "%s",'\
54
' but patch says it should be "%s"' % (line_no, orig, patch)
55
Exception.__init__(self, msg)
34
58
def get_patch_names(iter_lines):
36
60
line = iter_lines.next()
37
match = re.match(binary_files_re, line)
39
raise BinaryFiles(match.group(1), match.group(2))
40
61
if not line.startswith("--- "):
41
62
raise MalformedPatchHeader("No orig name", line)
218
def iter_hunks(iter_lines, allow_dirty=False):
220
:arg iter_lines: iterable of lines to parse for hunks
221
:kwarg allow_dirty: If True, when we encounter something that is not
222
a hunk header when we're looking for one, assume the rest of the lines
223
are not part of the patch (comments or other junk). Default False
241
def iter_hunks(iter_lines):
226
243
for line in iter_lines:
232
249
if hunk is not None:
235
hunk = hunk_from_header(line)
236
except MalformedHunkHeader:
238
# If the line isn't a hunk header, then we've reached the end
239
# of this patch and there's "junk" at the end. Ignore the
240
# rest of this patch.
251
hunk = hunk_from_header(line)
245
254
while orig_size < hunk.orig_range or mod_size < hunk.mod_range:
256
class BinaryPatch(object):
257
266
def __init__(self, oldname, newname):
258
267
self.oldname = oldname
259
268
self.newname = newname
262
return 'Binary files %s and %s differ\n' % (self.oldname, self.newname)
265
class Patch(BinaryPatch):
267
def __init__(self, oldname, newname):
268
BinaryPatch.__init__(self, oldname, newname)
271
271
def __str__(self):
272
ret = self.get_header()
272
ret = self.get_header()
273
273
ret += "".join([str(h) for h in self.hunks])
276
276
def get_header(self):
277
277
return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
279
def stats_values(self):
280
"""Calculate the number of inserts and removes."""
280
"""Return a string of patch statistics"""
283
283
for hunk in self.hunks:
287
287
elif isinstance(line, RemoveLine):
289
return (inserts, removes, len(self.hunks))
292
"""Return a string of patch statistics"""
293
289
return "%i inserts, %i removes in %i hunks" % \
290
(inserts, removes, len(self.hunks))
296
292
def pos_in_mod(self, position):
297
293
newpos = position
321
def parse_patch(iter_lines, allow_dirty=False):
323
:arg iter_lines: iterable of lines to parse
324
:kwarg allow_dirty: If True, allow the patch to have trailing junk.
327
iter_lines = iter_lines_handle_nl(iter_lines)
329
(orig_name, mod_name) = get_patch_names(iter_lines)
330
except BinaryFiles, e:
331
return BinaryPatch(e.orig_name, e.mod_name)
333
patch = Patch(orig_name, mod_name)
334
for hunk in iter_hunks(iter_lines, allow_dirty):
335
patch.hunks.append(hunk)
339
def iter_file_patch(iter_lines, allow_dirty=False):
341
:arg iter_lines: iterable of lines to parse for patches
342
:kwarg allow_dirty: If True, allow comments and other non-patch text
343
before the first patch. Note that the algorithm here can only find
344
such text before any patches have been found. Comments after the
345
first patch are stripped away in iter_hunks() if it is also passed
346
allow_dirty=True. Default False.
348
### FIXME: Docstring is not quite true. We allow certain comments no
349
# matter what, If they startwith '===', '***', or '#' Someone should
350
# reexamine this logic and decide if we should include those in
351
# allow_dirty or restrict those to only being before the patch is found
352
# (as allow_dirty does).
353
regex = re.compile(binary_files_re)
317
def parse_patch(iter_lines):
318
(orig_name, mod_name) = get_patch_names(iter_lines)
319
patch = Patch(orig_name, mod_name)
320
for hunk in iter_hunks(iter_lines):
321
patch.hunks.append(hunk)
325
def iter_file_patch(iter_lines):
357
328
for line in iter_lines:
358
329
if line.startswith('=== ') or line.startswith('*** '):
362
333
elif orig_range > 0:
363
334
if line.startswith('-') or line.startswith(' '):
365
elif line.startswith('--- ') or regex.match(line):
366
if allow_dirty and beginning:
367
# Patches can have "junk" at the beginning
368
# Stripping junk from the end of patches is handled when we
371
elif len(saved_lines) > 0:
336
elif line.startswith('--- '):
337
if len(saved_lines) > 0:
372
338
yield saved_lines
374
340
elif line.startswith('@@'):
403
def parse_patches(iter_lines, allow_dirty=False):
405
:arg iter_lines: iterable of lines to parse for patches
406
:kwarg allow_dirty: If True, allow text that's not part of the patch at
407
selected places. This includes comments before and after a patch
408
for instance. Default False.
410
return [parse_patch(f.__iter__(), allow_dirty) for f in
411
iter_file_patch(iter_lines, allow_dirty)]
368
def parse_patches(iter_lines):
369
iter_lines = iter_lines_handle_nl(iter_lines)
370
return [parse_patch(f.__iter__()) for f in iter_file_patch(iter_lines)]
414
373
def difference_index(atext, btext):
434
393
"""Iterate through a series of lines with a patch applied.
435
394
This handles a single file, and does exact, not fuzzy patching.
437
patch_lines = iter_lines_handle_nl(iter(patch_lines))
396
if orig_lines is not None:
397
orig_lines = orig_lines.__iter__()
399
patch_lines = iter_lines_handle_nl(patch_lines.__iter__())
438
400
get_patch_names(patch_lines)
439
return iter_patched_from_hunks(orig_lines, iter_hunks(patch_lines))
442
def iter_patched_from_hunks(orig_lines, hunks):
443
"""Iterate through a series of lines with a patch applied.
444
This handles a single file, and does exact, not fuzzy patching.
446
:param orig_lines: The unpatched lines.
447
:param hunks: An iterable of Hunk instances.
451
if orig_lines is not None:
452
orig_lines = iter(orig_lines)
402
for hunk in iter_hunks(patch_lines):
454
403
while line_no < hunk.orig_pos:
455
404
orig_line = orig_lines.next()