~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to patches.py

  • Committer: Aaron Bentley
  • Date: 2011-02-02 01:56:29 UTC
  • mfrom: (749.1.3 2.3)
  • Revision ID: aaron@aaronbentley.com-20110202015629-4rrhtffv1jujnqpi
Fake merge of 2.3 into bzrtools.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005 Aaron Bentley
2
 
# <aaron.bentley@utoronto.ca>
3
 
#
4
 
#    This program is free software; you can redistribute it and/or modify
5
 
#    it under the terms of the GNU General Public License as published by
6
 
#    the Free Software Foundation; either version 2 of the License, or
7
 
#    (at your option) any later version.
8
 
#
9
 
#    This program is distributed in the hope that it will be useful,
10
 
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
 
#    GNU General Public License for more details.
13
 
#
14
 
#    You should have received a copy of the GNU General Public License
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
17
 
 
18
 
class PatchSyntax(Exception):
19
 
    def __init__(self, msg):
20
 
        Exception.__init__(self, msg)
21
 
 
22
 
 
23
 
class MalformedPatchHeader(PatchSyntax):
24
 
    def __init__(self, desc, line):
25
 
        self.desc = desc
26
 
        self.line = line
27
 
        msg = "Malformed patch header.  %s\n%r" % (self.desc, self.line)
28
 
        PatchSyntax.__init__(self, msg)
29
 
 
30
 
class MalformedHunkHeader(PatchSyntax):
31
 
    def __init__(self, desc, line):
32
 
        self.desc = desc
33
 
        self.line = line
34
 
        msg = "Malformed hunk header.  %s\n%r" % (self.desc, self.line)
35
 
        PatchSyntax.__init__(self, msg)
36
 
 
37
 
class MalformedLine(PatchSyntax):
38
 
    def __init__(self, desc, line):
39
 
        self.desc = desc
40
 
        self.line = line
41
 
        msg = "Malformed line.  %s\n%s" % (self.desc, self.line)
42
 
        PatchSyntax.__init__(self, msg)
43
 
 
44
 
def get_patch_names(iter_lines):
45
 
    try:
46
 
        line = iter_lines.next()
47
 
        if not line.startswith("--- "):
48
 
            raise MalformedPatchHeader("No orig name", line)
49
 
        else:
50
 
            orig_name = line[4:].rstrip("\n")
51
 
    except StopIteration:
52
 
        raise MalformedPatchHeader("No orig line", "")
53
 
    try:
54
 
        line = iter_lines.next()
55
 
        if not line.startswith("+++ "):
56
 
            raise PatchSyntax("No mod name")
57
 
        else:
58
 
            mod_name = line[4:].rstrip("\n")
59
 
    except StopIteration:
60
 
        raise MalformedPatchHeader("No mod line", "")
61
 
    return (orig_name, mod_name)
62
 
 
63
 
def parse_range(textrange):
64
 
    """Parse a patch range, handling the "1" special-case
65
 
 
66
 
    :param textrange: The text to parse
67
 
    :type textrange: str
68
 
    :return: the position and range, as a tuple
69
 
    :rtype: (int, int)
70
 
    """
71
 
    tmp = textrange.split(',')
72
 
    if len(tmp) == 1:
73
 
        pos = tmp[0]
74
 
        range = "1"
75
 
    else:
76
 
        (pos, range) = tmp
77
 
    pos = int(pos)
78
 
    range = int(range)
79
 
    return (pos, range)
80
 
 
81
 
 
82
 
def hunk_from_header(line):
83
 
    if not line.startswith("@@") or not line.endswith("@@\n") \
84
 
        or not len(line) > 4:
85
 
        raise MalformedHunkHeader("Does not start and end with @@.", line)
86
 
    try:
87
 
        (orig, mod) = line[3:-4].split(" ")
88
 
    except Exception, e:
89
 
        raise MalformedHunkHeader(str(e), line)
