~abentley/bzrtools/bzrtools.dev

« back to all changes in this revision

Viewing changes to patches.py

  • Committer: Aaron Bentley
  • Date: 2005-06-17 14:07:59 UTC
  • Revision ID: abentley@panoramicfeedback.com-20050617140759-4dffb87b9cc1c7ef
Pulled all annotation code into a separate files

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
import sys
 
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%s" % (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%s" % (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
        return leadchar + self.contents
 
110
 
 
111
class ContextLine(HunkLine):
 
112
    def __init__(self, contents):
 
113
        HunkLine.__init__(self, contents)
 
114
 
 
115
    def __str__(self):
 
116
        return self.get_str(" ")
 
117
 
 
118
 
 
119
class InsertLine(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 RemoveLine(HunkLine):
 
128
    def __init__(self, contents):
 
129
        HunkLine.__init__(self, contents)
 
130
 
 
131
    def __str__(self):
 
132
        return self.get_str("-")
 
133
 
 
134
__pychecker__="no-returnvalues"
 
135
def parse_line(line):
 
136
    if line.startswith("\n"):
 
137
        return ContextLine(line)
 
138
    elif line.startswith(" "):
 
139
        return ContextLine(line[1:])
 
140
    elif line.startswith("+"):
 
141
        return InsertLine(line[1:])
 
142
    elif line.startswith("-"):
 
143
        return RemoveLine(line[1:])
 
144
    else:
 
145
        raise MalformedLine("Unknown line type", line)
 
146
__pychecker__=""
 
147
 
 
148
 
 
149
class Hunk:
 
150
    def __init__(self, orig_pos, orig_range, mod_pos, mod_range):
 
151
        self.orig_pos = orig_pos
 
152
        self.orig_range = orig_range
 
153
        self.mod_pos = mod_pos
 
154
        self.mod_range = mod_range
 
155
        self.lines = []
 
156
 
 
157
    def get_header(self):
 
158
        return "@@ -%s +%s @@\n" % (self.range_str(self.orig_pos, 
 
159
                                                   self.orig_range),
 
160
                                    self.range_str(self.mod_pos, 
 
161
                                                   self.mod_range))
 
162
 
 
163
    def range_str(self, pos, range):
 
164
        """Return a file range, special-casing for 1-line files.
 
165
 
 
166
        :param pos: The position in the file
 
167
        :type pos: int
 
168
        :range: The range in the file
 
169
        :type range: int
 
170
        :return: a string in the format 1,4 except when range == pos == 1
 
171
        """
 
172
        if range == 1:
 
173
            return "%i" % pos
 
174
        else:
 
175
            return "%i,%i" % (pos, range)
 
176
 
 
177
    def __str__(self):
 
178
        lines = [self.get_header()]
 
179
        for line in self.lines:
 
180
            lines.append(str(line))
 
181
        return "".join(lines)
 
182
 
 
183
    def shift_to_mod(self, pos):
 
184
        if pos < self.orig_pos-1:
 
185
            return 0
 
186
        elif pos > self.orig_pos+self.orig_range:
 
187
            return self.mod_range - self.orig_range
 
188
        else:
 
189
            return self.shift_to_mod_lines(pos)
 
190
 
 
191
    def shift_to_mod_lines(self, pos):
 
192
        assert (pos >= self.orig_pos-1 and pos <= self.orig_pos+self.orig_range)
 
193
        position = self.orig_pos-1
 
194
        shift = 0
 
195
        for line in self.lines:
 
196
            if isinstance(line, InsertLine):
 
197
                shift += 1
 
198
            elif isinstance(line, RemoveLine):
 
199
                if position == pos:
 
200
                    return None
 
201
                shift -= 1
 
202
                position += 1
 
203
            elif isinstance(line, ContextLine):
 
204
                position += 1
 
205
            if position > pos:
 
206
                break
 
207
        return shift
 
208
 
 
209
def iter_hunks(iter_lines):
 
210
    hunk = None
 
211
    for line in iter_lines:
 
212
        if line.startswith("@@"):
 
213
            if hunk is not None:
 
214
                yield hunk
 
215
            hunk = hunk_from_header(line)
 
216
        else:
 
217
            hunk.lines.append(parse_line(line))
 
218
 
 
219
    if hunk is not None:
 
220
        yield hunk
 
221
 
 
222
class Patch:
 
223
    def __init__(self, oldname, newname):
 
224
        self.oldname = oldname
 
225
        self.newname = newname
 
226
        self.hunks = []
 
227
 
 
228
    def __str__(self):
 
229
        ret =  "--- %s\n+++ %s\n" % (self.oldname, self.newname) 
 
230
        ret += "".join([str(h) for h in self.hunks])
 
231
        return ret
 
232
 
 
233
    def stats_str(self):
 
234
        """Return a string of patch statistics"""
 
235
        removes = 0
 
236
        inserts = 0
 
237
        for hunk in self.hunks:
 
238
            for line in hunk.lines:
 
239
                if isinstance(line, InsertLine):
 
240
                     inserts+=1;
 
241
                elif isinstance(line, RemoveLine):
 
242
                     removes+=1;
 
243
        return "%i inserts, %i removes in %i hunks" % \
 
244
            (inserts, removes, len(self.hunks))
 
245
 
 
246
    def pos_in_mod(self, position):
 
247
        newpos = position
 
248
        for hunk in self.hunks:
 
249
            shift = hunk.shift_to_mod(position)
 
250
            if shift is None:
 
251
                return None
 
252
            newpos += shift
 
253
        return newpos
 
254
            
 
255
    def iter_inserted(self):
 
256
        """Iteraties through inserted lines
 
257
        
 
258
        :return: Pair of line number, line
 
259
        :rtype: iterator of (int, InsertLine)
 
260
        """
 
261
        for hunk in self.hunks:
 
262
            pos = hunk.mod_pos - 1;
 
263
            for line in hunk.lines:
 
264
                if isinstance(line, InsertLine):
 
265
                    yield (pos, line)
 
266
                    pos += 1
 
267
                if isinstance(line, ContextLine):
 
268
                    pos += 1
 
269
 
 
270
def parse_patch(iter_lines):
 
271
    (orig_name, mod_name) = get_patch_names(iter_lines)
 
272
    patch = Patch(orig_name, mod_name)
 
273
    for hunk in iter_hunks(iter_lines):
 
274
        patch.hunks.append(hunk)
 
275
    return patch
 
276
 
 
277
 
 
278
def iter_file_patch(iter_lines):
 
279
    saved_lines = []
 
280
    for line in iter_lines:
 
281
        if line.startswith('*** '):
 
282
            continue
 
283
        elif line.startswith('--- '):
 
284
            if len(saved_lines) > 0:
 
285
                yield saved_lines
 
286
            saved_lines = []
 
287
        saved_lines.append(line)
 
288
    if len(saved_lines) > 0:
 
289
        yield saved_lines
 
290
 
 
291
 
 
292
def parse_patches(iter_lines):
 
293
    return [parse_patch(f.__iter__()) for f in iter_file_patch(iter_lines)]
 
294
 
 
295
 
 
296
def difference_index(atext, btext):
 
297
    """Find the indext of the first character that differs betweeen two texts
 
298
 
 
299
    :param atext: The first text
 
300
    :type atext: str
 
301
    :param btext: The second text
 
302
    :type str: str
 
303
    :return: The index, or None if there are no differences within the range
 
304
    :rtype: int or NoneType
 
305
    """
 
306
    length = len(atext)
 
307
    if len(btext) < length:
 
308
        length = len(btext)
 
309
    for i in range(length):
 
310
        if atext[i] != btext[i]:
 
311
            return i;
 
312
    return None
 
313
 
 
314
 
 
315
def test():
 
316
    import unittest
 
317
    class PatchesTester(unittest.TestCase):
 
318
        def testValidPatchHeader(self):
 
319
            """Parse a valid patch header"""
 
320
            lines = "--- orig/commands.py\n+++ mod/dommands.py\n".split('\n')
 
321
            (orig, mod) = get_patch_names(lines.__iter__())
 
322
            assert(orig == "orig/commands.py")
 
323
            assert(mod == "mod/dommands.py")
 
324
 
 
325
        def testInvalidPatchHeader(self):
 
326
            """Parse an invalid patch header"""
 
327
            lines = "-- orig/commands.py\n+++ mod/dommands.py".split('\n')
 
328
            self.assertRaises(MalformedPatchHeader, get_patch_names,
 
329
                              lines.__iter__())
 
330
 
 
331
        def testValidHunkHeader(self):
 
332
            """Parse a valid hunk header"""
 
333
            header = "@@ -34,11 +50,6 @@\n"
 
334
            hunk = hunk_from_header(header);
 
335
            assert (hunk.orig_pos == 34)
 
336
            assert (hunk.orig_range == 11)
 
337
            assert (hunk.mod_pos == 50)
 
338
            assert (hunk.mod_range == 6)
 
339
            assert (str(hunk) == header)
 
340
 
 
341
        def testValidHunkHeader2(self):
 
342
            """Parse a tricky, valid hunk header"""
 
343
            header = "@@ -1 +0,0 @@\n"
 
344
            hunk = hunk_from_header(header);
 
345
            assert (hunk.orig_pos == 1)
 
346
            assert (hunk.orig_range == 1)
 
347
            assert (hunk.mod_pos == 0)
 
348
            assert (hunk.mod_range == 0)
 
349
            assert (str(hunk) == header)
 
350
 
 
351
        def makeMalformed(self, header):
 
352
            self.assertRaises(MalformedHunkHeader, hunk_from_header, header)
 
353
 
 
354
        def testInvalidHeader(self):
 
355
            """Parse an invalid hunk header"""
 
356
            self.makeMalformed(" -34,11 +50,6 \n")
 
357
            self.makeMalformed("@@ +50,6 -34,11 @@\n")
 
358
            self.makeMalformed("@@ -34,11 +50,6 @@")
 
359
            self.makeMalformed("@@ -34.5,11 +50,6 @@\n")
 
360
            self.makeMalformed("@@-34,11 +50,6@@\n")
 
361
            self.makeMalformed("@@ 34,11 50,6 @@\n")
 
362
            self.makeMalformed("@@ -34,11 @@\n")
 
363
            self.makeMalformed("@@ -34,11 +50,6.5 @@\n")
 
364
            self.makeMalformed("@@ -34,11 +50,-6 @@\n")
 
365
 
 
366
        def lineThing(self,text, type):
 
367
            line = parse_line(text)
 
368
            assert(isinstance(line, type))
 
369
            assert(str(line)==text)
 
370
 
 
371
        def makeMalformedLine(self, text):
 
372
            self.assertRaises(MalformedLine, parse_line, text)
 
373
 
 
374
        def testValidLine(self):
 
375
            """Parse a valid hunk line"""
 
376
            self.lineThing(" hello\n", ContextLine)
 
377
            self.lineThing("+hello\n", InsertLine)
 
378
            self.lineThing("-hello\n", RemoveLine)
 
379
        
 
380
        def testMalformedLine(self):
 
381
            """Parse invalid valid hunk lines"""
 
382
            self.makeMalformedLine("hello\n")
 
383
        
 
384
        def compare_parsed(self, patchtext):
 
385
            lines = patchtext.splitlines(True)
 
386
            patch = parse_patch(lines.__iter__())
 
387
            pstr = str(patch)
 
388
            i = difference_index(patchtext, pstr)
 
389
            if i is not None:
 
390
                print "%i: \"%s\" != \"%s\"" % (i, patchtext[i], pstr[i])
 
391
            assert (patchtext == str(patch))
 
392
 
 
393
        def testAll(self):
 
394
            """Test parsing a whole patch"""
 
395
            patchtext = """--- orig/commands.py
 
396
+++ mod/commands.py
 
397
@@ -1337,7 +1337,8 @@
 
398
 
 
399
     def set_title(self, command=None):
 
400
         try:
 
401
-            version = self.tree.tree_version.nonarch
 
402
+            version = pylon.alias_or_version(self.tree.tree_version, self.tree,
 
403
+                                             full=False)
 
404
         except:
 
405
             version = "[no version]"
 
406
         if command is None:
 
407
@@ -1983,7 +1984,11 @@
 
408
                                          version)
 
409
         if len(new_merges) > 0:
 
410
             if cmdutil.prompt("Log for merge"):
 
411
-                mergestuff = cmdutil.log_for_merge(tree, comp_version)
 
412
+                if cmdutil.prompt("changelog for merge"):
 
413
+                    mergestuff = "Patches applied:\\n"
 
414
+                    mergestuff += pylon.changelog_for_merge(new_merges)
 
415
+                else:
 
416
+                    mergestuff = cmdutil.log_for_merge(tree, comp_version)
 
417
                 log.description += mergestuff
 
418
         log.save()
 
419
     try:
 
420
"""
 
421
            self.compare_parsed(patchtext)
 
422
 
 
423
        def testInit(self):
 
424
            """Handle patches missing half the position, range tuple"""
 
425
            patchtext = \
 
426
"""--- orig/__init__.py
 
427
+++ mod/__init__.py
 
428
@@ -1 +1,2 @@
 
429
 __docformat__ = "restructuredtext en"
 
430
+__doc__ = An alternate Arch commandline interface"""
 
431
            self.compare_parsed(patchtext)
 
432
            
 
433
 
 
434
 
 
435
        def testLineLookup(self):
 
436
            """Make sure we can accurately look up mod line from orig"""
 
437
            patch = parse_patch(open("testdata/diff"))
 
438
            orig = list(open("testdata/orig"))
 
439
            mod = list(open("testdata/mod"))
 
440
            removals = []
 
441
            for i in range(len(orig)):
 
442
                mod_pos = patch.pos_in_mod(i)
 
443
                if mod_pos is None:
 
444
                    removals.append(orig[i])
 
445
                    continue
 
446
                assert(mod[mod_pos]==orig[i])
 
447
            rem_iter = removals.__iter__()
 
448
            for hunk in patch.hunks:
 
449
                for line in hunk.lines:
 
450
                    if isinstance(line, RemoveLine):
 
451
                        next = rem_iter.next()
 
452
                        if line.contents != next:
 
453
                            sys.stdout.write(" orig:%spatch:%s" % (next,
 
454
                                             line.contents))
 
455
                        assert(line.contents == next)
 
456
            self.assertRaises(StopIteration, rem_iter.next)
 
457
 
 
458
        def testFirstLineRenumber(self):
 
459
            """Make sure we handle lines at the beginning of the hunk"""
 
460
            patch = parse_patch(open("testdata/insert_top.patch"))
 
461
            assert (patch.pos_in_mod(0)==1)
 
462
    
 
463
            
 
464
    patchesTestSuite = unittest.makeSuite(PatchesTester,'test')
 
465
    runner = unittest.TextTestRunner(verbosity=0)
 
466
    return runner.run(patchesTestSuite)
 
467
    
 
468
 
 
469
if __name__ == "__main__":
 
470
    test()
 
471
# arch-tag: d1541a25-eac5-4de9-a476-08a7cecd5683