~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/patches.py

  • Committer: Vincent Ladeuil
  • Date: 2016-02-01 19:26:41 UTC
  • mto: This revision was merged to the branch mainline in revision 6616.
  • Revision ID: v.ladeuil+lp@free.fr-20160201192641-mzn90m51rydhw00n
Open trunk again as 2.8b1

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004 - 2006, 2008 Aaron Bentley, Canonical Ltd
 
1
# Copyright (C) 2005-2010 Aaron Bentley, Canonical Ltd
2
2
# <aaron.bentley@utoronto.ca>
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
15
15
# along with this program; if not, write to the Free Software
16
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
17
 
18
 
 
19
 
class PatchSyntax(Exception):
20
 
    def __init__(self, msg):
21
 
        Exception.__init__(self, msg)
22
 
 
23
 
 
24
 
class MalformedPatchHeader(PatchSyntax):
25
 
    def __init__(self, desc, line):
26
 
        self.desc = desc
27
 
        self.line = line
28
 
        msg = "Malformed patch header.  %s\n%r" % (self.desc, self.line)
29
 
        PatchSyntax.__init__(self, msg)
30
 
 
31
 
 
32
 
class MalformedHunkHeader(PatchSyntax):
33
 
    def __init__(self, desc, line):
34
 
        self.desc = desc
35
 
        self.line = line
36
 
        msg = "Malformed hunk header.  %s\n%r" % (self.desc, self.line)
37
 
        PatchSyntax.__init__(self, msg)
38
 
 
39
 
 
40
 
class MalformedLine(PatchSyntax):
41
 
    def __init__(self, desc, line):
42
 
        self.desc = desc
43
 
        self.line = line
44
 
        msg = "Malformed line.  %s\n%s" % (self.desc, self.line)
45
 
        PatchSyntax.__init__(self, msg)
46
 
 
47
 
 
48
 
class PatchConflict(Exception):
49
 
    def __init__(self, line_no, orig_line, patch_line):
50
 
        orig = orig_line.rstrip('\n')
51
 
        patch = str(patch_line).rstrip('\n')
52
 
        msg = 'Text contents mismatch at line %d.  Original has "%s",'\
53
 
            ' but patch says it should be "%s"' % (line_no, orig, patch)
54
 
        Exception.__init__(self, msg)
 
18
from __future__ import absolute_import
 
19
 
 
20
from bzrlib.errors import (
 
21
    BinaryFiles,
 
22
    MalformedHunkHeader,
 
23
    MalformedLine,
 
24
    MalformedPatchHeader,
 
25
    PatchConflict,
 
26
    PatchSyntax,
 
27
    )
 
28
 
 
29
import re
 
30
 
 
31
 
 
32
binary_files_re = 'Binary files (.*) and (.*) differ\n'
55
33
 
56
34
 
57
35
def get_patch_names(iter_lines):
 
36
    line = iter_lines.next()
58
37
    try:
59
 
        line = iter_lines.next()
 
38
        match = re.match(binary_files_re, line)
 
39
        if match is not None:
 
40
            raise BinaryFiles(match.group(1), match.group(2))
60
41
        if not line.startswith("--- "):
61
42
            raise MalformedPatchHeader("No orig name", line)
62
43
        else:
235
216
        return shift
236
217
 
237
218
 
238
 
def iter_hunks(iter_lines):
 
219
def iter_hunks(iter_lines, allow_dirty=False):
 
220
    '''
 
221
    :arg iter_lines: iterable of lines to parse for hunks
 
222
    :kwarg allow_dirty: If True, when we encounter something that is not
 
223
        a hunk header when we're looking for one, assume the rest of the lines
 
224
        are not part of the patch (comments or other junk).  Default False
 
225
    '''
239
226
    hunk = None
240
227
    for line in iter_lines:
241
228
        if line == "\n":
245
232
            continue
246
233
        if hunk is not None:
247
234
            yield hunk
248
 
        hunk = hunk_from_header(line)
 
235
        try:
 
236
            hunk = hunk_from_header(line)
 
237
        except MalformedHunkHeader:
 
238
            if allow_dirty:
 
239
                # If the line isn't a hunk header, then we've reached the end
 
240
                # of this patch and there's "junk" at the end.  Ignore the
 
241
                # rest of this patch.
 
242
                return
 
243
            raise
249
244
        orig_size = 0
250
245
        mod_size = 0
251
246
        while orig_size < hunk.orig_range or mod_size < hunk.mod_range:
259
254
        yield hunk
260
255
 
261
256
 
262
 
class Patch:
 
257
class BinaryPatch(object):
263
258
    def __init__(self, oldname, newname):
264
259
        self.oldname = oldname
265
260
        self.newname = newname
 
261
 
 
262
    def __str__(self):
 
263
        return 'Binary files %s and %s differ\n' % (self.oldname, self.newname)
 
264
 
 
265
 
 
266
class Patch(BinaryPatch):
 
267
 
 
268
    def __init__(self, oldname, newname):
 
