1
# Copyright (C) 2004, 2005 Aaron Bentley
2
# <aaron.bentley@utoronto.ca>
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.
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.
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
19
class PatchSyntax(Exception):
20
def __init__(self, msg):
21
Exception.__init__(self, msg)
24
class MalformedPatchHeader(PatchSyntax):
25
def __init__(self, desc, line):
28
msg = "Malformed patch header. %s\n%s" % (self.desc, self.line)
29
PatchSyntax.__init__(self, msg)
31
class MalformedHunkHeader(PatchSyntax):
32
def __init__(self, desc, line):
35
msg = "Malformed hunk header. %s\n%s" % (self.desc, self.line)
36
PatchSyntax.__init__(self, msg)
38
class MalformedLine(PatchSyntax):
39
def __init__(self, desc, line):
42
msg = "Malformed line. %s\n%s" % (self.desc, self.line)
43
PatchSyntax.__init__(self, msg)
45
def get_patch_names(iter_lines):
47
line = iter_lines.next()
48
if not line.startswith("--- "):
49
raise MalformedPatchHeader("No orig name", line)
51
orig_name = line[4:].rstrip("\n")
53
raise MalformedPatchHeader("No orig line", "")
55
line = iter_lines.next()
56
if not line.startswith("+++ "):
57
raise PatchSyntax("No mod name")
59
mod_name = line[4:].rstrip("\n")
61
raise MalformedPatchHeader("No mod line", "")
62
return (orig_name, mod_name)
64
def parse_range(textrange):
65
"""Parse a patch range, handling the "1" special-case
67
:param textrange: The text to parse
69
:return: the position and range, as a tuple
72
tmp = textrange.split(',')
83
def hunk_from_header(line):
84
if not line.startswith("@@") or not line.endswith("@@\n") \
86
raise MalformedHunkHeader("Does not start and end with @@.", line)
88
(orig, mod) = line[3:-4].split(" ")
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)
94
(orig_pos, orig_range) = parse_range(orig[1:])
95
(mod_pos, mod_range) = parse_range(mod[1:])
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)
104
def __init__(self, contents):
105
self.contents = contents
107
def get_str(self, leadchar):
108
if self.contents == "\n" and leadchar == " " and False:
110
return leadchar + self.contents
112
class ContextLine(HunkLine):
113
def __init__(self, contents):
114
HunkLine.__init__(self, contents)
117
return self.get_str(" ")
120
class InsertLine(HunkLine):
121
def __init__(self, contents):
122
HunkLine.__init__(self, contents)
125
return self.get_str("+")
128
class RemoveLine(HunkLine):
129
def __init__(self, contents):
130
HunkLine.__init__(self, contents)
133
return self.get_str("-")
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:])
146
raise MalformedLine("Unknown line type", line)
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
158
def get_header(self):
159
return "@@ -%s +%s @@\n" % (self.range_str(self.orig_pos,
161
self.range_str(self.mod_pos,
164
def range_str(self, pos, range):
165
"""Return a file range, special-casing for 1-line files.
167
:param pos: The position in the file
169
:range: The range in the file
171
:return: a string in the format 1,4 except when range == pos == 1
176
return "%i,%i" % (pos, range)
179
lines = [self.get_header()]
180
for line in self.lines:
181
lines.append(str(line))
182
return "".join(lines)
184
def shift_to_mod(self, pos):
185
if pos < self.orig_pos-1:
187
elif pos > self.orig_pos+self.orig_range:
188
return self.mod_range - self.orig_range
190
return self.shift_to_mod_lines(pos)
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
196
for line in self.lines:
197
if isinstance(line, InsertLine):
199
elif isinstance(line, RemoveLine):
204
elif isinstance(line, ContextLine):
210
def iter_hunks(iter_lines):
212
for line in iter_lines:
213
if line.startswith("@@"):
216
hunk = hunk_from_header(line)
218
hunk.lines.append(parse_line(line))
224
def __init__(self, oldname, newname):
225
self.oldname = oldname
226
self.newname = newname
230
ret = "--- %s\n+++ %s\n" % (self.oldname, self.newname)
231
ret += "".join([str(h) for h in self.hunks])
235
"""Return a string of patch statistics"""
238
for hunk in self.hunks:
239
for line in hunk.lines:
240
if isinstance(line, InsertLine):
242
elif isinstance(line, RemoveLine):
244
return "%i inserts, %i removes in %i hunks" % \
245
(inserts, removes, len(self.hunks))
247
def pos_in_mod(self, position):
249
for hunk in self.hunks:
250
shift = hunk.shift_to_mod(position)
256
def iter_inserted(self):
257
"""Iteraties through inserted lines
259
:return: Pair of line number, line
260
:rtype: iterator of (int, InsertLine)
262
for hunk in self.hunks:
263
pos = hunk.mod_pos - 1;
264
for line in hunk.lines:
265
if isinstance(line, InsertLine):
268
if isinstance(line, ContextLine):
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)
280
"""A line associated with the log that produced it"""
281
def __init__(self, text, log=None):
285
class CantGetRevisionData(Exception):
286
def __init__(self, revision):
287
Exception.__init__(self, "Can't get data for revision %s" % revision)
289
def annotate_file2(file_lines, anno_iter):
290
for result in iter_annotate_file(file_lines, anno_iter):
295
def iter_annotate_file(file_lines, anno_iter):
296
lines = [AnnotateLine(f) for f in file_lines]
299
for result in anno_iter:
300
if isinstance(result, progress.Progress):
303
log, iter_inserted, patch = result
304
for (num, line) in iter_inserted:
307
for cur_patch in patches:
308
num = cur_patch.pos_in_mod(num)
312
if num >= len(lines):
314
if num is not None and lines[num].log is None:
316
patches=[patch]+patches
317
except CantGetRevisionData:
322
def difference_index(atext, btext):
323
"""Find the indext of the first character that differs betweeen two texts
325
:param atext: The first text
327
:param btext: The second text
329
:return: The index, or None if there are no differences within the range
330
:rtype: int or NoneType
333
if len(btext) < length:
335
for i in range(length):
336
if atext[i] != btext[i]:
343
class PatchesTester(unittest.TestCase):
344
def testValidPatchHeader(self):
345
"""Parse a valid patch header"""
346
lines = "--- orig/commands.py\n+++ mod/dommands.py\n".split('\n')
347
(orig, mod) = get_patch_names(lines.__iter__())
348
assert(orig == "orig/commands.py")
349
assert(mod == "mod/dommands.py")
351
def testInvalidPatchHeader(self):
352
"""Parse an invalid patch header"""
353
lines = "-- orig/commands.py\n+++ mod/dommands.py".split('\n')
354
self.assertRaises(MalformedPatchHeader, get_patch_names,
357
def testValidHunkHeader(self):
358
"""Parse a valid hunk header"""
359
header = "@@ -34,11 +50,6 @@\n"
360
hunk = hunk_from_header(header);
361
assert (hunk.orig_pos == 34)
362
assert (hunk.orig_range == 11)
363
assert (hunk.mod_pos == 50)
364
assert (hunk.mod_range == 6)
365
assert (str(hunk) == header)
367
def testValidHunkHeader2(self):
368
"""Parse a tricky, valid hunk header"""
369
header = "@@ -1 +0,0 @@\n"
370
hunk = hunk_from_header(header);
371
assert (hunk.orig_pos == 1)
372
assert (hunk.orig_range == 1)
373
assert (hunk.mod_pos == 0)
374
assert (hunk.mod_range == 0)
375
assert (str(hunk) == header)
377
def makeMalformed(self, header):
378
self.assertRaises(MalformedHunkHeader, hunk_from_header, header)
380
def testInvalidHeader(self):
381
"""Parse an invalid hunk header"""
382
self.makeMalformed(" -34,11 +50,6 \n")
383
self.makeMalformed("@@ +50,6 -34,11 @@\n")
384
self.makeMalformed("@@ -34,11 +50,6 @@")
385
self.makeMalformed("@@ -34.5,11 +50,6 @@\n")
386
self.makeMalformed("@@-34,11 +50,6@@\n")
387
self.makeMalformed("@@ 34,11 50,6 @@\n")
388
self.makeMalformed("@@ -34,11 @@\n")
389
self.makeMalformed("@@ -34,11 +50,6.5 @@\n")
390
self.makeMalformed("@@ -34,11 +50,-6 @@\n")
392
def lineThing(self,text, type):
393
line = parse_line(text)
394
assert(isinstance(line, type))
395
assert(str(line)==text)
397
def makeMalformedLine(self, text):
398
self.assertRaises(MalformedLine, parse_line, text)
400
def testValidLine(self):
401
"""Parse a valid hunk line"""
402
self.lineThing(" hello\n", ContextLine)
403
self.lineThing("+hello\n", InsertLine)
404
self.lineThing("-hello\n", RemoveLine)
406
def testMalformedLine(self):
407
"""Parse invalid valid hunk lines"""
408
self.makeMalformedLine("hello\n")
410
def compare_parsed(self, patchtext):
411
lines = patchtext.splitlines(True)
412
patch = parse_patch(lines.__iter__())
414
i = difference_index(patchtext, pstr)
416
print "%i: \"%s\" != \"%s\"" % (i, patchtext[i], pstr[i])
417
assert (patchtext == str(patch))
420
"""Test parsing a whole patch"""
421
patchtext = """--- orig/commands.py
423
@@ -1337,7 +1337,8 @@
425
def set_title(self, command=None):
427
- version = self.tree.tree_version.nonarch
428
+ version = pylon.alias_or_version(self.tree.tree_version, self.tree,
431
version = "[no version]"
433
@@ -1983,7 +1984,11 @@
435
if len(new_merges) > 0:
436
if cmdutil.prompt("Log for merge"):
437
- mergestuff = cmdutil.log_for_merge(tree, comp_version)
438
+ if cmdutil.prompt("changelog for merge"):
439
+ mergestuff = "Patches applied:\\n"
440
+ mergestuff += pylon.changelog_for_merge(new_merges)
442
+ mergestuff = cmdutil.log_for_merge(tree, comp_version)
443
log.description += mergestuff
447
self.compare_parsed(patchtext)
450
"""Handle patches missing half the position, range tuple"""
452
"""--- orig/__init__.py
455
__docformat__ = "restructuredtext en"
456
+__doc__ = An alternate Arch commandline interface"""
457
self.compare_parsed(patchtext)
461
def testLineLookup(self):
462
"""Make sure we can accurately look up mod line from orig"""
463
patch = parse_patch(open("testdata/diff"))
464
orig = list(open("testdata/orig"))
465
mod = list(open("testdata/mod"))
467
for i in range(len(orig)):
468
mod_pos = patch.pos_in_mod(i)
470
removals.append(orig[i])
472
assert(mod[mod_pos]==orig[i])
473
rem_iter = removals.__iter__()
474
for hunk in patch.hunks:
475
for line in hunk.lines:
476
if isinstance(line, RemoveLine):
477
next = rem_iter.next()
478
if line.contents != next:
479
sys.stdout.write(" orig:%spatch:%s" % (next,
481
assert(line.contents == next)
482
self.assertRaises(StopIteration, rem_iter.next)
484
def testFirstLineRenumber(self):
485
"""Make sure we handle lines at the beginning of the hunk"""
486
patch = parse_patch(open("testdata/insert_top.patch"))
487
assert (patch.pos_in_mod(0)==1)
490
patchesTestSuite = unittest.makeSuite(PatchesTester,'test')
491
runner = unittest.TextTestRunner(verbosity=0)
492
return runner.run(patchesTestSuite)
495
if __name__ == "__main__":
497
# arch-tag: d1541a25-eac5-4de9-a476-08a7cecd5683