/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-07-07 19:27:38 UTC
  • mto: (7027.4.10 python3-blackbox)
  • mto: This revision was merged to the branch mainline in revision 7038.
  • Revision ID: jelmer@jelmer.uk-20180707192738-cbt5f28lbd3lx4td
Add some more bees; support writing both bytes and unicode strings in build_tree_contents.

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
 
 
19
 
 
20
 
binary_files_re = 'Binary files (.*) and (.*) differ\n'
21
 
 
22
 
 
23
 
class BinaryFiles(Exception):
 
25
import sys
 
26
 
 
27
 
 
28
binary_files_re = b'Binary files (.*) and (.*) differ\n'
 
29
 
 
30
 
 
31
class PatchSyntax(BzrError):
 
32
    """Base class for patch syntax errors."""
 
33
 
 
34
 
 
35
class BinaryFiles(BzrError):
 
36
 
 
37
    _fmt = 'Binary files section encountered.'
24
38
 
25
39
    def __init__(self, orig_name, mod_name):
26
40
        self.orig_name = orig_name
27
41
        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
42
 
35
43
 
36
44
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)
 
45
 
 
46
    _fmt = "Malformed patch header.  %(desc)s\n%(line)r"
 
47
 
 
48
    def __init__(self, desc, line):
 
49
        self.desc = desc
 
50
        self.line = line
50
51
 
51
52
 
52
53
class MalformedLine(PatchSyntax):
 
54
 
 
55
    _fmt = "Malformed line.  %(desc)s\n%(line)r"
 
56
 
53
57
    def __init__(self, desc, line):
54
58
        self.desc = desc
55
59
        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):
 
60
 
 
61
 
 
62
class PatchConflict(BzrError):
 
63
 
 
64
    _fmt = ('Text contents mismatch at line %(line_no)d.  Original has '
 
65
            '"%(orig_line)s", but patch says it should be "%(patch_line)s"')
 
66
 
61
67
    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)
 
68
        self.line_no = line_no
 
69
        self.orig_line = orig_line.rstrip('\n')
 
70
        self.patch_line = patch_line.rstrip('\n')
 
71
 
 
72
 
 
73
class MalformedHunkHeader(PatchSyntax):
 
74
 
 
75
    _fmt = "Malformed hunk header.  %(desc)s\n%(line)r"
 
76
 
 
77
    def __init__(self, desc, line):
 
78
        self.desc = desc
 
79
        self.line = line
67
80
 
68
81
 
69
82
def get_patch_names(iter_lines):
 
83
    line = next(iter_lines)
70
84
    try:
71
 
        line = iter_lines.next()
72
85
        match = re.match(binary_files_re, line)
73
86
        if match is not None:
74
87
            raise BinaryFiles(match.group(1), match.group(2))
75
 
        if not line.startswith("--- "):
 
88
        if not line.startswith(b"--- "):
76
89
            raise MalformedPatchHeader("No orig name", line)
77
90
        else:
78
 
            orig_name = line[4:].rstrip("\n")
 
91
            orig_name = line[4:].rstrip(b"\n")
79
92
    except StopIteration:
80
93
        raise MalformedPatchHeader("No orig line", "")
81
94
    try:
82
 
        line = iter_lines.next()
83
 
        if not line.startswith("+++ "):
 
95
        line = next(iter_lines)
 
96
        if not line.startswith(b"+++ "):
84
97
            raise PatchSyntax("No mod name")
85
98
        else:
86
 
            mod_name = line[4:].rstrip("\n")
 
99
            mod_name = line[4:].rstrip(b"\n")
87
100
    except StopIteration:
88
101
        raise MalformedPatchHeader("No mod line", "")
89
102
    return (orig_name, mod_name)
97
110
    :return: the position and range, as a tuple
98
111
    :rtype: (int, int)