90
 
    if not orig.startswith('-') or not mod.startswith('+'):
91
 
        raise MalformedHunkHeader("Positions don't start with + or -.", line)
92
 
    try:
93
 
        (orig_pos, orig_range) = parse_range(orig[1:])
94
 
        (mod_pos, mod_range) = parse_range(mod[1:])
95
 
    except Exception, e:
96
 
        raise MalformedHunkHeader(str(e), line)
97
 
    if mod_range < 0 or orig_range < 0:
98
 
        raise MalformedHunkHeader("Hunk range is negative", line)
99
 
    return Hunk(orig_pos, orig_range, mod_pos, mod_range)
100
 
 
101
 
 
102
 
class HunkLine:
103
 
    def __init__(self, contents):
104
 
        self.contents = contents
105
 
 
106
 
    def get_str(self, leadchar):
107
 
        if self.contents == "\n" and leadchar == " " and False:
108
 
            return "\n"
109
 
        if not self.contents.endswith('\n'):
110
 
            terminator = '\n' + NO_NL
111
 
        else:
112
 
            terminator = ''
113
 
        return leadchar + self.contents + terminator
114
 
 
115
 
    def no_nl(self):
116
 
        assert self.contents.endswith('\n')
117
 
        self.contents = self.contents[:-1]
118
 
 
119
 
class ContextLine(HunkLine):
120
 
    def __init__(self, contents):
121
 
        HunkLine.__init__(self, contents)
122
 
 
123
 
    def __str__(self):
124
 
        return self.get_str(" ")
125
 
 
126
 
 
127
 
class InsertLine(HunkLine):
128
 
    def __init__(self, contents):
129
 
        HunkLine.__init__(self, contents)
130
 
 
131
 
    def __str__(self):
132
 
        return self.get_str("+")
133
 
 
134
 
 
135
 
class RemoveLine(HunkLine):
136
 
    def __init__(self, contents):
137
 
        HunkLine.__init__(self, contents)
138
 
 
139
 
    def __str__(self):
140
 
        return self.get_str("-")
141
 
 
142
 
NO_NL = '\\ No newline at end of file\n'
143
 
__pychecker__="no-returnvalues"
144
 
 
145
 
def parse_line(line):
146
 
    if line.startswith("\n"):
147
 
        return ContextLine(line)
148
 
    elif line.startswith(" "):
149
 
        return ContextLine(line[1:])
150
 
    elif line.startswith("+"):
151
 
        return InsertLine(line[1:])
152
 
    elif line.startswith("-"):
153
 
        return RemoveLine(line[1:])
154
 
    elif line == NO_NL:
155
 
        return NO_NL
156
 
    else:
157
 
        raise MalformedLine("Unknown line type", line)
158
 
__pychecker__=""
159
 
 
160
 
 
161
 
class Hunk:
162
 
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range):
163
 
        self.orig_pos = orig_pos
164
 
        self.orig_range = orig_range
165
 
        self.mod_pos = mod_pos
166
 
        self.mod_range = mod_range
167
 
        self.lines = []
168
 
 
169
 
    def get_header(self):
170
 
        return "@@ -%s +%s @@\n" % (self.range_str(self.orig_pos, 
171
 
                                                   self.orig_range),
172
 
                                    self.range_str(self.mod_pos, 
173
 
                                                   self.mod_range))
174
 
 
175
 
    def range_str(self, pos, range):
176
 
        """Return a file range, special-casing for 1-line files.
177
 
 
178
 
        :param pos: The position in the file
179
 
        :type pos: int
180
 
        :range: The range in the file
181
 
        :type range: int
182
 
        :return: a string in the format 1,4 except when range == pos == 1
183
 
        """
184
 
        if range == 1:
185
 
            return "%i" % pos
186
 
        else:
187
 
            return "%i,%i" % (pos, range)
188
 
 
189
 
    def __str__(self):
190
 
        lines = [self.get_header()]