269
        BinaryPatch.__init__(self, oldname, newname)
266
270
        self.hunks = []
267
271
 
268
272
    def __str__(self):
314
318
                if isinstance(line, ContextLine):
315
319
                    pos += 1
316
320
 
317
 
 
318
 
def parse_patch(iter_lines):
 
321
def parse_patch(iter_lines, allow_dirty=False):
 
322
    '''
 
323
    :arg iter_lines: iterable of lines to parse
 
324
    :kwarg allow_dirty: If True, allow the patch to have trailing junk.
 
325
        Default False
 
326
    '''
319
327
    iter_lines = iter_lines_handle_nl(iter_lines)
320
 
    (orig_name, mod_name) = get_patch_names(iter_lines)
321
 
    patch = Patch(orig_name, mod_name)
322
 
    for hunk in iter_hunks(iter_lines):
323
 
        patch.hunks.append(hunk)
324
 
    return patch
325
 
 
326
 
 
327
 
def iter_file_patch(iter_lines):
 
328
    try:
 
329
        (orig_name, mod_name) = get_patch_names(iter_lines)
 
330
    except BinaryFiles, e:
 
331
        return BinaryPatch(e.orig_name, e.mod_name)
 
332
    else:
 
333
        patch = Patch(orig_name, mod_name)
 
334
        for hunk in iter_hunks(iter_lines, allow_dirty):
 
335
            patch.hunks.append(hunk)
 
336
        return patch
 
337
 
 
338
 
 
339
def iter_file_patch(iter_lines, allow_dirty=False, keep_dirty=False):
 
340
    '''
 
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.
 
347
    '''
 
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)
328
354
    saved_lines = []
 
355
    dirty_head = []
329
356
    orig_range = 0
 
357
    beginning = True
 
358
 
330
359
    for line in iter_lines:
331
 
        if line.startswith('=== ') or line.startswith('*** '):
 
360
        if line.startswith('=== '):
 
361
            if len(saved_lines) > 0:
 
362
                if keep_dirty and len(dirty_head) > 0:
 
363
                    yield {'saved_lines': saved_lines,
 
364
                           'dirty_head': dirty_head}
 
365
                    dirty_head = []
 
366
                else:
 
367
                    yield saved_lines
 
368
                saved_lines = []
 
369
            dirty_head.append(line)
 
370
            continue
 
371
        if line.startswith('*** '):
332
372
            continue
333
373
        if line.startswith('#'):
334
374
            continue
335
375
        elif orig_range > 0:
336
376
            if line.startswith('-') or line.startswith(' '):
337
377
                orig_range -= 1
338
 
        elif line.startswith('--- '):
339
 
            if len(saved_lines) > 0:
340
 
                yield saved_lines
 
378
        elif line.startswith('--- ') or regex.match(line):
 
379
            if allow_dirty and beginning:
 
380
                # Patches can have "junk" at the beginning
 
381
                # Stripping junk from the end of patches is handled when we
 
382
                # parse the patch
 
383
                beginning = False
 
384
            elif len(saved_lines) > 0:
 
385
                if keep_dirty and len(dirty_head) > 0:
 
386
                    yield {'saved_lines': saved_lines,
 
387
                           'dirty_head': dirty_head}
 
388
                    dirty_head = []
 
389
                else:
 
390
                    yield saved_lines
341
391
            saved_lines = []
342
392
        elif line.startswith('@@'):
343
393
            hunk = hunk_from_header(line)
344
394
            orig_range = hunk.orig_range
345
395
        saved_lines.append(line)
346
396
    if len(saved_lines) > 0:
347
 
        yield saved_lines
 
397
        if keep_dirty and len(dirty_head) > 0:
 
398
            yield {'saved_lines': saved_lines,
 
399
                   'dirty_head': dirty_head}
 
400
        else:
 
401
            yield saved_lines
348
402
 
349
403
 
350
404
def iter_lines_handle_nl(iter_lines):
368
422
        yield last_line
369
423
 
370
424
 
371
 
def parse_patches(iter_lines):
372
 
    return [parse_patch(f.__iter__()) for f in iter_file_patch(iter_lines)]
 
425
def parse_patches(iter_lines, allow_dirty=False, keep_dirty=False):
 
426
    '''
 
427
    :arg iter_lines: iterable of lines to parse for patches
 
428
    :kwarg allow_dirty: If True, allow text that's not part of the patch at
 
429
        selected places.  This includes comments before and after a patch
 
430
        for instance.  Default False.
 
431
    :kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
 
432
        Default False.
 
433
    '''
 
434
    patches = []
 
435
    for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
 
436
        if 'dirty_head' in patch_lines:
 
437
            patches.append({'patch': parse_patch(
 
438
                patch_lines['saved_lines'], allow_dirty),
 
439
                            'dirty_head': patch_lines['dirty_head']})
 
440
        else:
 
441
            patches.append(parse_patch(patch_lines, allow_dirty))
 
442
    return patches
373
443
 
374
444
 
375
445
def difference_index(atext, btext):