/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/patches.py

  • Committer: Jelmer Vernooij
  • Date: 2018-05-20 23:20:37 UTC
  • mto: (6973.5.1 python3-c)
  • mto: This revision was merged to the branch mainline in revision 6984.
  • Revision ID: jelmer@jelmer.uk-20180520232037-inu6kdob1k6gwsyd
Fix a bunch of tests.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
17
 
 
18
from __future__ import absolute_import
 
19
 
 
20
from .errors import (
 
21
    BzrError,
 
22
    )
 
23
 
17
24
import re
18
25
 
19
26
 
20
27
binary_files_re = 'Binary files (.*) and (.*) differ\n'
21
28
 
22
29
 
23
 
class BinaryFiles(Exception):
 
30
class PatchSyntax(BzrError):
 
31
    """Base class for patch syntax errors."""
 
32
 
 
33
 
 
34
class BinaryFiles(BzrError):
 
35
 
 
36
    _fmt = 'Binary files section encountered.'
24
37
 
25
38
    def __init__(self, orig_name, mod_name):
26
39
        self.orig_name = orig_name
27
40
        self.mod_name = mod_name
28
 
        Exception.__init__(self, 'Binary files section encountered.')
29
 
 
30
 
 
31
 
class PatchSyntax(Exception):
32
 
    def __init__(self, msg):
33
 
        Exception.__init__(self, msg)
34
41
 
35
42
 
36
43
class MalformedPatchHeader(PatchSyntax):
37
 
    def __init__(self, desc, line):
38
 
        self.desc = desc
39
 
        self.line = line
40
 
        msg = "Malformed patch header.  %s\n%r" % (self.desc, self.line)
41
 
        PatchSyntax.__init__(self, msg)
42
 
 
43
 
 
44
 
class MalformedHunkHeader(PatchSyntax):
45
 
    def __init__(self, desc, line):
46
 
        self.desc = desc
47
 
        self.line = line
48
 
        msg = "Malformed hunk header.  %s\n%r" % (self.desc, self.line)
49
 
        PatchSyntax.__init__(self, msg)
 
44
 
 
45
    _fmt = "Malformed patch header.  %(desc)s\n%(line)r"
 
46
 
 
47
    def __init__(self, desc, line):
 
48
        self.desc = desc
 
49
        self.line = line
50
50
 
51
51
 
52
52
class MalformedLine(PatchSyntax):
 
53
 
 
54
    _fmt = "Malformed line.  %(desc)s\n%(line)r"
 
55
 
53
56
    def __init__(self, desc, line):
54
57
        self.desc = desc
55
58
        self.line = line
56
 
        msg = "Malformed line.  %s\n%s" % (self.desc, self.line)
57
 
        PatchSyntax.__init__(self, msg)
58
 
 
59
 
 
60
 
class PatchConflict(Exception):
 
59
 
 
60
 
 
61
class PatchConflict(BzrError):
 
62
 
 
63
    _fmt = ('Text contents mismatch at line %(line_no)d.  Original has '
 
64
            '"%(orig_line)s", but patch says it should be "%(patch_line)s"')
 
65
 
61
66
    def __init__(self, line_no, orig_line, patch_line):
62
 
        orig = orig_line.rstrip('\n')
63
 
        patch = str(patch_line).rstrip('\n')
64
 
        msg = 'Text contents mismatch at line %d.  Original has "%s",'\
65
 
            ' but patch says it should be "%s"' % (line_no, orig, patch)
66
 
        Exception.__init__(self, msg)
 
67
        self.line_no = line_no
 
68
        self.orig_line = orig_line.rstrip('\n')
 
69
        self.patch_line = patch_line.rstrip('\n')
 
70
 
 
71
 
 
72
class MalformedHunkHeader(PatchSyntax):
 
73
 
 
74
    _fmt = "Malformed hunk header.  %(desc)s\n%(line)r"
 
75
 
 
76
    def __init__(self, desc, line):
 
77
        self.desc = desc
 
78
        self.line = line
67
79
 
68
80
 
69
81
def get_patch_names(iter_lines):
 
82
    line = next(iter_lines)
70
83
    try:
71
 
        line = iter_lines.next()
72
84
        match = re.match(binary_files_re, line)
73
85
        if match is not None:
74
86
            raise BinaryFiles(match.group(1), match.group(2))
79
91
    except StopIteration:
80
92
        raise MalformedPatchHeader("No orig line", "")
81
93
    try:
82
 
        line = iter_lines.next()
 
94
        line = next(iter_lines)
83
95
        if not line.startswith("+++ "):
84
96
            raise PatchSyntax("No mod name")
85
97
        else:
115
127
        raise MalformedHunkHeader("Does not match format.", line)
116
128
    try:
117
129
        (orig, mod) = matches.group(1).split(" ")
118
 
    except (ValueError, IndexError), e:
 
130
    except (ValueError, IndexError) as e:
119
131
        raise MalformedHunkHeader(str(e), line)
120
132
    if not orig.startswith('-') or not mod.startswith('+'):
121
133
        raise MalformedHunkHeader("Positions don't start with + or -.", line)
122
134
    try:
123
135
        (orig_pos, orig_range) = parse_range(orig[1:])
124
136
        (mod_pos, mod_range) = parse_range(mod[1:])
125
 
    except (ValueError, IndexError), e:
 
137
    except (ValueError, IndexError) as e:
126
138
        raise MalformedHunkHeader(str(e), line)
127
139
    if mod_range < 0 or orig_range < 0:
128
140
        raise MalformedHunkHeader("Hunk range is negative", line)
278
290
        orig_size = 0
279
291
        mod_size = 0
280
292
        while orig_size < hunk.orig_range or mod_size < hunk.mod_range:
281
 
            hunk_line = parse_line(iter_lines.next())
 
293
            hunk_line = parse_line(next(iter_lines))
282
294
            hunk.lines.append(hunk_line)
283
295
            if isinstance(hunk_line, (RemoveLine, ContextLine)):
284
296
                orig_size += 1
352
364
                if isinstance(line, ContextLine):
353
365
                    pos += 1
354
366
 
355
 
 
356
367
def parse_patch(iter_lines, allow_dirty=False):
357
368
    '''
358
369
    :arg iter_lines: iterable of lines to parse
362
373
    iter_lines = iter_lines_handle_nl(iter_lines)
363
374
    try:
364
375
        (orig_name, mod_name) = get_patch_names(iter_lines)
365
 
    except BinaryFiles, e:
 
376
    except BinaryFiles as e:
366
377
        return BinaryPatch(e.orig_name, e.mod_name)
367
378
    else:
368
379
        patch = Patch(orig_name, mod_name)
371
382
        return patch
372
383
 
373
384
 
374
 
def iter_file_patch(iter_lines, allow_dirty=False):
 
385
def iter_file_patch(iter_lines, allow_dirty=False, keep_dirty=False):
375
386
    '''
376
387
    :arg iter_lines: iterable of lines to parse for patches
377
388
    :kwarg allow_dirty: If True, allow comments and other non-patch text
387
398
    # (as allow_dirty does).
388
399
    regex = re.compile(binary_files_re)
389
400
    saved_lines = []
 
401
    dirty_head = []
390
402
    orig_range = 0
391
403
    beginning = True
 
404
 
392
405
    for line in iter_lines:
393
 
        if line.startswith('=== ') or line.startswith('*** '):
 
406
        if line.startswith('=== '):
 
407
            if len(saved_lines) > 0:
 
408
                if keep_dirty and len(dirty_head) > 0:
 
409
                    yield {'saved_lines': saved_lines,
 
410
                           'dirty_head': dirty_head}
 
411
                    dirty_head = []
 
412
                else:
 
413
                    yield saved_lines
 
414
                saved_lines = []
 
415
            dirty_head.append(line)
 
416
            continue
 
417
        if line.startswith('*** '):
394
418
            continue
395
419
        if line.startswith('#'):
396
420
            continue
404
428
                # parse the patch
405
429
                beginning = False
406
430
            elif len(saved_lines) > 0:
407
 
                yield saved_lines
 
431
                if keep_dirty and len(dirty_head) > 0:
 
432
                    yield {'saved_lines': saved_lines,
 
433
                           'dirty_head': dirty_head}
 
434
                    dirty_head = []
 
435
                else:
 
436
                    yield saved_lines
408
437
            saved_lines = []
409
438
        elif line.startswith('@@'):
410
439
            hunk = hunk_from_header(line)
411
440
            orig_range = hunk.orig_range
412
441
        saved_lines.append(line)
413
442
    if len(saved_lines) > 0:
414
 
        yield saved_lines
 
443
        if keep_dirty and len(dirty_head) > 0:
 
444
            yield {'saved_lines': saved_lines,
 
445
                   'dirty_head': dirty_head}
 
446
        else:
 
447
            yield saved_lines
415
448
 
416
449
 
417
450
def iter_lines_handle_nl(iter_lines):
435
468
        yield last_line
436
469
 
437
470
 
438
 
def parse_patches(iter_lines, allow_dirty=False):
 
471
def parse_patches(iter_lines, allow_dirty=False, keep_dirty=False):
439
472
    '''
440
473
    :arg iter_lines: iterable of lines to parse for patches
441
474
    :kwarg allow_dirty: If True, allow text that's not part of the patch at
442
475
        selected places.  This includes comments before and after a patch
443
476
        for instance.  Default False.
 
477
    :kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
 
478
        Default False.
444
479
    '''
445
 
    return [parse_patch(f.__iter__(), allow_dirty) for f in
446
 
                        iter_file_patch(iter_lines, allow_dirty)]
 
480
    patches = []
 
481
    for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
 
482
        if 'dirty_head' in patch_lines:
 
483
            patches.append({'patch': parse_patch(
 
484
                patch_lines['saved_lines'], allow_dirty),
 
485
                            'dirty_head': patch_lines['dirty_head']})
 
486
        else:
 
487
            patches.append(parse_patch(patch_lines, allow_dirty))
 
488
    return patches
447
489
 
448
490
 
449
491
def difference_index(atext, btext):
487
529
        orig_lines = iter(orig_lines)
488
530
    for hunk in hunks:
489
531
        while line_no < hunk.orig_pos:
490
 
            orig_line = orig_lines.next()
 
532
            orig_line = next(orig_lines)
491
533
            yield orig_line
492
534
            line_no += 1
493
535
        for hunk_line in hunk.lines:
495
537
            if isinstance(hunk_line, InsertLine):
496
538
                yield hunk_line.contents
497
539
            elif isinstance(hunk_line, (ContextLine, RemoveLine)):
498
 
                orig_line = orig_lines.next()
 
540
                orig_line = next(orig_lines)
499
541
                if orig_line != hunk_line.contents:
500
542
                    raise PatchConflict(line_no, orig_line, "".join(seen_patch))
501
543
                if isinstance(hunk_line, ContextLine):