191
 
        for line in self.lines:
192
 
            lines.append(str(line))
193
 
        return "".join(lines)
194
 
 
195
 
    def shift_to_mod(self, pos):
196
 
        if pos < self.orig_pos-1:
197
 
            return 0
198
 
        elif pos > self.orig_pos+self.orig_range:
199
 
            return self.mod_range - self.orig_range
200
 
        else:
201
 
            return self.shift_to_mod_lines(pos)
202
 
 
203
 
    def shift_to_mod_lines(self, pos):
204
 
        assert (pos >= self.orig_pos-1 and pos <= self.orig_pos+self.orig_range)
205
 
        position = self.orig_pos-1
206
 
        shift = 0
207
 
        for line in self.lines:
208
 
            if isinstance(line, InsertLine):
209
 
                shift += 1
210
 
            elif isinstance(line, RemoveLine):
211
 
                if position == pos:
212
 
                    return None
213
 
                shift -= 1
214
 
                position += 1
215
 
            elif isinstance(line, ContextLine):
216
 
                position += 1
217
 
            if position > pos:
218
 
                break
219
 
        return shift
220
 
 
221
 
def iter_hunks(iter_lines):
222
 
    hunk = None
223
 
    for line in iter_lines:
224
 
        if line == NO_NL:
225
 
            hunk.lines[-1].no_nl()
226
 
            yield hunk
227
 
            hunk = None
228
 
            continue
229
 
        elif line == "\n":
230
 
            if hunk is not None:
231
 
                yield hunk
232
 
                hunk = None
233
 
            continue
234
 
        if hunk is not None:
235
 
            yield hunk
236
 
        hunk = hunk_from_header(line)
237
 
        orig_size = 0
238
 
        mod_size = 0
239
 
        while orig_size < hunk.orig_range or mod_size < hunk.mod_range:
240
 
            hunk_line = parse_line(iter_lines.next())
241
 
            if hunk_line is NO_NL:
242
 
                hunk.lines[-1].no_nl()
243
 
            else:
244
 
                hunk.lines.append(hunk_line)
245
 
            if isinstance(hunk_line, (RemoveLine, ContextLine)):
246
 
                orig_size += 1
247
 
            if isinstance(hunk_line, (InsertLine, ContextLine)):
248
 
                mod_size += 1
249
 
    if hunk is not None:
250
 
        yield hunk
251
 
 
252
 
class Patch:
253
 
    def __init__(self, oldname, newname):
254
 
        self.oldname = oldname
255
 
        self.newname = newname
256
 
        self.hunks = []
257
 
 
258
 
    def __str__(self):
259
 
        ret = self.get_header() 
260
 
        ret += "".join([str(h) for h in self.hunks])
261
 
        return ret
262
 
 
263
 
    def get_header(self):
264
 
        return "--- %s\n+++ %s\n" % (self.oldname, self.newname)
265
 
 
266
 
    def stats_str(self):
267
 
        """Return a string of patch statistics"""
268
 
        removes = 0
269
 
        inserts = 0
270
 
        for hunk in self.hunks:
271
 
            for line in hunk.lines:
272
 
                if isinstance(line, InsertLine):
273
 
                     inserts+=1;
274
 
                elif isinstance(line, RemoveLine):
275
 
                     removes+=1;
276
 
        return "%i inserts, %i removes in %i hunks" % \
277
 
            (inserts, removes, len(self.hunks))
278
 
 
279
 
    def pos_in_mod(self, position):
280
 
        newpos = position
281
 
        for hunk in self.hunks:
282
 
            shift = hunk.shift_to_mod(position)
283
 
            if shift is None:
284
 
                return None
285
 
            newpos += shift
286
 
        return newpos
287
 
            
288
 
    def iter_inserted(self):
289
 
        """Iteraties through inserted lines
290
 
        
291
 
        :return: Pair of line number, line
292
 
        :rtype: iterator of (int, InsertLine)
293
 
        """
294
 
        for hunk in self.hunks:
295
 
            pos = hunk.mod_pos - 1;
296
 
            for line in hunk.lines:
297
 
                if isinstance(line, InsertLine):
298
 
                    yield (pos, line)
299
 
                    pos += 1
300
 
                if isinstance(line, ContextLine):
301
 
                    pos += 1
302
 
 
303
 
def parse_patch(iter_lines):
304
 
    (orig_name, mod_name) = get_patch_names(iter_lines)
305
 
    patch = Patch(orig_name, mod_name)
306
 
    for hunk in iter_hunks(iter_lines):
307
 
        patch.hunks.append(hunk)
308
 
    return patch
309
 
 
310
 
 
311
 
def iter_file_patch(iter_lines):
312
 
    saved_lines = []
313
 
    for line in iter_lines:
314
 
        if line.startswith('*** '):
315
 
            continue
316
 
        elif line.startswith('--- '):
317
 
            if len(saved_lines) > 0:
318
 
                yield saved_lines
319
 
            saved_lines = []
320
 
        saved_lines.append(line)
321
 
    if len(saved_lines) > 0:
322
 
        yield saved_lines
323
 
 
324
 
 
325
 
def parse_patches(iter_lines):
326
 
    return [parse_patch(f.__iter__()) for f in iter_file_patch(iter_lines)]
327
 
 
328
 
 
329
 
def difference_index(atext, btext):
330
 
    """Find the indext of the first character that differs betweeen two texts
331
 
 
332
 
    :param atext: The first text
333
 
    :type atext: str
334
 
    :param btext: The second text
335
 
    :type str: str
336
 
    :return: The index, or None if there are no differences within the range
337
 
    :rtype: int or NoneType
338
 
    """
339
 
    length = len(atext)
340
 
    if len(btext) < length:
341
 
        length = len(btext)
342
 
    for i in range(length):
343
 
        if atext[i] != btext[i]:
344
 
            return i;
345
 
    return None
346
 
 
347
 
class PatchConflict(Exception):
348
 
    def __init__(self, line_no, orig_line, patch_line):
349
 
        orig = orig_line.rstrip('\n')
350
 
        patch = str(patch_line).rstrip('\n')
351
 
        msg = 'Text contents mismatch at line %d.  Original has "%s",'\
352
 
            ' but patch says it should be "%s"' % (line_no, orig, patch)
353
 
        Exception.__init__(self, msg)
354
 
 
355
 
 
356
 
def iter_patched(orig_lines, patch_lines):
357
 
    """Iterate through a series of lines with a patch applied.
358
 
    This handles a single file, and does exact, not fuzzy patching.
359
 
    """
360
 
    if orig_lines is not None:
361
 
        orig_lines = orig_lines.__iter__()
362
 
    seen_patch = []
363
 
    patch_lines = patch_lines.__iter__()
364
 
    get_patch_names(patch_lines)
365
 
    line_no = 1
366
 
    for hunk in iter_hunks(patch_lines):
367
 
        while line_no < hunk.orig_pos:
368
 
            orig_line = orig_lines.next()
369
 
            yield orig_line
370
 
            line_no += 1
371
 
        for hunk_line in hunk.lines:
372
 
            seen_patch.append(str(hunk_line))
373
 
            if isinstance(hunk_line, InsertLine):
374
 
                yield hunk_line.contents
375
 
            elif isinstance(hunk_line, (ContextLine, RemoveLine)):
376
 
                orig_line = orig_lines.next()
377
 
                if orig_line != hunk_line.contents:
378
 
                    raise PatchConflict(line_no, orig_line, "".join(seen_patch))
379
 
                if isinstance(hunk_line, ContextLine):
380
 
                    yield orig_line
381
 
                else:
382
 
                    assert isinstance(hunk_line, RemoveLine)
383
 
                line_no += 1
384
 
                    
385
 
import unittest
386
 
import os.path
387
 
class PatchesTester(unittest.TestCase):
388
 
    def datafile(self, filename):
389
 
        data_path = os.path.join(os.path.dirname(__file__), "testdata", 
390
 
                                 filename)
391
 
        return file(data_path, "rb")
392
 
 
393
 
    def testValidPatchHeader(self):
394
 
        """Parse a valid patch header"""
395
 
        lines = "--- orig/commands.py\n+++ mod/dommands.py\n".split('\n')
396
 
        (orig, mod) = get_patch_names(lines.__iter__())
397
 
        assert(orig == "orig/commands.py")
398
 
        assert(mod == "mod/dommands.py")
399
 
 
400
 
    def testInvalidPatchHeader(self):
401
 
        """Parse an invalid patch header"""
402
 
        lines = "-- orig/commands.py\n+++ mod/dommands.py".split('\n')
403
 
        self.assertRaises(MalformedPatchHeader, get_patch_names,
404
 
                          lines.__iter__())
405
 
 
406
 
    def testValidHunkHeader(self):
407
 
        """Parse a valid hunk header"""
408
 
        header = "@@ -34,11 +50,6 @@\n"
409
 
        hunk = hunk_from_header(header);
410
 
        assert (hunk.orig_pos == 34)
411
 
        assert (hunk.orig_range == 11)
412
 
        assert (hunk.mod_pos == 50)
413
 
        assert (hunk.mod_range == 6)
414
 
        assert (str(hunk) == header)
415
 
 
416
 
    def testValidHunkHeader2(self):
417
 
        """Parse a tricky, valid hunk header"""
418
 
        header = "@@ -1 +0,0 @@\n"
419
 
        hunk = hunk_from_header(header);
420
 
        assert (hunk.orig_pos == 1)
421
 
        assert (hunk.orig_range == 1)
422
 
        assert (hunk.mod_pos == 0)
423
 
        assert (hunk.mod_range == 0)
424
 
        assert (str(hunk) == header)
425
 
 
426
 
    def makeMalformed(self, header):
427
 
        self.assertRaises(MalformedHunkHeader, hunk_from_header, header)
428
 
 
429
 
    def testInvalidHeader(self):
430
 
        """Parse an invalid hunk header"""
431
 
        self.makeMalformed(" -34,11 +50,6 \n")
432
 
        self.makeMalformed("@@ +50,6 -34,11 @@\n")
433
 
        self.makeMalformed("@@ -34,11 +50,6 @@")
434
 
        self.makeMalformed("@@ -34.5,11 +50,6 @@\n")
435
 
        self.makeMalformed("@@-34,11 +50,6@@\n")
436
 
        self.makeMalformed("@@ 34,11 50,6 @@\n")
437
 
        self.makeMalformed("@@ -34,11 @@\n")
438
 
        self.makeMalformed("@@ -34,11 +50,6.5 @@\n")
439
 
        self.makeMalformed("@@ -34,11 +50,-6 @@\n")
440
 
 
441
 
    def lineThing(self,text, type):
442
 
        line = parse_line(text)
443
 
        assert(isinstance(line, type))
444
 
        assert(str(line)==text)
445
 
 
446
 
    def makeMalformedLine(self, text):
447
 
        self.assertRaises(MalformedLine, parse_line, text)
448
 
 
449
 
    def testValidLine(self):
450
 
        """Parse a valid hunk line"""
451
 
        self.lineThing(" hello\n", ContextLine)
452
 
        self.lineThing("+hello\n", InsertLine)
453
 
        self.lineThing("-hello\n", RemoveLine)
454
 
    
455
 
    def testMalformedLine(self):
456
 
        """Parse invalid valid hunk lines"""
457
 
        self.makeMalformedLine("hello\n")
458
 
    
459
 
    def compare_parsed(self, patchtext):
460
 
        lines = patchtext.splitlines(True)
461
 
        patch = parse_patch(lines.__iter__())
