/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: Vincent Ladeuil
  • Date: 2010-07-07 11:21:19 UTC
  • mto: (5193.7.1 unify-confs)
  • mto: This revision was merged to the branch mainline in revision 5349.
  • Revision ID: v.ladeuil+lp@free.fr-20100707112119-jwyh312df41w6l0o
Revert previous change as I can't reproduce the related problem anymore.

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