/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: Robert Collins
  • Date: 2010-05-06 11:08:10 UTC
  • mto: This revision was merged to the branch mainline in revision 5223.
  • Revision ID: robertc@robertcollins.net-20100506110810-h3j07fh5gmw54s25
Cleaner matcher matching revised unlocking protocol.

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 __future__ import absolute_import
19
 
 
20
 
from .errors import (
21
 
    BzrError,
22
 
    )
23
 
 
24
17
import re
25
 
import sys
26
 
 
27
 
 
28
 
binary_files_re = b'Binary files (.*) and (.*) differ\n'
29
 
 
30
 
 
31
 
class PatchSyntax(BzrError):
32
 
    """Base class for patch syntax errors."""
33
 
 
34
 
 
35
 
class BinaryFiles(BzrError):
36
 
 
37
 
    _fmt = 'Binary files section encountered.'
 
18
 
 
19
 
 
20
binary_files_re = 'Binary files (.*) and (.*) differ\n'
 
21
 
 
22
 
 
23
class BinaryFiles(Exception):
38
24
 
39
25
    def __init__(self, orig_name, mod_name):
40
26
        self.orig_name = orig_name
41
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)
42
34
 
43
35
 
44
36
class MalformedPatchHeader(PatchSyntax):
45
 
 
46
 
    _fmt = "Malformed patch header.  %(desc)s\n%(line)r"
47
 
 
48
 
    def __init__(self, desc, line):
49
 
        self.desc = desc
50
 
        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)
51
50
 
52
51
 
53
52
class MalformedLine(PatchSyntax):
54
 
 
55
 
    _fmt = "Malformed line.  %(desc)s\n%(line)r"
56
 
 
57
53
    def __init__(self, desc, line):
58
54
        self.desc = desc
59
55
        self.line = line
60
 
 
61
 
 
62
 
class PatchConflict(BzrError):
63
 
 
64
 
    _fmt = ('Text contents mismatch at line %(line_no)d.  Original has '
65
 
            '"%(orig_line)s", but patch says it should be "%(patch_line)s"')
66
 
 
 
56
        msg = "Malformed line.  %s\n%s" % (self.desc, self.line)
 
57
        PatchSyntax.__init__(self, msg)
 
58
 
 
59
 
 
60
class PatchConflict(Exception):
67
61
    def __init__(self, line_no, orig_line, patch_line):
68
 
        self.line_no = line_no
69
 
        self.orig_line = orig_line.rstrip('\n')
70
 
        self.patch_line = patch_line.rstrip('\n')
71
 
 
72
 
 
73
 
class MalformedHunkHeader(PatchSyntax):
74
 
 
75
 
    _fmt = "Malformed hunk header.  %(desc)s\n%(line)r"
76
 
 
77
 
    def __init__(self, desc, line):
78
 
        self.desc = desc
79
 
        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)
80
67
 
81
68
 
82
69
def get_patch_names(iter_lines):
83
 
    line = next(iter_lines)
84
70
    try:
 
71
        line = iter_lines.next()
85
72
        match = re.match(binary_files_re, line)
86
73
        if match is not None:
87
74
            raise BinaryFiles(match.group(1), match.group(2))
88
 
        if not line.startswith(b"--- "):
 
75
        if not line.startswith("--- "):
89
76
            raise MalformedPatchHeader("No orig name", line)
90
77
        else:
91
 
            orig_name = line[4:].rstrip(b"\n")
 
78
            orig_name = line[4:].rstrip("\n")
92
79
    except StopIteration:
93
80
        raise MalformedPatchHeader("No orig line", "")
94
81
    try:
95
 
        line = next(iter_lines)
96
 
        if not line.startswith(b"+++ "):
 
82
        line = iter_lines.next()
 
83
        if not line.startswith("+++ "):
97
84
            raise PatchSyntax("No mod name")
98
85
        else:
99
 
            mod_name = line[4:].rstrip(b"\n")
 
86
            mod_name = line[4:].rstrip("\n")
100
87
    except StopIteration:
101
88
        raise MalformedPatchHeader("No mod line", "")
102
89
    return (orig_name, mod_name)
