~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/patches.py

  • Committer: Jelmer Vernooij
  • Date: 2012-01-27 19:05:43 UTC
  • mto: This revision was merged to the branch mainline in revision 6450.
  • Revision ID: jelmer@samba.org-20120127190543-vk350mv4a0c7aug2
Fix weave test.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004 - 2006 Aaron Bentley, Canonical Ltd
 
1
# Copyright (C) 2005-2010 Aaron Bentley, Canonical Ltd
2
2
# <aaron.bentley@utoronto.ca>
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
13
13
#
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
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
17
 
 
18
from __future__ import absolute_import
 
19
 
 
20
from bzrlib.errors import (
 
21
    BinaryFiles,
 
22
    MalformedHunkHeader,
 
23
    MalformedLine,
 
24
    MalformedPatchHeader,
 
25
    PatchConflict,
 
26
    PatchSyntax,
 
27
    )
 
28
 
17
29
import re
18
30
 
19
31
 
20
 
class PatchSyntax(Exception):
21
 
    def __init__(self, msg):
22
 
        Exception.__init__(self, msg)
23
 
 
24
 
 
25
 
class MalformedPatchHeader(PatchSyntax):
26
 
    def __init__(self, desc, line):
27
 
        self.desc = desc
28
 
        self.line = line
29
 
        msg = "Malformed patch header.  %s\n%r" % (self.desc, self.line)
30
 
        PatchSyntax.__init__(self, msg)
31
 
 
32
 
 
33
 
class MalformedHunkHeader(PatchSyntax):
34
 
    def __init__(self, desc, line):
35
 
        self.desc = desc
36
 
        self.line = line
37
 
        msg = "Malformed hunk header.  %s\n%r" % (self.desc, self.line)
38
 
        PatchSyntax.__init__(self, msg)
39
 
 
40
 
 
41
 
class MalformedLine(PatchSyntax):
42
 
    def __init__(self, desc, line):
43
 
        self.desc = desc
44
 
        self.line = line
45
 
        msg = "Malformed line.  %s\n%s" % (self.desc, self.line)
46
 
        PatchSyntax.__init__(self, msg)
47
 
 
48
 
 
49
 
class PatchConflict(Exception):
50
 
    def __init__(self, line_no, orig_line, patch_line):
51
 
        orig = orig_line.rstrip('\n')
52
 
        patch = str(patch_line).rstrip('\n')
53
 
        msg = 'Text contents mismatch at line %d.  Original has "%s",'\
54
 
            ' but patch says it should be "%s"' % (line_no, orig, patch)
55
 
        Exception.__init__(self, msg)
56
 
 
 
32
binary_files_re = 'Binary files (.*) and (.*) differ\n'
57
33
 
58
34
def get_patch_names(iter_lines):
59
35
    try:
60
36
        line = iter_lines.next()
 
37
        match = re.match(binary_files_re, line)
 
38
        if match is not None:
 
39
            raise BinaryFiles(match.group(1), match.group(2))
61
40
        if not line.startswith("--- "):
62
41
            raise MalformedPatchHeader("No orig name", line)
63
42
        else:
93
72
    range = int(range)
94
73
    return (pos, range)
95
74
 
96
 
 
 
75
 
97
76
def hunk_from_header(line):
 
77
    import re
98
78
    matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
99
79
    if matches is None:
100
80
        raise MalformedHunkHeader("Does not match format.", line)
164
144
        return InsertLine(line[1:])
165
145
    elif line.startswith("-"):
166
146
        return RemoveLine(line[1:])
167
 
    elif line == NO_NL:
168
 
        return NO_NL
169
147
    else:
170
148
        raise MalformedLine("Unknown line type", line)
171
149
__pychecker__=""
237
215
        return shift
238
216
 
239
217
 
240
 
def iter_hunks(iter_lines):
 
218
def iter_hunks(iter_lines, allow_dirty=False):
 
219
    '''
 
220
    :arg iter_lines: iterable of lines to parse for hunks
 
221
    :kwarg allow_dirty: If True, when we encounter something that is not
 
222
        a hunk header when we're looking for one, assume the rest of the lines
 
223
        are not part of the patch (comments or other junk).  Default False
 
224
    '''
241
225
    hunk = None
242
226
    for line in iter_lines:
243
227
        if line == "\n":
247
231
            continue
248
232
        if hunk is not None:
249
233
            yield hunk
250
 
        hunk = hunk_from_header(line)
 
234
        try:
 
235
            hunk = hunk_from_header(line)
 
236
        except MalformedHunkHeader:
 
237
            if allow_dirty:
 
238
                # If the line isn't a hunk header, then we've reached the end
 
239
                # of this patch and there's "junk" at the end.  Ignore the
 
240
                # rest of this patch.
 
241
                return
 
242
            raise
251
243
        orig_size = 0
252
244
        mod_size = 0
253
245
        while orig_size < hunk.orig_range or mod_size < hunk.mod_range:
261
253
        yield hunk
262
254
 
263
255
 
264
 
class Patch:
 
256
class BinaryPatch(object):
265
257
    def __init__(self, oldname, newname):
266
258
        self.oldname = oldname
267
259
        self.newname = newname
 
260
 
 
261
    def __str__(self):
 
262
        return 'Binary files %s and %s differ\n' % (self.oldname, self.newname)
 
263
 
 
264
 
 
265
class Patch(BinaryPatch):
 
266
 
 
267
    def __init__(self, oldname, newname):
 
268
        BinaryPatch.__init__(self, oldname, newname)
268
269
        self.hunks = []
269
270
 
270
271
    def __str__(self):
271
 
        ret = self.get_header() 
 
272
        ret = self.get_header()
272
273
        ret += "".join([str(h) for h in self.hunks])
273
274
        return ret
274
275
 
275
276
    def get_header(self):
276
277
        return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
277
278
 
278
 
    def stats_str(self):
279
 
        """Return a string of patch statistics"""
 
279
    def stats_values(self):
 
280
        """Calculate the number of inserts and removes."""
280
281
        removes = 0
281
282
        inserts = 0
282
283
        for hunk in self.hunks:
285
286
                     inserts+=1;
286
287
                elif isinstance(line, RemoveLine):
287
288
                     removes+=1;
 
289
        return (inserts, removes, len(self.hunks))
 
290
 
 
291
    def stats_str(self):
 
292
        """Return a string of patch statistics"""
288
293
        return "%i inserts, %i removes in %i hunks" % \
289
 
            (inserts, removes, len(self.hunks))
 
294
            self.stats_values()
290
295
 
291
296
    def pos_in_mod(self, position):
292
297
        newpos = position
296
301
                return None
297
302
            newpos += shift
298
303
        return newpos
299
 
            
 
304
 
300
305
    def iter_inserted(self):
301
306
        """Iteraties through inserted lines
302
 
        
 
307
 
303
308
        :return: Pair of line number, line
304
309
        :rtype: iterator of (int, InsertLine)
305
310
        """
313
318
                    pos += 1
314
319
 
315
320
 
316
 
def parse_patch(iter_lines):
317
 
    (orig_name, mod_name) = get_patch_names(iter_lines)
318
 
    patch = Patch(orig_name, mod_name)
319
 
    for hunk in iter_hunks(iter_lines):
320
 
        patch.hunks.append(hunk)
321
 
    return patch
322
 
 
323
 
 
324
 
def iter_file_patch(iter_lines):
 
321
def parse_patch(iter_lines, allow_dirty=False):
 
322
    '''
 
323
    :arg iter_lines: iterable of lines to parse
 
324
    :kwarg allow_dirty: If True, allow the patch to have trailing junk.
 
325
        Default False
 
326
    '''
 
327
    iter_lines = iter_lines_handle_nl(iter_lines)
 
328
    try:
 
329
        (orig_name, mod_name) = get_patch_names(iter_lines)
 
330
    except BinaryFiles, e:
 
331
        return BinaryPatch(e.orig_name, e.mod_name)
 
332
    else:
 
333
        patch = Patch(orig_name, mod_name)
 
334
        for hunk in iter_hunks(iter_lines, allow_dirty):
 
335
            patch.hunks.append(hunk)
 
336
        return patch
 
337
 
 
338
 
 
339
def iter_file_patch(iter_lines, allow_dirty=False):
 
340
    '''
 
341
    :arg iter_lines: iterable of lines to parse for patches
 
342
    :kwarg allow_dirty: If True, allow comments and other non-patch text
 
343
        before the first patch.  Note that the algorithm here can only find
 
344
        such text before any patches have been found.  Comments after the
 
345
        first patch are stripped away in iter_hunks() if it is also passed
 
346
        allow_dirty=True.  Default False.
 
347
    '''
 
348
    ### FIXME: Docstring is not quite true.  We allow certain comments no
 
349
    # matter what, If they startwith '===', '***', or '#' Someone should
 
350
    # reexamine this logic and decide if we should include those in
 
351
    # allow_dirty or restrict those to only being before the patch is found
 
352
    # (as allow_dirty does).
 
353
    regex = re.compile(binary_files_re)
325
354
    saved_lines = []
326
355
    orig_range = 0
 
356
    beginning = True
327
357
    for line in iter_lines:
328
358
        if line.startswith('=== ') or line.startswith('*** '):
329
359
            continue
332
362
        elif orig_range > 0:
333
363
            if line.startswith('-') or line.startswith(' '):
334
364
                orig_range -= 1
335
 
        elif line.startswith('--- '):
336
 
            if len(saved_lines) > 0:
 
365
        elif line.startswith('--- ') or regex.match(line):
 
366
            if allow_dirty and beginning:
 
367
                # Patches can have "junk" at the beginning
 
368
                # Stripping junk from the end of patches is handled when we
 
369
                # parse the patch
 
370
                beginning = False
 
371
            elif len(saved_lines) > 0:
337
372
                yield saved_lines
338
373
            saved_lines = []
339
374
        elif line.startswith('@@'):
365
400
        yield last_line
366
401
 
367
402
 
368
 
def parse_patches(iter_lines):
369
 
    iter_lines = iter_lines_handle_nl(iter_lines)
370
 
    return [parse_patch(f.__iter__()) for f in iter_file_patch(iter_lines)]
 
403
def parse_patches(iter_lines, allow_dirty=False):
 
404
    '''
 
405
    :arg iter_lines: iterable of lines to parse for patches
 
406
    :kwarg allow_dirty: If True, allow text that's not part of the patch at
 
407
        selected places.  This includes comments before and after a patch
 
408
        for instance.  Default False.
 
409
    '''
 
410
    return [parse_patch(f.__iter__(), allow_dirty) for f in
 
411
                        iter_file_patch(iter_lines, allow_dirty)]
371
412
 
372
413
 
373
414
def difference_index(atext, btext):
393
434
    """Iterate through a series of lines with a patch applied.
394
435
    This handles a single file, and does exact, not fuzzy patching.
395
436
    """
396
 
    if orig_lines is not None:
397
 
        orig_lines = orig_lines.__iter__()
 
437
    patch_lines = iter_lines_handle_nl(iter(patch_lines))
 
438
    get_patch_names(patch_lines)
 
439
    return iter_patched_from_hunks(orig_lines, iter_hunks(patch_lines))
 
440
 
 
441
 
 
442
def iter_patched_from_hunks(orig_lines, hunks):
 
443
    """Iterate through a series of lines with a patch applied.
 
444
    This handles a single file, and does exact, not fuzzy patching.
 
445
 
 
446
    :param orig_lines: The unpatched lines.
 
447
    :param hunks: An iterable of Hunk instances.
 
448
    """
398
449
    seen_patch = []
399
 
    patch_lines = iter_lines_handle_nl(patch_lines.__iter__())
400
 
    get_patch_names(patch_lines)
401
450
    line_no = 1
402
 
    for hunk in iter_hunks(patch_lines):
 
451
    if orig_lines is not None:
 
452
        orig_lines = iter(orig_lines)
 
453
    for hunk in hunks:
403
454
        while line_no < hunk.orig_pos:
404
455
            orig_line = orig_lines.next()
405
456
            yield orig_line