99
112
    """
100
 
    tmp = textrange.split(',')
 
113
    tmp = textrange.split(b',')
101
114
    if len(tmp) == 1:
102
115
        pos = tmp[0]
103
 
        range = "1"
 
116
        range = b"1"
104
117
    else:
105
118
        (pos, range) = tmp
106
119
    pos = int(pos)
110
123
 
111
124
def hunk_from_header(line):
112
125
    import re
113
 
    matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
 
126
    matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
114
127
    if matches is None:
115
128
        raise MalformedHunkHeader("Does not match format.", line)
116
129
    try:
117
 
        (orig, mod) = matches.group(1).split(" ")
118
 
    except (ValueError, IndexError), e:
 
130
        (orig, mod) = matches.group(1).split(b" ")
 
131
    except (ValueError, IndexError) as e:
119
132
        raise MalformedHunkHeader(str(e), line)
120
 
    if not orig.startswith('-') or not mod.startswith('+'):
 
133
    if not orig.startswith(b'-') or not mod.startswith(b'+'):
121
134
        raise MalformedHunkHeader("Positions don't start with + or -.", line)
122
135
    try:
123
136
        (orig_pos, orig_range) = parse_range(orig[1:])
124
137
        (mod_pos, mod_range) = parse_range(mod[1:])
125
 
    except (ValueError, IndexError), e:
 
138
    except (ValueError, IndexError) as e:
126
139
        raise MalformedHunkHeader(str(e), line)
127
140
    if mod_range < 0 or orig_range < 0:
128
141
        raise MalformedHunkHeader("Hunk range is negative", line)
130
143
    return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
131
144
 
132
145
 
133
 
class HunkLine:
 
146
class HunkLine(object):
 
147
 
134
148
    def __init__(self, contents):
135
149
        self.contents = contents
136
150
 
137
151
    def get_str(self, leadchar):
138
 
        if self.contents == "\n" and leadchar == " " and False:
139
 
            return "\n"
140
 
        if not self.contents.endswith('\n'):
141
 
            terminator = '\n' + NO_NL
 
152
        if self.contents == b"\n" and leadchar == b" " and False:
 
153
            return b"\n"
 
154
        if not self.contents.endswith(b'\n'):
 
155
            terminator = b'\n' + NO_NL
142
156
        else:
143
 
            terminator = ''
 
157
            terminator = b''
144
158
        return leadchar + self.contents + terminator
145
159
 
 
160
    if sys.version_info[0] == 2:
 
161
        def __str__(self):
 
162
            return self.__bytes__()
 
163
 
146
164
 
147
165
class ContextLine(HunkLine):
 
166
 
148
167
    def __init__(self, contents):
149
168
        HunkLine.__init__(self, contents)
150
169
 
151
 
    def __str__(self):
152
 
        return self.get_str(" ")
 
170
    def __bytes__(self):
 
171
        return self.get_str(b" ")
153
172
 
154
173
 
155
174
class InsertLine(HunkLine):
156
175
    def __init__(self, contents):
157
176
        HunkLine.__init__(self, contents)
158
177
 
159
 
    def __str__(self):
160
 
        return self.get_str("+")
 
178
    def __bytes__(self):
 
179
        return self.get_str(b"+")
161
180
 
162
181
 
163
182
class RemoveLine(HunkLine):
164
183
    def __init__(self, contents):
165
184
        HunkLine.__init__(self, contents)
166
185
 
167
 
    def __str__(self):
168
 
        return self.get_str("-")
 
186
    def __bytes__(self):
 
187
        return self.get_str(b"-")
169
188
 
170
 
NO_NL = '\\ No newline at end of file\n'
 
189
NO_NL = b'\\ No newline at end of file\n'
171
190
__pychecker__="no-returnvalues"
172
191
 
173
192
def parse_line(line):
174
 
    if line.startswith("\n"):
 
193
    if line.startswith(b"\n"):
175
194
        return ContextLine(line)
176
 
    elif line.startswith(" "):
 
195
    elif line.startswith(b" "):
177
196
        return ContextLine(line[1:])
178
 
    elif line.startswith("+"):
 
197
    elif line.startswith(b"+"):
179
198
        return InsertLine(line[1:])
180
 
    elif line.startswith("-"):
 
199
    elif line.startswith(b"-"):
181
200
        return RemoveLine(line[1:])
182
201
    else:
183
202
        raise MalformedLine("Unknown line type", line)
184
203
__pychecker__=""
185
204
 
186
205
 
187
 
class Hunk:
 
206
class Hunk(object):
 
207
 
188
208
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
189
209
        self.orig_pos = orig_pos
190
210
        self.orig_range = orig_range
195
215
 
196
216
    def get_header(self):
197
217
        if self.tail is None:
198
 
            tail_str = ''
 
218
            tail_str = b''
199
219
        else:
200
 
            tail_str = ' ' + self.tail
201
 
        return "@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
 
220
            tail_str = b' ' + self.tail
 
221
        return b"@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
202
222
                                                     self.orig_range),
203
223
                                      self.range_str(self.mod_pos,
204
224
                                                     self.mod_range),
214
234
        :return: a string in the format 1,4 except when range == pos == 1
215
235
        """
216
236
        if range == 1:
217
 
            return "%i" % pos
 
237
            return b"%i" % pos
218
238
        else:
219
 
            return "%i,%i" % (pos, range)
 
239
            return b"%i,%i" % (pos, range)
220
240
 
221
 
    def __str__(self):
 
241
    def __bytes__(self):
222
242
        lines = [self.get_header()]
223
243
        for line in self.lines:
224
 
            lines.append(str(line))
225
 
        return "".join(lines)
 
244
            lines.append(bytes(line))
 
245
        return b"".join(lines)
 
246
 
 
247
    if sys.version_info[0] == 2:
 
248
        __str__ = __bytes__
226
249
 
227
250
    def shift_to_mod(self, pos):
228
251
        if pos < self.orig_pos-1:
259
282
    '''
260
283
    hunk = None
261
284
    for line in iter_lines:
262
 
        if line == "\n":
 
285
        if line == b"\n":
263
286
            if hunk is not None:
264
287
                yield hunk
265
288
                hunk = None
278
301
        orig_size = 0
279
302
        mod_size = 0
280
303
        while orig_size < hunk.orig_range or mod_size < hunk.mod_range:
281
 
            hunk_line = parse_line(iter_lines.next())
 
304
            hunk_line = parse_line(next(iter_lines))
282
305
            hunk.lines.append(hunk_line)
283
306
            if isinstance(hunk_line, (RemoveLine, ContextLine)):
284
307
                orig_size += 1
289
312
 
290
313
 
291
314
class BinaryPatch(object):
 
315
 
292
316
    def __init__(self, oldname, newname):
293
317
        self.oldname = oldname
294
318
        self.newname = newname
295
319
 
296
 
    def __str__(self):
297
 
        return 'Binary files %s and %s differ\n' % (self.oldname, self.newname)
 
320
    def __bytes__(self):
 
321
        return b'Binary files %s and %s differ\n' % (self.oldname, self.newname)
 
322
 
 
323
    if sys.version_info[0] == 2:
 
324
        def __str__(self):
 
325
            return self.__bytes__()
298
326
 
299
327
 
300
328
class Patch(BinaryPatch):
303
331
        BinaryPatch.__init__(self, oldname, newname)
304
332
        self.hunks = []
305
333
 
306
 
    def __str__(self):
 
334
    def __bytes__(self):
307
335
        ret = self.get_header()
308
 
        ret += "".join([str(h) for h in self.hunks])
 
336
        ret += b"".join([bytes(h) for h in self.hunks])
309
337
        return ret
310
338
 
311
339
    def get_header(self):
312
 
        return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
 
340
        return b"--- %s\n+++ %s\n" % (self.oldname, self.newname)
313
341
 
314
342
    def stats_values(self):
315
343
        """Calculate the number of inserts and removes."""
362
390
    iter_lines = iter_lines_handle_nl(iter_lines)
363
391
    try:
364
392
        (orig_name, mod_name) = get_patch_names(iter_lines)
365
 
    except BinaryFiles, e:
 
393
    except BinaryFiles as e:
366
394
        return BinaryPatch(e.orig_name, e.mod_name)
367
395
    else:
368
396
        patch = Patch(orig_name, mod_name)
371
399
        return patch
372
400
 
373
401
 
374
 
def iter_file_patch(iter_lines, allow_dirty=False):
 
402
def iter_file_patch(iter_lines, allow_dirty=False, keep_dirty=False):
375
403
    '''
376
404
    :arg iter_lines: iterable of lines to parse for patches
377
405
    :kwarg allow_dirty: If True, allow comments and other non-patch text
387
415
    # (as allow_dirty does).
388
416
    regex = re.compile(binary_files_re)
389
417
    saved_lines = []
 
418
    dirty_head = []
390
419
    orig_range = 0
391
420
    beginning = True
 
421
 
392
422
    for line in iter_lines:
393
 
        if line.startswith('=== ') or line.startswith('*** '):
394
 
            continue
395
 
        if line.startswith('#'):
 
423
        if line.startswith(b'=== '):
 
424
            if len(saved_lines) > 0:
 
425
                if keep_dirty and len(dirty_head) > 0:
 
426
                    yield {'saved_lines': saved_lines,
 
427
                           'dirty_head': dirty_head}
 
428
                    dirty_head = []
 
429
                else:
 
430
                    yield saved_lines
 
431
                saved_lines = []
 
432
            dirty_head.append(line)
 
433
            continue
 
434
        if line.startswith(b'*** '):
 
435
            continue
 
436
        if line.startswith(b'#'):
396
437
            continue
397
438
        elif orig_range > 0:
398
 
            if line.startswith('-') or line.startswith(' '):
 
439
            if line.startswith(b'-') or line.startswith(b' '):
399
440
                orig_range -= 1
400
 
        elif line.startswith('--- ') or regex.match(line):
 
441
        elif line.startswith(b'--- ') or regex.match(line):
401
442
            if allow_dirty and beginning:
402
443
                # Patches can have "junk" at the beginning
403
444
                # Stripping junk from the end of patches is handled when we
404
445
                # parse the patch
405
446
                beginning = False
406
447
            elif len(saved_lines) > 0:
407
 
                yield saved_lines
 
448
                if keep_dirty and len(dirty_head) > 0:
 
449
                    yield {'saved_lines': saved_lines,
 
450
                           'dirty_head': dirty_head}
 
451
                    dirty_head = []
 
452
                else:
 
453
                    yield saved_lines
408
454
            saved_lines = []
409
 
        elif line.startswith('@@'):
 
455
        elif line.startswith(b'@@'):
410
456
            hunk = hunk_from_header(line)
411
457
            orig_range = hunk.orig_range
412
458
        saved_lines.append(line)
413
459
    if len(saved_lines) > 0:
414
 
        yield saved_lines
 
460
        if keep_dirty and len(dirty_head) > 0:
 
461
            yield {'saved_lines': saved_lines,
 
462
                   'dirty_head': dirty_head}
 
463
        else:
 
464
            yield saved_lines
415
465
 
416
466
 
417
467
def iter_lines_handle_nl(iter_lines):
424
474
    last_line = None
425
475
    for line in iter_lines:
426
476
        if line == NO_NL:
427
 
            if not last_line.endswith('\n'):
 
477
            if not last_line.endswith(b'\n'):
428
478
                raise AssertionError()
429
479
            last_line = last_line[:-1]
430
480
            line = None
435
485
        yield last_line
436
486
 
437
487
 
438
 
def parse_patches(iter_lines, allow_dirty=False):
 
488
def parse_patches(iter_lines, allow_dirty=False, keep_dirty=False):
439
489
    '''
440
490
    :arg iter_lines: iterable of lines to parse for patches
441
491
    :kwarg allow_dirty: If True, allow text that's not part of the patch at
442
492
        selected places.  This includes comments before and after a patch
443
493
        for instance.  Default False.
 
494
    :kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
 
495
        Default False.
444
496
    '''
445
 
    return [parse_patch(f.__iter__(), allow_dirty) for f in
446
 
                        iter_file_patch(iter_lines, allow_dirty)]
 
497
    for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
 
498
        if 'dirty_head' in patch_lines:
 
499
            yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
 
500
                    'dirty_head': patch_lines['dirty_head']})
 
501
        else:
 
502
            yield parse_patch(patch_lines, allow_dirty)
447
503
 
448
504
 
449
505
def difference_index(atext, btext):
487
543
        orig_lines = iter(orig_lines)
488
544
    for hunk in hunks:
489
545
        while line_no < hunk.orig_pos:
490
 
            orig_line = orig_lines.next()
 
546
            orig_line = next(orig_lines)
491
547
            yield orig_line
492
548
            line_no += 1
493
549
        for hunk_line in hunk.lines:
495
551
            if isinstance(hunk_line, InsertLine):
496
552
                yield hunk_line.contents
497
553
            elif isinstance(hunk_line, (ContextLine, RemoveLine)):
498
 
                orig_line = orig_lines.next()
 
554
                orig_line = next(orig_lines)
499
555
                if orig_line != hunk_line.contents:
500
 
                    raise PatchConflict(line_no, orig_line, "".join(seen_patch))
 
556
                    raise PatchConflict(line_no, orig_line, b"".join(seen_patch))
501
557
                if isinstance(hunk_line, ContextLine):
502
558
                    yield orig_line
503
559
                else: