~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/patches.py

Merge bzr.dev

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004 - 2006, 2008 Aaron Bentley, Canonical Ltd
 
1
# Copyright (C) 2004 - 2006 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17
17
 
18
18
 
19
19
class PatchSyntax(Exception):
92
92
    range = int(range)
93
93
    return (pos, range)
94
94
 
95
 
 
 
95
 
96
96
def hunk_from_header(line):
97
 
    import re
98
 
    matches = re.match(r'\@\@ ([^@]*) \@\@( (.*))?\n', line)
99
 
    if matches is None:
100
 
        raise MalformedHunkHeader("Does not match format.", line)
 
97
    if not line.startswith("@@") or not line.endswith("@@\n") \
 
98
        or not len(line) > 4:
 
99
        raise MalformedHunkHeader("Does not start and end with @@.", line)
101
100
    try:
102
 
        (orig, mod) = matches.group(1).split(" ")
103
 
    except (ValueError, IndexError), e:
 
101
        (orig, mod) = line[3:-4].split(" ")
 
102
    except Exception, e:
104
103
        raise MalformedHunkHeader(str(e), line)
105
104
    if not orig.startswith('-') or not mod.startswith('+'):
106
105
        raise MalformedHunkHeader("Positions don't start with + or -.", line)
107
106
    try:
108
107
        (orig_pos, orig_range) = parse_range(orig[1:])
109
108
        (mod_pos, mod_range) = parse_range(mod[1:])
110
 
    except (ValueError, IndexError), e:
 
109
    except Exception, e:
111
110
        raise MalformedHunkHeader(str(e), line)
112
111
    if mod_range < 0 or orig_range < 0:
113
112
        raise MalformedHunkHeader("Hunk range is negative", line)
114
 
    tail = matches.group(3)
115
 
    return Hunk(orig_pos, orig_range, mod_pos, mod_range, tail)
 
113
    return Hunk(orig_pos, orig_range, mod_pos, mod_range)
116
114
 
117
115
 
118
116
class HunkLine:
164
162
        return InsertLine(line[1:])
165
163
    elif line.startswith("-"):
166
164
        return RemoveLine(line[1:])
 
165
    elif line == NO_NL:
 
166
        return NO_NL
167
167
    else:
168
168
        raise MalformedLine("Unknown line type", line)
169
169
__pychecker__=""
170
170
 
171
171
 
172
172
class Hunk:
173
 
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range, tail=None):
 
173
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range):
174
174
        self.orig_pos = orig_pos
175
175
        self.orig_range = orig_range
176
176
        self.mod_pos = mod_pos
177
177
        self.mod_range = mod_range
178
 
        self.tail = tail
179
178
        self.lines = []
180
179
 
181
180
    def get_header(self):
182
 
        if self.tail is None:
183
 
            tail_str = ''
184
 
        else:
185
 
            tail_str = ' ' + self.tail
186
 
        return "@@ -%s +%s @@%s\n" % (self.range_str(self.orig_pos,
187
 
                                                     self.orig_range),
188
 
                                      self.range_str(self.mod_pos,
189
 
                                                     self.mod_range),
190
 
                                      tail_str)
 
181
        return "@@ -%s +%s @@\n" % (self.range_str(self.orig_pos, 
 
182
                                                   self.orig_range),
 
183
                                    self.range_str(self.mod_pos, 
 
184
                                                   self.mod_range))
191
185
 
192
186
    def range_str(self, pos, range):
193
187
        """Return a file range, special-casing for 1-line files.
218
212
            return self.shift_to_mod_lines(pos)
219
213
 
220
214
    def shift_to_mod_lines(self, pos):
 
215
        assert (pos >= self.orig_pos-1 and pos <= self.orig_pos+self.orig_range)
221
216
        position = self.orig_pos-1
222
217
        shift = 0
223
218
        for line in self.lines:
266
261
        self.hunks = []
267
262
 
268
263
    def __str__(self):
269
 
        ret = self.get_header()
 
264
        ret = self.get_header() 
270
265
        ret += "".join([str(h) for h in self.hunks])
271
266
        return ret
272
267
 
273
268
    def get_header(self):
274
269
        return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
275
270
 
276
 
    def stats_values(self):
277
 
        """Calculate the number of inserts and removes."""
 
271
    def stats_str(self):
 
272
        """Return a string of patch statistics"""
278
273
        removes = 0
279
274
        inserts = 0
280
275
        for hunk in self.hunks:
283
278
                     inserts+=1;
284
279
                elif isinstance(line, RemoveLine):
285
280
                     removes+=1;
286
 
        return (inserts, removes, len(self.hunks))
287
 
 
288
 
    def stats_str(self):
289
 
        """Return a string of patch statistics"""
290
281
        return "%i inserts, %i removes in %i hunks" % \
291
 
            self.stats_values()
 
282
            (inserts, removes, len(self.hunks))
292
283
 
293
284
    def pos_in_mod(self, position):
294
285
        newpos = position
298
289
                return None
299
290
            newpos += shift
300
291
        return newpos
301
 
 
 
292
            
302
293
    def iter_inserted(self):
303
294
        """Iteraties through inserted lines
304
 
 
 
295
        
305
296
        :return: Pair of line number, line
306
297
        :rtype: iterator of (int, InsertLine)
307
298
        """
316
307
 
317
308
 
318
309
def parse_patch(iter_lines):
319
 
    iter_lines = iter_lines_handle_nl(iter_lines)
320
310
    (orig_name, mod_name) = get_patch_names(iter_lines)
321
311
    patch = Patch(orig_name, mod_name)
322
312
    for hunk in iter_hunks(iter_lines):
357
347
    last_line = None
358
348
    for line in iter_lines:
359
349
        if line == NO_NL:
360
 
            if not last_line.endswith('\n'):
361
 
                raise AssertionError()
 
350
            assert last_line.endswith('\n')
362
351
            last_line = last_line[:-1]
363
352
            line = None
364
353
        if last_line is not None:
369
358
 
370
359
 
371
360
def parse_patches(iter_lines):
 
361
    iter_lines = iter_lines_handle_nl(iter_lines)
372
362
    return [parse_patch(f.__iter__()) for f in iter_file_patch(iter_lines)]
373
363
 
374
364
 
395
385
    """Iterate through a series of lines with a patch applied.
396
386
    This handles a single file, and does exact, not fuzzy patching.
397
387
    """
398
 
    patch_lines = iter_lines_handle_nl(iter(patch_lines))
 
388
    if orig_lines is not None:
 
389
        orig_lines = orig_lines.__iter__()
 
390
    seen_patch = []
 
391
    patch_lines = iter_lines_handle_nl(patch_lines.__iter__())
399
392
    get_patch_names(patch_lines)
400
 
    return iter_patched_from_hunks(orig_lines, iter_hunks(patch_lines))
401
 
 
402
 
 
403
 
def iter_patched_from_hunks(orig_lines, hunks):
404
 
    """Iterate through a series of lines with a patch applied.
405
 
    This handles a single file, and does exact, not fuzzy patching.
406
 
 
407
 
    :param orig_lines: The unpatched lines.
408
 
    :param hunks: An iterable of Hunk instances.
409
 
    """
410
 
    seen_patch = []
411
393
    line_no = 1
412
 
    if orig_lines is not None:
413
 
        orig_lines = iter(orig_lines)
414
 
    for hunk in hunks:
 
394
    for hunk in iter_hunks(patch_lines):
415
395
        while line_no < hunk.orig_pos:
416
396
            orig_line = orig_lines.next()
417
397
            yield orig_line
427
407
                if isinstance(hunk_line, ContextLine):
428
408
                    yield orig_line
429
409
                else:
430
 
                    if not isinstance(hunk_line, RemoveLine):
431
 
                        raise AssertionError(hunk_line)
 
410
                    assert isinstance(hunk_line, RemoveLine)
432
411
                line_no += 1
433
412
    if orig_lines is not None:
434
413
        for line in orig_lines: