/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: 2017-06-10 01:39:46 UTC
  • mto: This revision was merged to the branch mainline in revision 6690.
  • Revision ID: jelmer@jelmer.uk-20170610013946-08donzxbo8iv0ewz
Fix more imports.

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
    BinaryFiles,
 
22
    MalformedHunkHeader,
 
23
    MalformedLine,
 
24
    MalformedPatchHeader,
 
25
    PatchConflict,
 
26
    PatchSyntax,
 
27
    )
 
28
 
17
29
import re
18
30
 
19
31
 
20
32
binary_files_re = 'Binary files (.*) and (.*) differ\n'
21
33
 
22
34
 
23
 
class BinaryFiles(Exception):
24
 
 
25
 
    def __init__(self, orig_name, mod_name):
26
 
        self.orig_name = orig_name
27
 
        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
 
 
35
 
 
36
 
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)
50
 
 
51
 
 
52
 
class MalformedLine(PatchSyntax):
53
 
    def __init__(self, desc, line):
54
 
        self.desc = desc
55
 
        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):
61
 
    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
 
 
68
 
 
69
35
def get_patch_names(iter_lines):
 
36
    line = next(iter_lines)
70
37
    try:
71
 
        line = iter_lines.next()
72
38
        match = re.match(binary_files_re, line)
73
39
        if match is not None:
74
40
            raise BinaryFiles(match.group(1), match.group(2))
79
45
    except StopIteration:
80
46
        raise MalformedPatchHeader("No orig line", "")
81
47
    try:
82
 
        line = iter_lines.next()
 
48
        line = next(iter_lines)
83
49
        if not line.startswith("+++ "):
84
50
            raise PatchSyntax("No mod name")
85
51
        else:
115
81
        raise MalformedHunkHeader("Does not match format.", line)
116
82
    try:
117
83
        (orig, mod) = matches.group(1).split(" ")
118
 
    except (ValueError, IndexError), e:
 
84
    except (ValueError, IndexError) as e:
119
85
        raise MalformedHunkHeader(str(e), line)
120
86
    if not orig.startswith('-') or not mod.startswith('+'):
121
87
        raise MalformedHunkHeader("Positions don't start with + or -.", line)
122
88
    try:
123
89
        (orig_pos, orig_range) = parse_range(orig[1:])
124
90
        (mod_pos, mod_range) = parse_range(mod[1:])
125
 
    except (ValueError, IndexError), e:
 
91
    except (ValueError, IndexError) as e:
126
92
        raise MalformedHunkHeader(str(e), line)
127
93
    if mod_range < 0 or orig_range < 0:
128
94
        raise MalformedHunkHeader("Hunk range is negative", line)
278
244
        orig_size = 0
279
245
        mod_size = 0
280
246
        while orig_size < hunk.orig_range or mod_size < hunk.mod_range:
281
 
            hunk_line = parse_line(iter_lines.next())
 
247
            hunk_line = parse_line(next(iter_lines))
282
248
            hunk.lines.append(hunk_line)
283
249
            if isinstance(hunk_line, (RemoveLine, ContextLine)):
284
250
                orig_size += 1
352
318
                if isinstance(line, ContextLine):
353
319
                    pos += 1
354
320
 
355
 
 
356
321
def parse_patch(iter_lines, allow_dirty=False):
357
322
    '''
358
323
    :arg iter_lines: iterable of lines to parse
362
327
    iter_lines = iter_lines_handle_nl(iter_lines)
363
328
    try:
364
329
        (orig_name, mod_name) = get_patch_names(iter_lines)
365
 
    except BinaryFiles, e:
 
330
    except BinaryFiles as e:
366
331
        return BinaryPatch(e.orig_name, e.mod_name)
367
332
    else:
368
333
        patch = Patch(orig_name, mod_name)
371
336
        return patch
372
337
 
373
338
 
374
 
def iter_file_patch(iter_lines, allow_dirty=False):
 
339
def iter_file_patch(iter_lines, allow_dirty=False, keep_dirty=False):
375
340
    '''
376
341
    :arg iter_lines: iterable of lines to parse for patches
377
342
    :kwarg allow_dirty: If True, allow comments and other non-patch text
387
352
    # (as allow_dirty does).
388
353
    regex = re.compile(binary_files_re)
389
354
    saved_lines = []
 
355
    dirty_head = []
390
356
    orig_range = 0
391
357
    beginning = True
 
358
 
392
359
    for line in iter_lines:
393
 
        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('*** '):
394
372
            continue
395
373
        if line.startswith('#'):
396
374
            continue
404
382
                # parse the patch
405
383
                beginning = False
406
384
            elif len(saved_lines) > 0:
407
 
                yield saved_lines
 
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
408
391
            saved_lines = []
409
392
        elif line.startswith('@@'):
410
393
            hunk = hunk_from_header(line)
411
394
            orig_range = hunk.orig_range
412
395
        saved_lines.append(line)
413
396
    if len(saved_lines) > 0:
414
 
        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
415
402
 
416
403
 
417
404
def iter_lines_handle_nl(iter_lines):
435
422
        yield last_line
436
423
 
437
424
 
438
 
def parse_patches(iter_lines, allow_dirty=False):
 
425
def parse_patches(iter_lines, allow_dirty=False, keep_dirty=False):
439
426
    '''
440
427
    :arg iter_lines: iterable of lines to parse for patches
441
428
    :kwarg allow_dirty: If True, allow text that's not part of the patch at
442
429
        selected places.  This includes comments before and after a patch
443
430
        for instance.  Default False.
 
431
    :kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
 
432
        Default False.
444
433
    '''
445
 
    return [parse_patch(f.__iter__(), allow_dirty) for f in
446
 
                        iter_file_patch(iter_lines, allow_dirty)]
 
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
447
443
 
448
444
 
449
445
def difference_index(atext, btext):
487
483
        orig_lines = iter(orig_lines)
488
484
    for hunk in hunks:
489
485
        while line_no < hunk.orig_pos:
490
 
            orig_line = orig_lines.next()
 
486
            orig_line = next(orig_lines)
491
487
            yield orig_line
492
488
            line_no += 1
493
489
        for hunk_line in hunk.lines:
495
491
            if isinstance(hunk_line, InsertLine):
496
492
                yield hunk_line.contents
497
493
            elif isinstance(hunk_line, (ContextLine, RemoveLine)):
498
 
                orig_line = orig_lines.next()
 
494
                orig_line = next(orig_lines)
499
495
                if orig_line != hunk_line.contents:
500
496
                    raise PatchConflict(line_no, orig_line, "".join(seen_patch))
501
497
                if isinstance(hunk_line, ContextLine):