/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: Breezy landing bot
  • Author(s): Colin Watson
  • Date: 2020-11-16 21:47:08 UTC
  • mfrom: (7521.1.1 remove-lp-workaround)
  • Revision ID: breezy.the.bot@gmail.com-20201116214708-jos209mgxi41oy15
Remove breezy.git workaround for bazaar.launchpad.net.

Merged from https://code.launchpad.net/~cjwatson/brz/remove-lp-workaround/+merge/393710

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
from __future__ import absolute_import
19
 
 
20
 
from bzrlib.errors import (
21
 
    BinaryFiles,
22
 
    MalformedHunkHeader,
23
 
    MalformedLine,
24
 
    MalformedPatchHeader,
25
 
    PatchConflict,
26
 
    PatchSyntax,
 
18
from .errors import (
 
19
    BzrError,
27
20
    )
28
21
 
 
22
import os
29
23
import re
30
24
 
31
25
 
32
 
binary_files_re = 'Binary files (.*) and (.*) differ\n'
 
26
binary_files_re = b'Binary files (.*) and (.*) differ\n'
 
27
 
 
28
 
 
29
class PatchSyntax(BzrError):
 
30
    """Base class for patch syntax errors."""
 
31
 
 
32
 
 
33
class BinaryFiles(BzrError):
 
34
 
 
35
    _fmt = 'Binary files section encountered.'
 
36
 
 
37
    def __init__(self, orig_name, mod_name):
 
38
        self.orig_name = orig_name
 
39
        self.mod_name = mod_name
 
40
 
 
41
 
 
42
class MalformedPatchHeader(PatchSyntax):
 
43
 
 
44
    _fmt = "Malformed patch header.  %(desc)s\n%(line)r"
 
45
 
 
46
    def __init__(self, desc, line):
 
47
        self.desc = desc
 
48
        self.line = line
 
49
 
 
50
 
 
51
class MalformedLine(PatchSyntax):
 
52
 
 
53
    _fmt = "Malformed line.  %(desc)s\n%(line)r"
 
54
 
 
55
    def __init__(self, desc, line):
 
56
        self.desc = desc
 
57
        self.line = line
 
58
 
 
59
 
 
60
class PatchConflict(BzrError):
 
61
 
 
62
    _fmt = ('Text contents mismatch at line %(line_no)d.  Original has '
 
63
            '"%(orig_line)s", but patch says it should be "%(patch_line)s"')
 
64
 
 
65
    def __init__(self, line_no, orig_line, patch_line):
 
66
        self.line_no = line_no
 
67
        self.orig_line = orig_line.rstrip('\n')
 
68
        self.patch_line = patch_line.rstrip('\n')
 
69
 
 
70
 
 
71
class MalformedHunkHeader(PatchSyntax):
 
72
 
 
73
    _fmt = "Malformed hunk header.  %(desc)s\n%(line)r"
 
74
 
 
75
    def __init__(self, desc, line):
 
76
        self.desc = desc
 
77
        self.line = line
33
78
 
34
79
 
35
80
def get_patch_names(iter_lines):
36
 
    line = iter_lines.next()
 
81
    line = next(iter_lines)
37
82
    try:
38
83
        match = re.match(binary_files_re, line)
39
84
        if match is not None:
40
85
            raise BinaryFiles(match.group(1), match.group(2))
41
 
        if not line.startswith("--- "):
 
86
        if not line.startswith(b"--- "):
42
87
            raise MalformedPatchHeader("No orig name", line)
43
88
        else:
44
 
            orig_name = line[4:].rstrip("\n")
 
89
            orig_name = line[4:].rstrip(b"\n")
45
90
    except StopIteration:
46
91
        raise MalformedPatchHeader("No orig line", "")
47
92
    try:
48
 
        line = iter_lines.next()
49
 
        if not line.startswith("+++ "):
 
93
        line = next(iter_lines)
 
94
        if not line.startswith(b"+++ "):
50
95
            raise PatchSyntax("No mod name")
51
96
        else:
52
 
            mod_name = line[4:].rstrip("\n")
 
97
            mod_name = line[4:].rstrip(b"\n")
53
98
    except StopIteration:
54
99
        raise MalformedPatchHeader("No mod line", "")
55
100
    return (orig_name, mod_name)
63
108
    :return: the position and range, as a tuple
64
109
    :rtype: (int, int)
65
110
    """
66
 
    tmp = textrange.split(',')
 
111
    tmp = textrange.split(b',')
67
112
    if len(tmp) == 1:
68
113
        pos = tmp[0]
69
 
        range = "1"
 
114
        range = b"1"
70
115
    else:
71
116
        (pos, range) = tmp
72
117
    pos = int(pos)
76
121
 
77
122
def hunk_from_header(line):
78
123
    import re
79
 
    matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
 
124
    matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
80
125
    if matches is None:
81
126
        raise MalformedHunkHeader("Does not match format.", line)
82
127
    try:
83
 
        (orig, mod) = matches.group(1).split(" ")
84
 
    except (ValueError, IndexError), e:
 
128
        (orig, mod) = matches.group(1).split(b" ")
 
129
    except (ValueError, IndexError) as e:
85
130
        raise MalformedHunkHeader(str(e), line)
86
 
    if not orig.startswith('-') or not mod.startswith('+'):
 
131
    if not orig.startswith(b'-') or not mod.startswith(b'+'):
87
132
        raise MalformedHunkHeader("Positions don't start with + or -.", line)
88
133
    try:
89
134
        (orig_pos, orig_range) = parse_range(orig[1:])
90
135
        (mod_pos, mod_range) = parse_range(mod[1:])
91
 
    except (ValueError, IndexError), e:
 
136
    except (ValueError, IndexError) as e:
92
137
        raise MalformedHunkHeader(str(e), line)
93
138
    if mod_range < 0 or orig_range < 0:
94
139
        raise MalformedHunkHeader("Hunk range is negative", line)
96
141
    return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
97
142
 
98
143
 
99
 
class HunkLine:
 
144
class HunkLine(object):
 
145
 
100
146
    def __init__(self, contents):
101
147
        self.contents = contents
102
148
 
103
149
    def get_str(self, leadchar):
104
 
        if self.contents == "\n" and leadchar == " " and False:
105
 
            return "\n"
106
 
        if not self.contents.endswith('\n'):
107
 
            terminator = '\n' + NO_NL
 
150
        if self.contents == b"\n" and leadchar == b" " and False:
 
151
            return b"\n"
 
152
        if not self.contents.endswith(b'\n'):
 
153
            terminator = b'\n' + NO_NL
108
154
        else:
109
 
            terminator = ''
 
155
            terminator = b''
110
156
        return leadchar + self.contents + terminator
111
157
 
 
158
    def as_bytes(self):
 
159
        raise NotImplementedError
 
160
 
112
161
 
113
162
class ContextLine(HunkLine):
 
163
 
114
164
    def __init__(self, contents):
115
165
        HunkLine.__init__(self, contents)
116
166
 
117
 
    def __str__(self):
118
 
        return self.get_str(" ")
 
167
    def as_bytes(self):
 
168
        return self.get_str(b" ")
119
169
 
120
170
 
121
171
class InsertLine(HunkLine):
122
172
    def __init__(self, contents):
123
173
        HunkLine.__init__(self, contents)
124
174
 
125
 
    def __str__(self):
126
 
        return self.get_str("+")
 
175
    def as_bytes(self):
 
176
        return self.get_str(b"+")
127
177
 
128
178
 
129
179
class RemoveLine(HunkLine):
130
180
    def __init__(self, contents):
131
181
        HunkLine.__init__(self, contents)
132
182
 
133
 
    def __str__(self):
134
 
        return self.get_str("-")
135
 
 
136
 
NO_NL = '\\ No newline at end of file\n'
137
 
__pychecker__="no-returnvalues"
 
183
    def as_bytes(self):
 
184
        return self.get_str(b"-")
 
185
 
 
186
 
 
187
NO_NL = b'\\ No newline at end of file\n'
 
188
__pychecker__ = "no-returnvalues"
 
189
 
138
190
 
139
191
def parse_line(line):
140
 
    if line.startswith("\n"):
 
192
    if line.startswith(b"\n"):
141
193
        return ContextLine(line)
142
 
    elif line.startswith(" "):
 
194
    elif line.startswith(b" "):
143
195
        return ContextLine(line[1:])
144
 
    elif line.startswith("+"):
 
196
    elif line.startswith(b"+"):
145
197
        return InsertLine(line[1:])
146
 
    elif line.startswith("-"):
 
198
    elif line.startswith(b"-"):
147
199
        return RemoveLine(line[1:])
148
200
    else:
149
201
        raise MalformedLine("Unknown line type", line)
150
 
__pychecker__=""
151
 
 
152
 
 
153
 
class Hunk:
 
202
 
 
203
 
 
204
__pychecker__ = ""
 
205
 
 
206
 
 
207
class Hunk(object):
 
208
 
154
209
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
155
210
        self.orig_pos = orig_pos
156
211
        self.orig_range = orig_range
161
216
 
162
217
    def get_header(self):
163
218
        if self.tail is None:
164
 
            tail_str = ''
 
219
            tail_str = b''
165
220
        else:
166
 
            tail_str = ' ' + self.tail
167
 
        return "@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
168
 
                                                     self.orig_range),
169
 
                                      self.range_str(self.mod_pos,
170
 
                                                     self.mod_range),
171
 
                                      tail_str)
 
221
            tail_str = b' ' + self.tail
 
222
        return b"@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
 
223
                                                      self.orig_range),
 
224
                                       self.range_str(self.mod_pos,
 
225
                                                      self.mod_range),
 
226
                                       tail_str)
172
227
 
173
228
    def range_str(self, pos, range):
174
229
        """Return a file range, special-casing for 1-line files.
180
235
        :return: a string in the format 1,4 except when range == pos == 1
181
236
        """
182
237
        if range == 1:
183
 
            return "%i" % pos
 
238
            return b"%i" % pos
184
239
        else:
185
 
            return "%i,%i" % (pos, range)
 
240
            return b"%i,%i" % (pos, range)
186
241
 
187
 
    def __str__(self):
 
242
    def as_bytes(self):
188
243
        lines = [self.get_header()]
189
244
        for line in self.lines:
190
 
            lines.append(str(line))
191
 
        return "".join(lines)
 
245
            lines.append(line.as_bytes())
 
246
        return b"".join(lines)
 
247
 
 
248
    __bytes__ = as_bytes
192
249
 
193
250
    def shift_to_mod(self, pos):
194
 
        if pos < self.orig_pos-1:
 
251
        if pos < self.orig_pos - 1:
195
252
            return 0
196
 
        elif pos > self.orig_pos+self.orig_range:
 
253
        elif pos > self.orig_pos + self.orig_range:
197
254
            return self.mod_range - self.orig_range
198
255
        else:
199
256
            return self.shift_to_mod_lines(pos)
200
257
 
201
258
    def shift_to_mod_lines(self, pos):
202
 
        position = self.orig_pos-1
 
259
        position = self.orig_pos - 1
203
260
        shift = 0
204
261
        for line in self.lines:
205
262
            if isinstance(line, InsertLine):
225
282
    '''
226
283
    hunk = None
227
284
    for line in iter_lines:
228
 
        if line == "\n":
 
285
        if line == b"\n":
229
286
            if hunk is not None:
230
287
                yield hunk
231
288
                hunk = None
244
301
        orig_size = 0
245
302
        mod_size = 0
246
303
        while orig_size < hunk.orig_range or mod_size < hunk.mod_range:
247
 
            hunk_line = parse_line(iter_lines.next())
 
304
            hunk_line = parse_line(next(iter_lines))
248
305
            hunk.lines.append(hunk_line)
249
306
            if isinstance(hunk_line, (RemoveLine, ContextLine)):
250
307
                orig_size += 1
255
312
 
256
313
 
257
314
class BinaryPatch(object):
 
315
 
258
316
    def __init__(self, oldname, newname):
259
317
        self.oldname = oldname
260
318
        self.newname = newname
261
319
 
262
 
    def __str__(self):
263
 
        return 'Binary files %s and %s differ\n' % (self.oldname, self.newname)
 
320
    def as_bytes(self):
 
321
        return b'Binary files %s and %s differ\n' % (self.oldname, self.newname)
264
322
 
265
323
 
266
324
class Patch(BinaryPatch):
269
327
        BinaryPatch.__init__(self, oldname, newname)
270
328
        self.hunks = []
271
329
 
272
 
    def __str__(self):
 
330
    def as_bytes(self):
273
331
        ret = self.get_header()
274
 
        ret += "".join([str(h) for h in self.hunks])
 
332
        ret += b"".join([h.as_bytes() for h in self.hunks])
275
333
        return ret
276
334
 
277
335
    def get_header(self):
278
 
        return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
 
336
        return b"--- %s\n+++ %s\n" % (self.oldname, self.newname)
279
337
 
280
338
    def stats_values(self):
281
339
        """Calculate the number of inserts and removes."""
284
342
        for hunk in self.hunks:
285
343
            for line in hunk.lines:
286
344
                if isinstance(line, InsertLine):
287
 
                     inserts+=1;
 
345
                    inserts += 1
288
346
                elif isinstance(line, RemoveLine):
289
 
                     removes+=1;
 
347
                    removes += 1
290
348
        return (inserts, removes, len(self.hunks))
291
349
 
292
350
    def stats_str(self):
310
368
        :rtype: iterator of (int, InsertLine)
311
369
        """
312
370
        for hunk in self.hunks:
313
 
            pos = hunk.mod_pos - 1;
 
371
            pos = hunk.mod_pos - 1
314
372
            for line in hunk.lines:
315
373
                if isinstance(line, InsertLine):
316
374
                    yield (pos, line)
318
376
                if isinstance(line, ContextLine):
319
377
                    pos += 1
320
378
 
 
379
 
321
380
def parse_patch(iter_lines, allow_dirty=False):
322
381
    '''
323
382
    :arg iter_lines: iterable of lines to parse
327
386
    iter_lines = iter_lines_handle_nl(iter_lines)
328
387
    try:
329
388
        (orig_name, mod_name) = get_patch_names(iter_lines)
330
 
    except BinaryFiles, e:
 
389
    except BinaryFiles as e:
331
390
        return BinaryPatch(e.orig_name, e.mod_name)
332
391
    else:
333
392
        patch = Patch(orig_name, mod_name)
345
404
        first patch are stripped away in iter_hunks() if it is also passed
346
405
        allow_dirty=True.  Default False.
347
406
    '''
348
 
    ### FIXME: Docstring is not quite true.  We allow certain comments no
 
407
    # FIXME: Docstring is not quite true.  We allow certain comments no
349
408
    # matter what, If they startwith '===', '***', or '#' Someone should
350
409
    # reexamine this logic and decide if we should include those in
351
410
    # allow_dirty or restrict those to only being before the patch is found
357
416
    beginning = True
358
417
 
359
418
    for line in iter_lines:
360
 
        if line.startswith('=== '):
 
419
        if line.startswith(b'=== '):
361
420
            if len(saved_lines) > 0:
362
421
                if keep_dirty and len(dirty_head) > 0:
363
422
                    yield {'saved_lines': saved_lines,
368
427
                saved_lines = []
369
428
            dirty_head.append(line)
370
429
            continue
371
 
        if line.startswith('*** '):
 
430
        if line.startswith(b'*** '):
372
431
            continue
373
 
        if line.startswith('#'):
 
432
        if line.startswith(b'#'):
374
433
            continue
375
434
        elif orig_range > 0:
376
 
            if line.startswith('-') or line.startswith(' '):
 
435
            if line.startswith(b'-') or line.startswith(b' '):
377
436
                orig_range -= 1
378
 
        elif line.startswith('--- ') or regex.match(line):
 
437
        elif line.startswith(b'--- ') or regex.match(line):
379
438
            if allow_dirty and beginning:
380
439
                # Patches can have "junk" at the beginning
381
440
                # Stripping junk from the end of patches is handled when we
389
448
                else:
390
449
                    yield saved_lines
391
450
            saved_lines = []
392
 
        elif line.startswith('@@'):
 
451
        elif line.startswith(b'@@'):
393
452
            hunk = hunk_from_header(line)
394
453
            orig_range = hunk.orig_range
395
454
        saved_lines.append(line)
411
470
    last_line = None
412
471
    for line in iter_lines:
413
472
        if line == NO_NL:
414
 
            if not last_line.endswith('\n'):
 
473
            if not last_line.endswith(b'\n'):
415
474
                raise AssertionError()
416
475
            last_line = last_line[:-1]
417
476
            line = None
431
490
    :kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
432
491
        Default False.
433
492
    '''
434
 
    patches = []
435
493
    for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
436
494
        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']})
 
495
            yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
 
496
                    'dirty_head': patch_lines['dirty_head']})
440
497
        else:
441
 
            patches.append(parse_patch(patch_lines, allow_dirty))
442
 
    return patches
 
498
            yield parse_patch(patch_lines, allow_dirty)
443
499
 
444
500
 
445
501
def difference_index(atext, btext):
457
513
        length = len(btext)
458
514
    for i in range(length):
459
515
        if atext[i] != btext[i]:
460
 
            return i;
 
516
            return i
461
517
    return None
462
518
 
463
519
 
483
539
        orig_lines = iter(orig_lines)
484
540
    for hunk in hunks:
485
541
        while line_no < hunk.orig_pos:
486
 
            orig_line = orig_lines.next()
 
542
            orig_line = next(orig_lines)
487
543
            yield orig_line
488
544
            line_no += 1
489
545
        for hunk_line in hunk.lines:
490
 
            seen_patch.append(str(hunk_line))
 
546
            seen_patch.append(hunk_line.contents)
491
547
            if isinstance(hunk_line, InsertLine):
492
548
                yield hunk_line.contents
493
549
            elif isinstance(hunk_line, (ContextLine, RemoveLine)):
494
 
                orig_line = orig_lines.next()
 
550
                orig_line = next(orig_lines)
495
551
                if orig_line != hunk_line.contents:
496
 
                    raise PatchConflict(line_no, orig_line, "".join(seen_patch))
 
552
                    raise PatchConflict(line_no, orig_line,
 
553
                                        b''.join(seen_patch))
497
554
                if isinstance(hunk_line, ContextLine):
498
555
                    yield orig_line
499
556
                else:
503
560
    if orig_lines is not None:
504
561
        for line in orig_lines:
505
562
            yield line
 
563
 
 
564
 
 
565
def apply_patches(tt, patches, prefix=1):
 
566
    """Apply patches to a TreeTransform.
 
567
 
 
568
    :param tt: TreeTransform instance
 
569
    :param patches: List of patches
 
570
    :param prefix: Number leading path segments to strip
 
571
    """
 
572
    def strip_prefix(p):
 
573
        return '/'.join(p.split('/')[1:])
 
574
 
 
575
    from breezy.bzr.generate_ids import gen_file_id
 
576
    # TODO(jelmer): Extract and set mode
 
577
    for patch in patches:
 
578
        if patch.oldname == b'/dev/null':
 
579
            trans_id = None
 
580
            orig_contents = b''
 
581
        else:
 
582
            oldname = strip_prefix(patch.oldname.decode())
 
583
            trans_id = tt.trans_id_tree_path(oldname)
 
584
            orig_contents = tt._tree.get_file_text(oldname)
 
585
            tt.delete_contents(trans_id)
 
586
 
 
587
        if patch.newname != b'/dev/null':
 
588
            newname = strip_prefix(patch.newname.decode())
 
589
            new_contents = iter_patched_from_hunks(
 
590
                orig_contents.splitlines(True), patch.hunks)
 
591
            if trans_id is None:
 
592
                parts = os.path.split(newname)
 
593
                trans_id = tt.root
 
594
                for part in parts[1:-1]:
 
595
                    trans_id = tt.new_directory(part, trans_id)
 
596
                tt.new_file(
 
597
                    parts[-1], trans_id, new_contents,
 
598
                    file_id=gen_file_id(newname))
 
599
            else:
 
600
                tt.create_file(new_contents, trans_id)
 
601
 
 
602
 
 
603
class AppliedPatches(object):
 
604
    """Context that provides access to a tree with patches applied.
 
605
    """
 
606
 
 
607
    def __init__(self, tree, patches, prefix=1):
 
608
        self.tree = tree
 
609
        self.patches = patches
 
610
        self.prefix = prefix
 
611
 
 
612
    def __enter__(self):
 
613
        self._tt = self.tree.preview_transform()
 
614
        apply_patches(self._tt, self.patches, prefix=self.prefix)
 
615
        return self._tt.get_preview_tree()
 
616
 
 
617
    def __exit__(self, exc_type, exc_value, exc_tb):
 
618
        self._tt.finalize()
 
619
        return False