110
97
    :return: the position and range, as a tuple
111
98
    :rtype: (int, int)
112
99
    """
113
 
    tmp = textrange.split(b',')
 
100
    tmp = textrange.split(',')
114
101
    if len(tmp) == 1:
115
102
        pos = tmp[0]
116
 
        range = b"1"
 
103
        range = "1"
117
104
    else:
118
105
        (pos, range) = tmp
119
106
    pos = int(pos)
123
110
 
124
111
def hunk_from_header(line):
125
112
    import re
126
 
    matches = re.match(br'\@\@ ([^@]*) \@\@( (.*))?\n', line)
 
113
    matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
127
114
    if matches is None:
128
115
        raise MalformedHunkHeader("Does not match format.", line)
129
116
    try:
130
 
        (orig, mod) = matches.group(1).split(b" ")
131
 
    except (ValueError, IndexError) as e:
 
117
        (orig, mod) = matches.group(1).split(" ")
 
118
    except (ValueError, IndexError), e:
132
119
        raise MalformedHunkHeader(str(e), line)
133
 
    if not orig.startswith(b'-') or not mod.startswith(b'+'):
 
120
    if not orig.startswith('-') or not mod.startswith('+'):
134
121
        raise MalformedHunkHeader("Positions don't start with + or -.", line)
135
122
    try:
136
123
        (orig_pos, orig_range) = parse_range(orig[1:])
137
124
        (mod_pos, mod_range) = parse_range(mod[1:])
138
 
    except (ValueError, IndexError) as e:
 
125
    except (ValueError, IndexError), e:
139
126
        raise MalformedHunkHeader(str(e), line)
140
127
    if mod_range < 0 or orig_range < 0:
141
128
        raise MalformedHunkHeader("Hunk range is negative", line)
143
130
    return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
144
131
 
145
132
 
146
 
class HunkLine(object):
147
 
 
 
133
class HunkLine:
148
134
    def __init__(self, contents):
149
135
        self.contents = contents
150
136
 
151
137
    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
 
138
        if self.contents == "\n" and leadchar == " " and False:
 
139
            return "\n"
 
140
        if not self.contents.endswith('\n'):
 
141
            terminator = '\n' + NO_NL
156
142
        else:
157
 
            terminator = b''
 
143
            terminator = ''
158
144
        return leadchar + self.contents + terminator
159
145
 
160
 
    def as_bytes(self):
161
 
        raise NotImplementedError
162
 
 
163
146
 
164
147
class ContextLine(HunkLine):
165
 
 
166
148
    def __init__(self, contents):
167
149
        HunkLine.__init__(self, contents)
168
150
 
169
 
    def as_bytes(self):
170
 
        return self.get_str(b" ")
 
151
    def __str__(self):
 
152
        return self.get_str(" ")
171
153
 
172
154
 
173
155
class InsertLine(HunkLine):
174
156
    def __init__(self, contents):
175
157
        HunkLine.__init__(self, contents)
176
158
 
177
 
    def as_bytes(self):
178
 
        return self.get_str(b"+")
 
159
    def __str__(self):
 
160
        return self.get_str("+")
179
161
 
180
162
 
181
163
class RemoveLine(HunkLine):
182
164
    def __init__(self, contents):
183
165
        HunkLine.__init__(self, contents)
184
166
 
185
 
    def as_bytes(self):
186
 
        return self.get_str(b"-")
 
167
    def __str__(self):
 
168
        return self.get_str("-")
187
169
 
188
 
NO_NL = b'\\ No newline at end of file\n'
 
170
NO_NL = '\\ No newline at end of file\n'
189
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
184
__pychecker__=""
203
185
 
204
186
 
205
 
class Hunk(object):
206
 
 
 
187
class Hunk:
207
188
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
208
189
        self.orig_pos = orig_pos
209
190
        self.orig_range = orig_range
214
195
 
215
196
    def get_header(self):
216
197
        if self.tail is None:
217
 
            tail_str = b''
 
198
            tail_str = ''
218
199
        else:
219
 
            tail_str = b' ' + self.tail
220
 
        return b"@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
 
200
            tail_str = ' ' + self.tail
 
201
        return "@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
221
202
                                                     self.orig_range),
222
203
                                      self.range_str(self.mod_pos,
223
204
                                                     self.mod_range),
233
214
        :return: a string in the format 1,4 except when range == pos == 1
234
215
        """
