/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: 2019-02-04 01:01:24 UTC
  • mto: This revision was merged to the branch mainline in revision 7268.
  • Revision ID: jelmer@jelmer.uk-20190204010124-ni0i4qc6f5tnbvux
Fix source 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
 
binary_files_re = 'Binary files (.*) and (.*) differ\n'
21
 
 
22
 
 
23
 
class BinaryFiles(Exception):
 
27
binary_files_re = b'Binary files (.*) and (.*) differ\n'
 
28
 
 
29
 
 
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))
75
 
        if not line.startswith("--- "):
 
87
        if not line.startswith(b"--- "):
76
88
            raise MalformedPatchHeader("No orig name", line)
77
89
        else:
78
 
            orig_name = line[4:].rstrip("\n")
 
90
            orig_name = line[4:].rstrip(b"\n")
79
91
    except StopIteration:
80
92
        raise MalformedPatchHeader("No orig line", "")
81
93
    try:
82
 
        line = iter_lines.next()
83
 
        if not line.startswith("+++ "):
 
94
        line = next(iter_lines)
 
95
        if not line.startswith(b"+++ "):
84
96
            raise PatchSyntax("No mod name")
85
97
        else:
86
 
            mod_name = line[4:].rstrip("\n")
 
98
            mod_name = line[4:].rstrip(b"\n")
87
99
    except StopIteration:
88
100
        raise MalformedPatchHeader("No mod line", "")
89
101
    return (orig_name, mod_name)
97
109
    :return: the position and range, as a tuple
98
110
    :rtype: (int, int)
99
111
    """
100
 
    tmp = textrange.split(',')
 
112
    tmp = textrange.split(b',')
101
113
    if len(tmp) == 1:
102
114
        pos = tmp[0]
103
 
        range = "1"
 
115
        range = b"1"
104
116
    else:
105
117
        (pos, range) = tmp
106
118
    pos = int(pos)
110
122
 
111
123
def hunk_from_header(line):
112
124
    import re
113
 
    matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
 
125
    matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
114
126
    if matches is None:
115
127
        raise MalformedHunkHeader("Does not match format.", line)
116
128
    try:
117
 
        (orig, mod) = matches.group(1).split(" ")
118
 
    except (ValueError, IndexError), e:
 
129
        (orig, mod) = matches.group(1).split(b" ")
 
130
    except (ValueError, IndexError) as e:
119
131
        raise MalformedHunkHeader(str(e), line)
120
 
    if not orig.startswith('-') or not mod.startswith('+'):
 
132
    if not orig.startswith(b'-') or not mod.startswith(b'+'):
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)
130
142
    return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
131
143
 
132
144
 
133
 
class HunkLine:
 
145
class HunkLine(object):
 
146
 
134
147
    def __init__(self, contents):
135
148
        self.contents = contents
136
149
 
137
150
    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
 
151
        if self.contents == b"\n" and leadchar == b" " and False:
 
152
            return b"\n"
 
153
        if not self.contents.endswith(b'\n'):
 
154
            terminator = b'\n' + NO_NL
142
155
        else:
143
 
            terminator = ''
 
156
            terminator = b''
144
157
        return leadchar + self.contents + terminator
145
158
 
 
159
    def as_bytes(self):
 
160
        raise NotImplementedError
 
161
 
146
162
 
147
163
class ContextLine(HunkLine):
 
164
 
148
165
    def __init__(self, contents):
149
166
        HunkLine.__init__(self, contents)
150
167
 
151
 
    def __str__(self):
152
 
        return self.get_str(" ")
 
168
    def as_bytes(self):
 
169
        return self.get_str(b" ")
153
170
 
154
171
 
155
172
class InsertLine(HunkLine):
156
173
    def __init__(self, contents):
157
174
        HunkLine.__init__(self, contents)
158
175
 
159
 
    def __str__(self):
160
 
        return self.get_str("+")
 
176
    def as_bytes(self):
 
177
        return self.get_str(b"+")
161
178
 
162
179
 
163
180
class RemoveLine(HunkLine):
164
181
    def __init__(self, contents):
165
182
        HunkLine.__init__(self, contents)
166
183
 
167
 
    def __str__(self):
168
 
        return self.get_str("-")
169
 
 
170
 
NO_NL = '\\ No newline at end of file\n'
171
 
__pychecker__="no-returnvalues"
 
184
    def as_bytes(self):
 
185
        return self.get_str(b"-")
 
186
 
 
187
 
 
188
NO_NL = b'\\ No newline at end of file\n'
 
189
__pychecker__ = "no-returnvalues"
 
190
 
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
 
__pychecker__=""
185
 
 
186
 
 
187
 
class Hunk:
 
203
 
 
204
 
 
205
__pychecker__ = ""
 
206
 
 
207
 
 
208
class Hunk(object):
 
209
 
188
210
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
189
211
        self.orig_pos = orig_pos
190
212
        self.orig_range = orig_range
195
217
 
196
218
    def get_header(self):
197
219
        if self.tail is None:
198
 
            tail_str = ''
 
220
            tail_str = b''
199
221
        else:
200
 
            tail_str = ' ' + self.tail
201
 
        return "@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
202
 
                                                     self.orig_range),
203
 
                                      self.range_str(self.mod_pos,
204
 
                                                     self.mod_range),
205
 
                                      tail_str)
 
222
            tail_str = b' ' + self.tail
 
223
        return b"@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
 
224
                                                      self.orig_range),
 
225
                                       self.range_str(self.mod_pos,
 
226
                                                      self.mod_range),
 
227
                                       tail_str)
206
228
 
207
229
    def range_str(self, pos, range):
208
230
        """Return a file range, special-casing for 1-line files.
214
236
        :return: a string in the format 1,4 except when range == pos == 1
215
237
        """
216
238
        if range == 1:
217
 
            return "%i" % pos
 
239
            return b"%i" % pos
218
240
        else:
219
 
            return "%i,%i" % (pos, range)
 
241
            return b"%i,%i" % (pos, range)
220
242
 
221
 
    def __str__(self):
 
243
    def as_bytes(self):
222
244
        lines = [self.get_header()]
223
245
        for line in self.lines:
224
 
            lines.append(str(line))
225
 
        return "".join(lines)
 
246
            lines.append(line.as_bytes())
 
247
        return b"".join(lines)
 
248
 
 
249
    __bytes__ = as_bytes
226
250
 
227
251
    def shift_to_mod(self, pos):
228
 
        if pos < self.orig_pos-1:
 
252
        if pos < self.orig_pos - 1:
229
253
            return 0
230
 
        elif pos > self.orig_pos+self.orig_range:
 
254
        elif pos > self.orig_pos + self.orig_range:
231
255
            return self.mod_range - self.orig_range
232
256
        else:
233
257
            return self.shift_to_mod_lines(pos)
234
258
 
235
259
    def shift_to_mod_lines(self, pos):
236
 
        position = self.orig_pos-1
 
260
        position = self.orig_pos - 1
237
261
        shift = 0
238
262
        for line in self.lines:
239
263
            if isinstance(line, InsertLine):
259
283
    '''
260
284
    hunk = None
261
285
    for line in iter_lines:
262
 
        if line == "\n":
 
286
        if line == b"\n":
263
287
            if hunk is not None:
264
288
                yield hunk
265
289
                hunk = None
278
302
        orig_size = 0
279
303
        mod_size = 0
280
304
        while orig_size < hunk.orig_range or mod_size < hunk.mod_range:
281
 
            hunk_line = parse_line(iter_lines.next())
 
305
            hunk_line = parse_line(next(iter_lines))
282
306
            hunk.lines.append(hunk_line)
283
307
            if isinstance(hunk_line, (RemoveLine, ContextLine)):
284
308
                orig_size += 1
289
313
 
290
314
 
291
315
class BinaryPatch(object):
 
316
 
292
317
    def __init__(self, oldname, newname):
293
318
        self.oldname = oldname
294
319
        self.newname = newname
295
320
 
296
 
    def __str__(self):
297
 
        return 'Binary files %s and %s differ\n' % (self.oldname, self.newname)
 
321
    def as_bytes(self):
 
322
        return b'Binary files %s and %s differ\n' % (self.oldname, self.newname)
298
323
 
299
324
 
300
325
class Patch(BinaryPatch):
303
328
        BinaryPatch.__init__(self, oldname, newname)
304
329
        self.hunks = []
305
330
 
306
 
    def __str__(self):
 
331
    def as_bytes(self):
307
332
        ret = self.get_header()
308
 
        ret += "".join([str(h) for h in self.hunks])
 
333
        ret += b"".join([h.as_bytes() for h in self.hunks])
309
334
        return ret
310
335
 
311
336
    def get_header(self):
312
 
        return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
 
337
        return b"--- %s\n+++ %s\n" % (self.oldname, self.newname)
313
338
 
314
339
    def stats_values(self):
315
340
        """Calculate the number of inserts and removes."""
318
343
        for hunk in self.hunks:
319
344
            for line in hunk.lines:
320
345
                if isinstance(line, InsertLine):
321
 
                     inserts+=1;
 
346
                    inserts += 1
322
347
                elif isinstance(line, RemoveLine):
323
 
                     removes+=1;
 
348
                    removes += 1
324
349
        return (inserts, removes, len(self.hunks))
325
350
 
326
351
    def stats_str(self):
344
369
        :rtype: iterator of (int, InsertLine)
345
370
        """
346
371
        for hunk in self.hunks:
347
 
            pos = hunk.mod_pos - 1;
 
372
            pos = hunk.mod_pos - 1
348
373
            for line in hunk.lines:
349
374
                if isinstance(line, InsertLine):
350
375
                    yield (pos, line)
362
387
    iter_lines = iter_lines_handle_nl(iter_lines)
363
388
    try:
364
389
        (orig_name, mod_name) = get_patch_names(iter_lines)
365
 
    except BinaryFiles, e:
 
390
    except BinaryFiles as e:
366
391
        return BinaryPatch(e.orig_name, e.mod_name)
367
392
    else:
368
393
        patch = Patch(orig_name, mod_name)
371
396
        return patch
372
397
 
373
398
 
374
 
def iter_file_patch(iter_lines, allow_dirty=False):
 
399
def iter_file_patch(iter_lines, allow_dirty=False, keep_dirty=False):
375
400
    '''
376
401
    :arg iter_lines: iterable of lines to parse for patches
377
402
    :kwarg allow_dirty: If True, allow comments and other non-patch text
380
405
        first patch are stripped away in iter_hunks() if it is also passed
381
406
        allow_dirty=True.  Default False.
382
407
    '''
383
 
    ### FIXME: Docstring is not quite true.  We allow certain comments no
 
408
    # FIXME: Docstring is not quite true.  We allow certain comments no
384
409
    # matter what, If they startwith '===', '***', or '#' Someone should
385
410
    # reexamine this logic and decide if we should include those in
386
411
    # allow_dirty or restrict those to only being before the patch is found
387
412
    # (as allow_dirty does).
388
413
    regex = re.compile(binary_files_re)
389
414
    saved_lines = []
 
415
    dirty_head = []
390
416
    orig_range = 0
391
417
    beginning = True
 
418
 
392
419
    for line in iter_lines:
393
 
        if line.startswith('=== ') or line.startswith('*** '):
394
 
            continue
395
 
        if line.startswith('#'):
 
420
        if line.startswith(b'=== '):
 
421
            if len(saved_lines) > 0:
 
422
                if keep_dirty and len(dirty_head) > 0:
 
423
                    yield {'saved_lines': saved_lines,
 
424
                           'dirty_head': dirty_head}
 
425
                    dirty_head = []
 
426
                else:
 
427
                    yield saved_lines
 
428
                saved_lines = []
 
429
            dirty_head.append(line)
 
430
            continue
 
431
        if line.startswith(b'*** '):
 
432
            continue
 
433
        if line.startswith(b'#'):
396
434
            continue
397
435
        elif orig_range > 0:
398
 
            if line.startswith('-') or line.startswith(' '):
 
436
            if line.startswith(b'-') or line.startswith(b' '):
399
437
                orig_range -= 1
400
 
        elif line.startswith('--- ') or regex.match(line):
 
438
        elif line.startswith(b'--- ') or regex.match(line):
401
439
            if allow_dirty and beginning:
402
440
                # Patches can have "junk" at the beginning
403
441
                # Stripping junk from the end of patches is handled when we
404
442
                # parse the patch
405
443
                beginning = False
406
444
            elif len(saved_lines) > 0:
407
 
                yield saved_lines
 
445
                if keep_dirty and len(dirty_head) > 0:
 
446
                    yield {'saved_lines': saved_lines,
 
447
                           'dirty_head': dirty_head}
 
448
                    dirty_head = []
 
449
                else:
 
450
                    yield saved_lines
408
451
            saved_lines = []
409
 
        elif line.startswith('@@'):
 
452
        elif line.startswith(b'@@'):
410
453
            hunk = hunk_from_header(line)
411
454
            orig_range = hunk.orig_range
412
455
        saved_lines.append(line)
413
456
    if len(saved_lines) > 0:
414
 
        yield saved_lines
 
457
        if keep_dirty and len(dirty_head) > 0:
 
458
            yield {'saved_lines': saved_lines,
 
459
                   'dirty_head': dirty_head}
 
460
        else:
 
461
            yield saved_lines
415
462
 
416
463
 
417
464
def iter_lines_handle_nl(iter_lines):
424
471
    last_line = None
425
472
    for line in iter_lines:
426
473
        if line == NO_NL:
427
 
            if not last_line.endswith('\n'):
 
474
            if not last_line.endswith(b'\n'):
428
475
                raise AssertionError()
429
476
            last_line = last_line[:-1]
430
477
            line = None
435
482
        yield last_line
436
483
 
437
484
 
438
 
def parse_patches(iter_lines, allow_dirty=False):
 
485
def parse_patches(iter_lines, allow_dirty=False, keep_dirty=False):
439
486
    '''
440
487
    :arg iter_lines: iterable of lines to parse for patches
441
488
    :kwarg allow_dirty: If True, allow text that's not part of the patch at
442
489
        selected places.  This includes comments before and after a patch
443
490
        for instance.  Default False.
 
491
    :kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
 
492
        Default False.
444
493
    '''
445
 
    return [parse_patch(f.__iter__(), allow_dirty) for f in
446
 
                        iter_file_patch(iter_lines, allow_dirty)]
 
494
    for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
 
495
        if 'dirty_head' in patch_lines:
 
496
            yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
 
497
                    'dirty_head': patch_lines['dirty_head']})
 
498
        else:
 
499
            yield parse_patch(patch_lines, allow_dirty)
447
500
 
448
501
 
449
502
def difference_index(atext, btext):
461
514
        length = len(btext)
462
515
    for i in range(length):
463
516
        if atext[i] != btext[i]:
464
 
            return i;
 
517
            return i
465
518
    return None
466
519
 
467
520
 
487
540
        orig_lines = iter(orig_lines)
488
541
    for hunk in hunks:
489
542
        while line_no < hunk.orig_pos:
490
 
            orig_line = orig_lines.next()
 
543
            orig_line = next(orig_lines)
491
544
            yield orig_line
492
545
            line_no += 1
493
546
        for hunk_line in hunk.lines:
495
548
            if isinstance(hunk_line, InsertLine):
496
549
                yield hunk_line.contents
497
550
            elif isinstance(hunk_line, (ContextLine, RemoveLine)):
498
 
                orig_line = orig_lines.next()
 
551
                orig_line = next(orig_lines)
499
552
                if orig_line != hunk_line.contents:
500
 
                    raise PatchConflict(line_no, orig_line, "".join(seen_patch))
 
553
                    raise PatchConflict(line_no, orig_line,
 
554
                                        b"".join(seen_patch))
501
555
                if isinstance(hunk_line, ContextLine):
502
556
                    yield orig_line
503
557
                else: