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)
279
def iter_file_patch(iter_lines):
281
for line in iter_lines:
282
if line.startswith('*** '):
284
elif line.startswith('--- '):
285
if len(saved_lines) > 0:
288
saved_lines.append(line)
289
if len(saved_lines) > 0:
293
def parse_patches(iter_lines):
294
return [parse_patch(f.__iter__()) for f in iter_file_patch(iter_lines)]
298
"""A line associated with the log that produced it"""
299
def __init__(self, text, log=None):
303
class CantGetRevisionData(Exception):
304
def __init__(self, revision):
305
Exception.__init__(self, "Can't get data for revision %s" % revision)
307
def annotate_file2(file_lines, anno_iter):
308
for result in iter_annotate_file(file_lines, anno_iter):
313
def iter_annotate_file(file_lines, anno_iter):
314
lines = [AnnotateLine(f) for f in file_lines]
317
for result in anno_iter:
318
if isinstance(result, progress.Progress):
321
log, iter_inserted, patch = result
322
for (num, line) in iter_inserted:
325
for cur_patch in patches:
326
num = cur_patch.pos_in_mod(num)
330
if num >= len(lines):
332
if num is not None and lines[num].log is None:
334
patches=[patch]+patches
335
except CantGetRevisionData:
340
def difference_index(atext, btext):
341
"""Find the indext of the first character that differs betweeen two texts
343
:param atext: The first text
345
:param btext: The second text
347
:return: The index, or None if there are no differences within the range
348
:rtype: int or NoneType
351
if len(btext) < length:
353
for i in range(length):
354
if atext[i] != btext[i]:
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")
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,
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)
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)
395
def makeMalformed(self, header):
396
self.assertRaises(MalformedHunkHeader, hunk_from_header, header)
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")
410
def lineThing(self,text, type):
411
line = parse_line(text)
412
assert(isinstance(line, type))
413
assert(str(line)==text)
415
def makeMalformedLine(self, text):
416
self.assertRaises(MalformedLine, parse_line, text)
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)
424
def testMalformedLine(self):
425
"""Parse invalid valid hunk lines"""
426
self.makeMalformedLine("hello\n")
428
def compare_parsed(self, patchtext):
429
lines = patchtext.splitlines(True)
430
patch = parse_patch(lines.__iter__())
432
i = difference_index(patchtext, pstr)
434
print "%i: \"%s\" != \"%s\"" % (i, patchtext[i], pstr[i])
435
assert (patchtext == str(patch))
438
"""Test parsing a whole patch"""
439
patchtext = """--- orig/commands.py
441
@@ -1337,7 +1337,8 @@
443
def set_title(self, command=None):
445
- version = self.tree.tree_version.nonarch
446
+ version = pylon.alias_or_version(self.tree.tree_version, self.tree,
449
version = "[no version]"
451
@@ -1983,7 +1984,11 @@
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)
460
+ mergestuff = cmdutil.log_for_merge(tree, comp_version)
461
log.description += mergestuff
465
self.compare_parsed(patchtext)
468
"""Handle patches missing half the position, range tuple"""
470
"""--- orig/__init__.py
473
__docformat__ = "restructuredtext en"
474
+__doc__ = An alternate Arch commandline interface"""
475
self.compare_parsed(patchtext)
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"))
485
for i in range(len(orig)):
486
mod_pos = patch.pos_in_mod(i)
488
removals.append(orig[i])
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,
499
assert(line.contents == next)
500
self.assertRaises(StopIteration, rem_iter.next)
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)
508
patchesTestSuite = unittest.makeSuite(PatchesTester,'test')
509
runner = unittest.TextTestRunner(verbosity=0)
510
return runner.run(patchesTestSuite)
513
if __name__ == "__main__":
515
# arch-tag: d1541a25-eac5-4de9-a476-08a7cecd5683