462
 
        pstr = str(patch)
463
 
        i = difference_index(patchtext, pstr)
464
 
        if i is not None:
465
 
            print "%i: \"%s\" != \"%s\"" % (i, patchtext[i], pstr[i])
466
 
        self.assertEqual (patchtext, str(patch))
467
 
 
468
 
    def testAll(self):
469
 
        """Test parsing a whole patch"""
470
 
        patchtext = """--- orig/commands.py
471
 
+++ mod/commands.py
472
 
@@ -1337,7 +1337,8 @@
473
 
 
474
 
     def set_title(self, command=None):
475
 
         try:
476
 
-            version = self.tree.tree_version.nonarch
477
 
+            version = pylon.alias_or_version(self.tree.tree_version, self.tree,
478
 
+                                             full=False)
479
 
         except:
480
 
             version = "[no version]"
481
 
         if command is None:
482
 
@@ -1983,7 +1984,11 @@
483
 
                                          version)
484
 
         if len(new_merges) > 0:
485
 
             if cmdutil.prompt("Log for merge"):
486
 
-                mergestuff = cmdutil.log_for_merge(tree, comp_version)
487
 
+                if cmdutil.prompt("changelog for merge"):
488
 
+                    mergestuff = "Patches applied:\\n"
489
 
+                    mergestuff += pylon.changelog_for_merge(new_merges)
490
 
+                else:
491
 
+                    mergestuff = cmdutil.log_for_merge(tree, comp_version)
492
 
                 log.description += mergestuff
493
 
         log.save()
494
 
     try:
495
 
"""
496
 
        self.compare_parsed(patchtext)
497
 
 
498
 
    def testInit(self):
499
 
        """Handle patches missing half the position, range tuple"""
500
 
        patchtext = \
501
 
"""--- orig/__init__.py
502
 
+++ mod/__init__.py
503
 
@@ -1 +1,2 @@
504
 
 __docformat__ = "restructuredtext en"
505
 
+__doc__ = An alternate Arch commandline interface
506
 
"""
507
 
        self.compare_parsed(patchtext)
508
 
        
509
 
 
510
 
 
511
 
    def testLineLookup(self):
512
 
        import sys
513
 
        """Make sure we can accurately look up mod line from orig"""
514
 
        patch = parse_patch(self.datafile("diff"))
515
 
        orig = list(self.datafile("orig"))
516
 
        mod = list(self.datafile("mod"))
517
 
        removals = []
518
 
        for i in range(len(orig)):
519
 
            mod_pos = patch.pos_in_mod(i)
520
 
            if mod_pos is None:
521
 
                removals.append(orig[i])
522
 
                continue
523
 
            assert(mod[mod_pos]==orig[i])
524
 
        rem_iter = removals.__iter__()
525
 
        for hunk in patch.hunks:
526
 
            for line in hunk.lines:
527
 
                if isinstance(line, RemoveLine):
528
 
                    next = rem_iter.next()
529
 
                    if line.contents != next:
530
 
                        sys.stdout.write(" orig:%spatch:%s" % (next,
531
 
                                         line.contents))
532
 
                    assert(line.contents == next)
533
 
        self.assertRaises(StopIteration, rem_iter.next)
534
 
 
535
 
    def testFirstLineRenumber(self):
536
 
        """Make sure we handle lines at the beginning of the hunk"""
537
 
        patch = parse_patch(self.datafile("insert_top.patch"))
538
 
        assert (patch.pos_in_mod(0)==1)
539
 
 
540
 
def test():
541
 
    patchesTestSuite = unittest.makeSuite(PatchesTester,'test')
542
 
    runner = unittest.TextTestRunner(verbosity=0)
543
 
    return runner.run(patchesTestSuite)
544
 
    
545
 
 
546
 
if __name__ == "__main__":
547
 
    test()
548
 
# arch-tag: d1541a25-eac5-4de9-a476-08a7cecd5683