~abentley/bzrtools/bzrtools.dev

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