235
216
        if range == 1:
236
 
            return b"%i" % pos
 
217
            return "%i" % pos
237
218
        else:
238
 
            return b"%i,%i" % (pos, range)
 
219
            return "%i,%i" % (pos, range)
239
220
 
240
 
    def as_bytes(self):
 
221
    def __str__(self):
241
222
        lines = [self.get_header()]
242
223
        for line in self.lines:
243
 
            lines.append(line.as_bytes())
244
 
        return b"".join(lines)
 
224
            lines.append(str(line))
 
225
        return "".join(lines)
245
226
 
246
227
    def shift_to_mod(self, pos):
247
228
        if pos < self.orig_pos-1:
278
259
    '''
279
260
    hunk = None
280
261
    for line in iter_lines:
281
 
        if line == b"\n":
 
262
        if line == "\n":
282
263
            if hunk is not None:
283
264
                yield hunk
284
265
                hunk = None
297
278
        orig_size = 0
298
279
        mod_size = 0
299
280
        while orig_size < hunk.orig_range or mod_size < hunk.mod_range:
300
 
            hunk_line = parse_line(next(iter_lines))
 
281
            hunk_line = parse_line(iter_lines.next())
301
282
            hunk.lines.append(hunk_line)
302
283
            if isinstance(hunk_line, (RemoveLine, ContextLine)):
303
284
                orig_size += 1
308
289
 
309
290
 
310
291
class BinaryPatch(object):
311
 
 
312
292
    def __init__(self, oldname, newname):
313
293
        self.oldname = oldname
314
294
        self.newname = newname
315
295
 
316
 
    def as_bytes(self):
317
 
        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)
318
298
 
319
299
 
320
300
class Patch(BinaryPatch):
323
303
        BinaryPatch.__init__(self, oldname, newname)
324
304
        self.hunks = []
325
305
 
326
 
    def as_bytes(self):
 
306
    def __str__(self):
327
307
        ret = self.get_header()
328
 
        ret += b"".join([h.as_bytes() for h in self.hunks])
 
308
        ret += "".join([str(h) for h in self.hunks])
329
309
        return ret
330
310
 
331
311
    def get_header(self):
332
 
        return b"--- %s\n+++ %s\n" % (self.oldname, self.newname)
 
312
        return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
333
313
 
334
314
    def stats_values(self):
335
315
        """Calculate the number of inserts and removes."""
382
362
    iter_lines = iter_lines_handle_nl(iter_lines)
383
363
    try:
384
364
        (orig_name, mod_name) = get_patch_names(iter_lines)
385
 
    except BinaryFiles as e:
 
365
    except BinaryFiles, e:
386
366
        return BinaryPatch(e.orig_name, e.mod_name)
387
367
    else:
388
368
        patch = Patch(orig_name, mod_name)
391
371
        return patch
392
372
 
393
373
 
394
 
def iter_file_patch(iter_lines, allow_dirty=False, keep_dirty=False):
 
374
def iter_file_patch(iter_lines, allow_dirty=False):
395
375
    '''
396
376
    :arg iter_lines: iterable of lines to parse for patches
397
377
    :kwarg allow_dirty: If True, allow comments and other non-patch text
407
387
    # (as allow_dirty does).
408
388
    regex = re.compile(binary_files_re)
409
389
    saved_lines = []
410
 
    dirty_head = []
411
390
    orig_range = 0
412
391
    beginning = True
413
 
 
414
392
    for line in iter_lines:
415
 
        if line.startswith(b'=== '):
416
 
            if len(saved_lines) > 0:
417
 
                if keep_dirty and len(dirty_head) > 0:
418
 
                    yield {'saved_lines': saved_lines,
419
 
                           'dirty_head': dirty_head}
420
 
                    dirty_head = []
421
 
                else:
422
 
                    yield saved_lines
423
 
                saved_lines = []
424
 
            dirty_head.append(line)
425
 
            continue
426
 
        if line.startswith(b'*** '):
