/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: 2020-03-22 01:35:14 UTC
  • mfrom: (7490.7.6 work)
  • mto: This revision was merged to the branch mainline in revision 7499.
  • Revision ID: jelmer@jelmer.uk-20200322013514-7vw1ntwho04rcuj3
merge lp:brz/3.1.

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
18
from .errors import (
21
19
    BzrError,
22
20
    )
23
21
 
 
22
import os
24
23
import re
25
24
 
26
25
 
27
 
binary_files_re = 'Binary files (.*) and (.*) differ\n'
 
26
binary_files_re = b'Binary files (.*) and (.*) differ\n'
28
27
 
29
28
 
30
29
class PatchSyntax(BzrError):
84
83
        match = re.match(binary_files_re, line)
85
84
        if match is not None:
86
85
            raise BinaryFiles(match.group(1), match.group(2))
87
 
        if not line.startswith("--- "):
 
86
        if not line.startswith(b"--- "):
88
87
            raise MalformedPatchHeader("No orig name", line)
89
88
        else:
90
 
            orig_name = line[4:].rstrip("\n")
 
89
            orig_name = line[4:].rstrip(b"\n")
91
90
    except StopIteration:
92
91
        raise MalformedPatchHeader("No orig line", "")
93
92
    try:
94
93
        line = next(iter_lines)
95
 
        if not line.startswith("+++ "):
 
94
        if not line.startswith(b"+++ "):
96
95
            raise PatchSyntax("No mod name")
97
96
        else:
98
 
            mod_name = line[4:].rstrip("\n")
 
97
            mod_name = line[4:].rstrip(b"\n")
99
98
    except StopIteration:
100
99
        raise MalformedPatchHeader("No mod line", "")
101
100
    return (orig_name, mod_name)
109
108
    :return: the position and range, as a tuple
110
109
    :rtype: (int, int)
111
110
    """
112
 
    tmp = textrange.split(',')
 
111
    tmp = textrange.split(b',')
113
112
    if len(tmp) == 1:
114
113
        pos = tmp[0]
115
 
        range = "1"
 
114
        range = b"1"
116
115
    else:
117
116
        (pos, range) = tmp
118
117
    pos = int(pos)
122
121
 
123
122
def hunk_from_header(line):
124
123
    import re
125
 
    matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
 
124
    matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
126
125
    if matches is None:
127
126
        raise MalformedHunkHeader("Does not match format.", line)
128
127
    try:
129
 
        (orig, mod) = matches.group(1).split(" ")
 
128
        (orig, mod) = matches.group(1).split(b" ")
130
129
    except (ValueError, IndexError) as e:
131
130
        raise MalformedHunkHeader(str(e), line)
132
 
    if not orig.startswith('-') or not mod.startswith('+'):
 
131
    if not orig.startswith(b'-') or not mod.startswith(b'+'):
133
132
        raise MalformedHunkHeader("Positions don't start with + or -.", line)
134
133
    try:
135
134
        (orig_pos, orig_range) = parse_range(orig[1:])
142
141
    return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
143
142
 
144
143
 
145
 
class HunkLine:
 
144
class HunkLine(object):
 
145
 
146
146
    def __init__(self, contents):
147
147
        self.contents = contents
148
148
 
149
149
    def get_str(self, leadchar):
150
 
        if self.contents == "\n" and leadchar == " " and False:
151
 
            return "\n"
152
 
        if not self.contents.endswith('\n'):
153
 
            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
154
154
        else:
155
 
            terminator = ''
 
155
            terminator = b''
156
156
        return leadchar + self.contents + terminator
157
157
 
 
158
    def as_bytes(self):
 
159
        raise NotImplementedError
 
160
 
158
161
 
159
162
class ContextLine(HunkLine):
 
163
 
160
164
    def __init__(self, contents):
161
165
        HunkLine.__init__(self, contents)
162
166
 
163
 
    def __str__(self):
164
 
        return self.get_str(" ")
 
167
    def as_bytes(self):
 
168
        return self.get_str(b" ")
165
169
 
166
170
 
167
171
class InsertLine(HunkLine):
168
172
    def __init__(self, contents):
169
173
        HunkLine.__init__(self, contents)
170
174
 
171
 
    def __str__(self):
172
 
        return self.get_str("+")
 
175
    def as_bytes(self):
 
176
        return self.get_str(b"+")
173
177
 
174
178
 
175
179
class RemoveLine(HunkLine):
176
180
    def __init__(self, contents):
177
181
        HunkLine.__init__(self, contents)
178
182
 
179
 
    def __str__(self):
180
 
        return self.get_str("-")
181
 
 
182
 
NO_NL = '\\ No newline at end of file\n'
183
 
__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
 
184
190
 
185
191
def parse_line(line):
186
 
    if line.startswith("\n"):
 
192
    if line.startswith(b"\n"):
187
193
        return ContextLine(line)
188
 
    elif line.startswith(" "):
 
194
    elif line.startswith(b" "):
189
195
        return ContextLine(line[1:])
190
 
    elif line.startswith("+"):
 
196
    elif line.startswith(b"+"):
191
197
        return InsertLine(line[1:])
192
 
    elif line.startswith("-"):
 
198
    elif line.startswith(b"-"):
193
199
        return RemoveLine(line[1:])
194
200
    else:
195
201
        raise MalformedLine("Unknown line type", line)
196
 
__pychecker__=""
197
 
 
198
 
 
199
 
class Hunk:
 
202
 
 
203
 
 
204
__pychecker__ = ""
 
205
 
 
206
 
 
207
class Hunk(object):
 
208
 
200
209
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
201
210
        self.orig_pos = orig_pos
202
211
        self.orig_range = orig_range
207
216
 
208
217
    def get_header(self):
209
218
        if self.tail is None:
210
 
            tail_str = ''
 
219
            tail_str = b''
211
220
        else:
212
 
            tail_str = ' ' + self.tail
213
 
        return "@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
214
 
                                                     self.orig_range),
215
 
                                      self.range_str(self.mod_pos,
216
 
                                                     self.mod_range),
217
 
                                      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)
218
227
 
219
228
    def range_str(self, pos, range):
220
229
        """Return a file range, special-casing for 1-line files.
226
235
        :return: a string in the format 1,4 except when range == pos == 1
227
236
        """
228
237
        if range == 1:
229
 
            return "%i" % pos
 
238
            return b"%i" % pos
230
239
        else:
231
 
            return "%i,%i" % (pos, range)
 
240
            return b"%i,%i" % (pos, range)
232
241
 
233
 
    def __str__(self):
 
242
    def as_bytes(self):
234
243
        lines = [self.get_header()]
235
244
        for line in self.lines:
236
 
            lines.append(str(line))
237
 
        return "".join(lines)
 
245
            lines.append(line.as_bytes())
 
246
        return b"".join(lines)
 
247
 
 
248
    __bytes__ = as_bytes
238
249
 
239
250
    def shift_to_mod(self, pos):
240
 
        if pos < self.orig_pos-1:
 
251
        if pos < self.orig_pos - 1:
241
252
            return 0
242
 
        elif pos > self.orig_pos+self.orig_range:
 
253
        elif pos > self.orig_pos + self.orig_range:
243
254
            return self.mod_range - self.orig_range
244
255
        else:
245
256
            return self.shift_to_mod_lines(pos)
246
257
 
247
258
    def shift_to_mod_lines(self, pos):
248
 
        position = self.orig_pos-1
 
259
        position = self.orig_pos - 1
249
260
        shift = 0
250
261
        for line in self.lines:
251
262
            if isinstance(line, InsertLine):
271
282
    '''
272
283
    hunk = None
273
284
    for line in iter_lines:
274
 
        if line == "\n":
 
285
        if line == b"\n":
275
286
            if hunk is not None:
276
287
                yield hunk
277
288
                hunk = None
301
312
 
302
313
 
303
314
class BinaryPatch(object):
 
315
 
304
316
    def __init__(self, oldname, newname):
305
317
        self.oldname = oldname
306
318
        self.newname = newname
307
319
 
308
 
    def __str__(self):
309
 
        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)
310
322
 
311
323
 
312
324
class Patch(BinaryPatch):
315
327
        BinaryPatch.__init__(self, oldname, newname)
316
328
        self.hunks = []
317
329
 
318
 
    def __str__(self):
 
330
    def as_bytes(self):
319
331
        ret = self.get_header()
320
 
        ret += "".join([str(h) for h in self.hunks])
 
332
        ret += b"".join([h.as_bytes() for h in self.hunks])
321
333
        return ret
322
334
 
323
335
    def get_header(self):
324
 
        return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
 
336
        return b"--- %s\n+++ %s\n" % (self.oldname, self.newname)
325
337
 
326
338
    def stats_values(self):
327
339
        """Calculate the number of inserts and removes."""
330
342
        for hunk in self.hunks:
331
343
            for line in hunk.lines:
332
344
                if isinstance(line, InsertLine):
333
 
                     inserts+=1;
 
345
                    inserts += 1
334
346
                elif isinstance(line, RemoveLine):
335
 
                     removes+=1;
 
347
                    removes += 1
336
348
        return (inserts, removes, len(self.hunks))
337
349
 
338
350
    def stats_str(self):
356
368
        :rtype: iterator of (int, InsertLine)
357
369
        """
358
370
        for hunk in self.hunks:
359
 
            pos = hunk.mod_pos - 1;
 
371
            pos = hunk.mod_pos - 1
360
372
            for line in hunk.lines:
361
373
                if isinstance(line, InsertLine):
362
374
                    yield (pos, line)
364
376
                if isinstance(line, ContextLine):
365
377
                    pos += 1
366
378
 
 
379
 
367
380
def parse_patch(iter_lines, allow_dirty=False):
368
381
    '''
369
382
    :arg iter_lines: iterable of lines to parse
391
404
        first patch are stripped away in iter_hunks() if it is also passed
392
405
        allow_dirty=True.  Default False.
393
406
    '''
394
 
    ### FIXME: Docstring is not quite true.  We allow certain comments no
 
407
    # FIXME: Docstring is not quite true.  We allow certain comments no
395
408
    # matter what, If they startwith '===', '***', or '#' Someone should
396
409
    # reexamine this logic and decide if we should include those in
397
410
    # allow_dirty or restrict those to only being before the patch is found
403
416
    beginning = True
404
417
 
405
418
    for line in iter_lines:
406
 
        if line.startswith('=== '):
 
419
        if line.startswith(b'=== '):
407
420
            if len(saved_lines) > 0:
408
421
                if keep_dirty and len(dirty_head) > 0:
409
422
                    yield {'saved_lines': saved_lines,
414
427
                saved_lines = []
415
428
            dirty_head.append(line)
416
429
            continue
417
 
        if line.startswith('*** '):
 
430
        if line.startswith(b'*** '):
418
431
            continue
419
 
        if line.startswith('#'):
 
432
        if line.startswith(b'#'):
420
433
            continue
421
434
        elif orig_range > 0:
422
 
            if line.startswith('-') or line.startswith(' '):
 
435
            if line.startswith(b'-') or line.startswith(b' '):
423
436
                orig_range -= 1
424
 
        elif line.startswith('--- ') or regex.match(line):
 
437
        elif line.startswith(b'--- ') or regex.match(line):
425
438
            if allow_dirty and beginning:
426
439
                # Patches can have "junk" at the beginning
427
440
                # Stripping junk from the end of patches is handled when we
435
448
                else:
436
449
                    yield saved_lines
437
450
            saved_lines = []
438
 
        elif line.startswith('@@'):
 
451
        elif line.startswith(b'@@'):
439
452
            hunk = hunk_from_header(line)
440
453
            orig_range = hunk.orig_range
441
454
        saved_lines.append(line)
457
470
    last_line = None
458
471
    for line in iter_lines:
459
472
        if line == NO_NL:
460
 
            if not last_line.endswith('\n'):
 
473
            if not last_line.endswith(b'\n'):
461
474
                raise AssertionError()
462
475
            last_line = last_line[:-1]
463
476
            line = None
477
490
    :kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
478
491
        Default False.
479
492
    '''
480
 
    patches = []
481
493
    for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
482
494
        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']})
 
495
            yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
 
496
                    'dirty_head': patch_lines['dirty_head']})
486
497
        else:
487
 
            patches.append(parse_patch(patch_lines, allow_dirty))
488
 
    return patches
 
498
            yield parse_patch(patch_lines, allow_dirty)
489
499
 
490
500
 
491
501
def difference_index(atext, btext):
503
513
        length = len(btext)
504
514
    for i in range(length):
505
515
        if atext[i] != btext[i]:
506
 
            return i;
 
516
            return i
507
517
    return None
508
518
 
509
519
 
533
543
            yield orig_line
534
544
            line_no += 1
535
545
        for hunk_line in hunk.lines:
536
 
            seen_patch.append(str(hunk_line))
 
546
            seen_patch.append(hunk_line.contents)
537
547
            if isinstance(hunk_line, InsertLine):
538
548
                yield hunk_line.contents
539
549
            elif isinstance(hunk_line, (ContextLine, RemoveLine)):
540
550
                orig_line = next(orig_lines)
541
551
                if orig_line != hunk_line.contents:
542
 
                    raise PatchConflict(line_no, orig_line, "".join(seen_patch))
 
552
                    raise PatchConflict(line_no, orig_line,
 
553
                                        b''.join(seen_patch))
543
554
                if isinstance(hunk_line, ContextLine):
544
555
                    yield orig_line
545
556
                else:
549
560
    if orig_lines is not None:
550
561
        for line in orig_lines:
551
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
        from .transform import TransformPreview
 
614
        self._tt = TransformPreview(self.tree)
 
615
        apply_patches(self._tt, self.patches, prefix=self.prefix)
 
616
        return self._tt.get_preview_tree()
 
617
 
 
618
    def __exit__(self, exc_type, exc_value, exc_tb):
 
619
        self._tt.finalize()
 
620
        return False