/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 bzrlib/patches.py

  • Committer: Richard Wilbur
  • Date: 2016-02-04 19:07:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6618.
  • Revision ID: richard.wilbur@gmail.com-20160204190728-p0zvfii6zase0fw7
Update COPYING.txt from the original http://www.gnu.org/licenses/gpl-2.0.txt  (Only differences were in whitespace.)  Thanks to Petr Stodulka for pointing out the discrepancy.

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