427
 
            continue
428
 
        if line.startswith(b'#'):
 
393
        if line.startswith('=== ') or line.startswith('*** '):
 
394
            continue
 
395
        if line.startswith('#'):
429
396
            continue
430
397
        elif orig_range > 0:
431
 
            if line.startswith(b'-') or line.startswith(b' '):
 
398
            if line.startswith('-') or line.startswith(' '):
432
399
                orig_range -= 1
433
 
        elif line.startswith(b'--- ') or regex.match(line):
 
400
        elif line.startswith('--- ') or regex.match(line):
434
401
            if allow_dirty and beginning:
435
402
                # Patches can have "junk" at the beginning
436
403
                # Stripping junk from the end of patches is handled when we
437
404
                # parse the patch
438
405
                beginning = False
439
406
            elif len(saved_lines) > 0:
440
 
                if keep_dirty and len(dirty_head) > 0:
441
 
                    yield {'saved_lines': saved_lines,
442
 
                           'dirty_head': dirty_head}
443
 
                    dirty_head = []
444
 
                else:
445
 
                    yield saved_lines
 
407
                yield saved_lines
446
408
            saved_lines = []
447
 
        elif line.startswith(b'@@'):
 
409
        elif line.startswith('@@'):
448
410
            hunk = hunk_from_header(line)
449
411
            orig_range = hunk.orig_range
450
412
        saved_lines.append(line)
451
413
    if len(saved_lines) > 0:
452
 
        if keep_dirty and len(dirty_head) > 0:
453
 
            yield {'saved_lines': saved_lines,
454
 
                   'dirty_head': dirty_head}
455
 
        else:
456
 
            yield saved_lines
 
414
        yield saved_lines
457
415
 
458
416
 
459
417
def iter_lines_handle_nl(iter_lines):
466
424
    last_line = None
467
425
    for line in iter_lines:
468
426
        if line == NO_NL:
469
 
            if not last_line.endswith(b'\n'):
 
427
            if not last_line.endswith('\n'):
470
428
                raise AssertionError()
471
429
            last_line = last_line[:-1]
472
430
            line = None
477
435
        yield last_line
478
436
 
479
437
 
480
 
def parse_patches(iter_lines, allow_dirty=False, keep_dirty=False):
 
438
def parse_patches(iter_lines, allow_dirty=False):
481
439
    '''
482
440
    :arg iter_lines: iterable of lines to parse for patches
483
441
    :kwarg allow_dirty: If True, allow text that's not part of the patch at
484
442
        selected places.  This includes comments before and after a patch
485
443
        for instance.  Default False.
486
 
    :kwarg keep_dirty: If True, returns a dict of patches with dirty headers.
487
 
        Default False.
488
444
    '''
489
 
    for patch_lines in iter_file_patch(iter_lines, allow_dirty, keep_dirty):
490
 
        if 'dirty_head' in patch_lines:
491
 
            yield ({'patch': parse_patch(patch_lines['saved_lines'], allow_dirty),
492
 
                    'dirty_head': patch_lines['dirty_head']})
493
 
        else:
494
 
            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)]
495
447
 
496
448
 
497
449
def difference_index(atext, btext):
535
487
        orig_lines = iter(orig_lines)
536
488
    for hunk in hunks:
537
489
        while line_no < hunk.orig_pos:
538
 
            orig_line = next(orig_lines)
 
490
            orig_line = orig_lines.next()
539
491
            yield orig_line
540
492
            line_no += 1
541
493
        for hunk_line in hunk.lines:
543
495
            if isinstance(hunk_line, InsertLine):
544
496
                yield hunk_line.contents
545
497
            elif isinstance(hunk_line, (ContextLine, RemoveLine)):
546
 
                orig_line = next(orig_lines)
 
498
                orig_line = orig_lines.next()
547
499
                if orig_line != hunk_line.contents:
548
 
                    raise PatchConflict(line_no, orig_line, b"".join(seen_patch))
 
500
                    raise PatchConflict(line_no, orig_line, "".join(seen_patch))
549
501
                if isinstance(hunk_line, ContextLine):
550
502
                    yield orig_line
551
503
                else: