/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

Merge test-run support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
21
21
    BzrError,
22
22
    )
23
23
 
24
 
import os
25
24
import re
26
25
 
27
26
 
28
 
binary_files_re = b'Binary files (.*) and (.*) differ\n'
 
27
binary_files_re = 'Binary files (.*) and (.*) differ\n'
29
28
 
30
29
 
31
30
class PatchSyntax(BzrError):
85
84
        match = re.match(binary_files_re, line)
86
85
        if match is not None:
87
86
            raise BinaryFiles(match.group(1), match.group(2))
88
 
        if not line.startswith(b"--- "):
 
87
        if not line.startswith("--- "):
89
88
            raise MalformedPatchHeader("No orig name", line)
90
89
        else:
91
 
            orig_name = line[4:].rstrip(b"\n")
 
90
            orig_name = line[4:].rstrip("\n")
92
91
    except StopIteration:
93
92
        raise MalformedPatchHeader("No orig line", "")
94
93
    try:
95
94
        line = next(iter_lines)
96
 
        if not line.startswith(b"+++ "):
 
95
        if not line.startswith("+++ "):
97
96
            raise PatchSyntax("No mod name")
98
97
        else:
99
 
            mod_name = line[4:].rstrip(b"\n")
 
98
            mod_name = line[4:].rstrip("\n")
100
99
    except StopIteration:
101
100
        raise MalformedPatchHeader("No mod line", "")
102
101
    return (orig_name, mod_name)
110
109
    :return: the position and range, as a tuple
111
110
    :rtype: (int, int)
112
111
    """
113
 
    tmp = textrange.split(b',')
 
112
    tmp = textrange.split(',')
114
113
    if len(tmp) == 1:
115
114
        pos = tmp[0]
116
 
        range = b"1"
 
115
        range = "1"
117
116
    else:
118
117
        (pos, range) = tmp
119
118
    pos = int(pos)
123
122
 
124
123
def hunk_from_header(line):
125
124
    import re
126
 
    matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
 
125
    matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
127
126
    if matches is None:
128
127
        raise MalformedHunkHeader("Does not match format.", line)
129
128
    try:
130
 
        (orig, mod) = matches.group(1).split(b" ")
 
129
        (orig, mod) = matches.group(1).split(" ")
131
130
    except (ValueError, IndexError) as e:
132
131
        raise MalformedHunkHeader(str(e), line)
133
 
    if not orig.startswith(b'-') or not mod.startswith(b'+'):
 
132
    if not orig.startswith('-') or not mod.startswith('+'):
134
133
        raise MalformedHunkHeader("Positions don't start with + or -.", line)
135
134
    try:
136
135
        (orig_pos, orig_range) = parse_range(orig[1:])
143
142
    return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
144
143
 
145
144
 
146
 
class HunkLine(object):
147
 
 
 
145
class HunkLine:
148
146
    def __init__(self, contents):
149
147
        self.contents = contents
150
148
 
151
149
    def get_str(self, leadchar):
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
 
150
        if self.contents == "\n" and leadchar == " " and False:
 
151
            return "\n"
 
152
        if not self.contents.endswith('\n'):
 
153
            terminator = '\n' + NO_NL
156
154
        else:
157
 
            terminator = b''
 
155
            terminator = ''
158
156
        return leadchar + self.contents + terminator
159
157
 
160
 
    def as_bytes(self):
161
 
        raise NotImplementedError
162
 
 
163
158
 
164
159
class ContextLine(HunkLine):
165
 
 
166
160
    def __init__(self, contents):
167
161
        HunkLine.__init__(self, contents)
168
162
 
169
 
    def as_bytes(self):
170
 
        return self.get_str(b" ")
 
163
    def __str__(self):
 
164
        return self.get_str(" ")
171
165
 
172
166
 
173
167
class InsertLine(HunkLine):
174
168
    def __init__(self, contents):
175
169
        HunkLine.__init__(self, contents)
176
170
 
177
 
    def as_bytes(self):
178
 
        return self.get_str(b"+")
 
171
    def __str__(self):
 
172
        return self.get_str("+")
179
173
 
180
174
 
181
175
class RemoveLine(HunkLine):
182
176
    def __init__(self, contents):
183
177
        HunkLine.__init__(self, contents)
184
178
 
185
 
    def as_bytes(self):
186
 
        return self.get_str(b"-")
187
 
 
188
 
 
189
 
NO_NL = b'\\ No newline at end of file\n'
190
 
__pychecker__ = "no-returnvalues"
191
 
 
 
179
    def __str__(self):
 
180
        return self.get_str("-")
 
181
 
 
182
NO_NL = '\\ No newline at end of file\n'
 
183
__pychecker__="no-returnvalues"
192
184
 
193
185
def parse_line(line):
194
 
    if line.startswith(b"\n"):
 
186
    if line.startswith("\n"):
195
187
        return ContextLine(line)
196
 
    elif line.startswith(b" "):
 
188
    elif line.startswith(" "):
197
189
        return ContextLine(line[1:])
198
 
    elif line.startswith(b"+"):
 
190
    elif line.startswith("+"):
199
191
        return InsertLine(line[1:])
200
 
    elif line.startswith(b"-"):
 
192
    elif line.startswith("-"):
201
193
        return RemoveLine(line[1:])
202
194
    else:
203
195
        raise MalformedLine("Unknown line type", line)
204
 
 
205
 
 
206
 
__pychecker__ = ""
207
 
 
208
 
 
209
 
class Hunk(object):
210
 
 
 
196
__pychecker__=""
 
197
 
 
198
 
 
199
class Hunk:
211
200
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
212
201
        self.orig_pos = orig_pos
213
202
        self.orig_range = orig_range
218
207
 
219
208
    def get_header(self):
220
209
        if self.tail is None:
221
 
            tail_str = b''
 
210
            tail_str = ''
222
211
        else:
223
 
            tail_str = b' ' + self.tail
224
 
        return b"@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
225
 
                                                      self.orig_range),
226
 
                                       self.range_str(self.mod_pos,
227
 
                                                      self.mod_range),
228
 
                                       tail_str)
 
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)
229
218
 
230
219
    def range_str(self, pos, range):
231
220
        """Return a file range, special-casing for 1-line files.
237
226
        :return: a string in the format 1,4 except when range == pos == 1
238
227
        """
239
228
        if range == 1:
240
 
            return b"%i" % pos
 
229
            return "%i" % pos
241
230
        else:
242
 
            return b"%i,%i" % (pos, range)
 
231
            return "%i,%i" % (pos, range)
243
232
 
244
 
    def as_bytes(self):
 
233
    def __str__(self):
245
234
        lines = [self.get_header()]
246
235
        for line in self.lines:
247
 
            lines.append(line.as_bytes())
248
 
        return b"".join(lines)
249
 
 
250
 
    __bytes__ = as_bytes
 
236
            lines.append(str(line))
 
237
        return "".join(lines)
251
238
 
252
239
    def shift_to_mod(self, pos):
253
 
        if pos < self.orig_pos - 1:
 
240
        if pos < self.orig_pos-1:
254
241
            return 0
255
 
        elif pos > self.orig_pos + self.orig_range:
 
242
        elif pos > self.orig_pos+self.orig_range:
256
243
            return self.mod_range - self.orig_range
257
244
        else:
258
245
            return self.shift_to_mod_lines(pos)
259
246
 
260
247
    def shift_to_mod_lines(self, pos):
261
 
        position = self.orig_pos - 1
 
248
        position = self.orig_pos-1
262
249
        shift = 0
263
250
        for line in self.lines:
264
251
            if isinstance(line, InsertLine):
284
271
    '''
285
272
    hunk = None
286
273
    for line in iter_lines:
287
 
        if line == b"\n":
 
274
        if line == "\n":
288
275
            if hunk is not None:
289
276
                yield hunk
290
277
                hunk = None
314
301
 
315
302
 
316
303
class BinaryPatch(object):
317
 
 
318
304
    def __init__(self, oldname, newname):
319
305
        self.oldname = oldname
320
306
        self.newname = newname
321
307
 
322
 
    def as_bytes(self):
323
 
        return b'Binary files %s and %s differ\n' % (self.oldname, self.newname)
 
308
    def __str__(self):
 
309
        return 'Binary files %s and %s differ\n' % (self.oldname, self.newname)
324
310
 
325
311
 
326
312
class Patch(BinaryPatch):
329
315
        BinaryPatch.__init__(self, oldname, newname)
330
316
        self.hunks = []
331
317
 
332
 
    def as_bytes(self):
 
318
    def __str__(self):
333
319
        ret = self.get_header()
334
 
        ret += b"".join([h.as_bytes() for h in self.hunks])
 
320
        ret += "".join([str(h) for h in self.hunks])
335
321
        return ret
336
322
 
337
323
    def get_header(self):
338
 
        return b"--- %s\n+++ %s\n" % (self.oldname, self.newname)
 
324
        return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
339
325
 
340
326
    def stats_values(self):
341
327
        """Calculate the number of inserts and removes."""
344
330
        for hunk in self.hunks:
345
331
            for line in hunk.lines:
346
332
                if isinstance(line, InsertLine):
347
 
                    inserts += 1
 
333
                     inserts+=1;
348
334
                elif isinstance(line, RemoveLine):
349
 
                    removes += 1
 
335
                     removes+=1;
350
336
        return (inserts, removes, len(self.hunks))
351
337
 
352
338
    def stats_str(self):
370
356
        :rtype: iterator of (int, InsertLine)
371
357
        """
372
358
        for hunk in self.hunks:
373
 
            pos = hunk.mod_pos - 1
 
359
            pos = hunk.mod_pos - 1;
374
360
            for line in hunk.lines:
375
361
                if isinstance(line, InsertLine):
376
362
                    yield (pos, line)
378
364
                if isinstance(line, ContextLine):
379
365
                    pos += 1
380
366
 
381
 
 
382
367
def parse_patch(iter_lines, allow_dirty=False):
383
368
    '''
384
369
    :arg iter_lines: iterable of lines to parse
406
391
        first patch are stripped away in iter_hunks() if it is also passed
407
392
        allow_dirty=True.  Default False.
408
393
    '''
409
 
    # FIXME: Docstring is not quite true.  We allow certain comments no
 
394
    ### FIXME: Docstring is not quite true.  We allow certain comments no
410
395
    # matter what, If they startwith '===', '***', or '#' Someone should
411
396
    # reexamine this logic and decide if we should include those in
412
397
    # allow_dirty or restrict those to only being before the patch is found
418
403
    beginning = True
419
404
 
420
405
    for line in iter_lines:
421
 
        if line.startswith(b'=== '):
 
406
        if line.startswith('=== '):
422
407
            if len(saved_lines) > 0:
423
408
                if keep_dirty and len(dirty_head) > 0:
424
409
                    yield {'saved_lines': saved_lines,
429
414
                saved_lines = []
430
415
            dirty_head.append(line)
431
416
            continue
432
 
        if line.startswith(b'*** '):
 
417
        if line.startswith('*** '):
433
418
            continue
434
 
        if line.startswith(b'#'):
 
419
        if line.startswith('#'):
435
420
            continue
436
421
        elif orig_range > 0:
437
 
            if line.startswith(b'-') or line.startswith(b' '):
 
422
            if line.startswith('-') or line.startswith(' '):
438
423
                orig_range -= 1
439
 
        elif line.startswith(b'--- ') or regex.match(line):
 
424
        elif line.startswith('--- ') or regex.match(line):
440
425
            if allow_dirty and beginning:
441
426
                # Patches can have "junk" at the beginning
442
427
                # Stripping junk from the end of patches is handled when we
450
435
                else:
451
436
                    yield saved_lines
452
437
            saved_lines = []
453
 
        elif line.startswith(b'@@'):
 
438
        elif line.startswith('@@'):
454
439
            hunk = hunk_from_header(line)
455
440
            orig_range = hunk.orig_range
456
441
        saved_lines.append(line)
472
457
    last_line = None
473
458
    for line in iter_lines:
474
459
        if line == NO_NL:
475
 
            if not last_line.endswith(b'\n'):
 
460
            if not last_line.endswith('\n'):
476
461
                raise AssertionError()
477
462
            last_line = last_line[:-1]
478
463
            line = None
492
477
    :kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
493
478
        Default False.
494
479
    '''
 
480
    patches = []
495
481
    for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
496
482
        if 'dirty_head' in patch_lines:
497
 
            yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
498
 
                    'dirty_head': patch_lines['dirty_head']})
 
483
            patches.append({'patch': parse_patch(
 
484
                patch_lines['saved_lines'], allow_dirty),
 
485
                            'dirty_head': patch_lines['dirty_head']})
499
486
        else:
500
 
            yield parse_patch(patch_lines, allow_dirty)
 
487
            patches.append(parse_patch(patch_lines, allow_dirty))
 
488
    return patches
501
489
 
502
490
 
503
491
def difference_index(atext, btext):
515
503
        length = len(btext)
516
504
    for i in range(length):
517
505
        if atext[i] != btext[i]:
518
 
            return i
 
506
            return i;
519
507
    return None
520
508
 
521
509
 
545
533
            yield orig_line
546
534
            line_no += 1
547
535
        for hunk_line in hunk.lines:
548
 
            seen_patch.append(hunk_line.contents)
 
536
            seen_patch.append(str(hunk_line))
549
537
            if isinstance(hunk_line, InsertLine):
550
538
                yield hunk_line.contents
551
539
            elif isinstance(hunk_line, (ContextLine, RemoveLine)):
552
540
                orig_line = next(orig_lines)
553
541
                if orig_line != hunk_line.contents:
554
 
                    raise PatchConflict(line_no, orig_line,
555
 
                                        b''.join(seen_patch))
 
542
                    raise PatchConflict(line_no, orig_line, "".join(seen_patch))
556
543
                if isinstance(hunk_line, ContextLine):
557
544
                    yield orig_line
558
545
                else:
562
549
    if orig_lines is not None:
563
550
        for line in orig_lines:
564
551
            yield line
565
 
 
566
 
 
567
 
def apply_patches(tt, patches, prefix=1):
568
 
    """Apply patches to a TreeTransform.
569
 
 
570
 
    :param tt: TreeTransform instance
571
 
    :param patches: List of patches
572
 
    :param prefix: Number leading path segments to strip
573
 
    """
574
 
    def strip_prefix(p):
575
 
        return '/'.join(p.split('/')[1:])
576
 
 
577
 
    from breezy.bzr.generate_ids import gen_file_id
578
 
    # TODO(jelmer): Extract and set mode
579
 
    for patch in patches:
580
 
        if patch.oldname == b'/dev/null':
581
 
            trans_id = None
582
 
            orig_contents = b''
583
 
        else:
584
 
            oldname = strip_prefix(patch.oldname.decode())
585
 
            trans_id = tt.trans_id_tree_path(oldname)
586
 
            orig_contents = tt._tree.get_file_text(oldname)
587
 
            tt.delete_contents(trans_id)
588
 
 
589
 
        if patch.newname != b'/dev/null':
590
 
            newname = strip_prefix(patch.newname.decode())
591
 
            new_contents = iter_patched_from_hunks(
592
 
                orig_contents.splitlines(True), patch.hunks)
593
 
            if trans_id is None:
594
 
                parts = os.path.split(newname)
595
 
                trans_id = tt.root
596
 
                for part in parts[1:-1]:
597
 
                    trans_id = tt.new_directory(part, trans_id)
598
 
                tt.new_file(
599
 
                    parts[-1], trans_id, new_contents,
600
 
                    file_id=gen_file_id(newname))
601
 
            else:
602
 
                tt.create_file(new_contents, trans_id)
603
 
 
604
 
 
605
 
class AppliedPatches(object):
606
 
    """Context that provides access to a tree with patches applied.
607
 
    """
608
 
 
609
 
    def __init__(self, tree, patches, prefix=1):
610
 
        self.tree = tree
611
 
        self.patches = patches
612
 
        self.prefix = prefix
613
 
 
614
 
    def __enter__(self):
615
 
        from .transform import TransformPreview
616
 
        self._tt = TransformPreview(self.tree)
617
 
        apply_patches(self._tt, self.patches, prefix=self.prefix)
618
 
        return self._tt.get_preview_tree()
619
 
 
620
 
    def __exit__(self, exc_type, exc_value, exc_tb):
621
 
        self._tt.finalize()
622
 
        return False