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
18
class PatchSyntax(Exception):
19
def __init__(self, msg):
20
Exception.__init__(self, msg)
23
class MalformedPatchHeader(PatchSyntax):
24
def __init__(self, desc, line):
27
msg = "Malformed patch header. %s\n%s" % (self.desc, self.line)
28
PatchSyntax.__init__(self, msg)
30
class MalformedHunkHeader(PatchSyntax):
31
def __init__(self, desc, line):
34
msg = "Malformed hunk header. %s\n%s" % (self.desc, self.line)
35
PatchSyntax.__init__(self, msg)
37
class MalformedLine(PatchSyntax):
38
def __init__(self, desc, line):
41
msg = "Malformed line. %s\n%s" % (self.desc, self.line)
42
PatchSyntax.__init__(self, msg)
44
def get_patch_names(iter_lines):
46
line = iter_lines.next()
47
if not line.startswith("--- "):
48
raise MalformedPatchHeader("No orig name", line)
50
orig_name = line[4:].rstrip("\n")
52
raise MalformedPatchHeader("No orig line", "")
54
line = iter_lines.next()
55
if not line.startswith("+++ "):
56
raise PatchSyntax("No mod name")
58
mod_name = line[4:].rstrip("\n")
60
raise MalformedPatchHeader("No mod line", "")
61
return (orig_name, mod_name)
63
def parse_range(textrange):
64
"""Parse a patch range, handling the "1" special-case
66
:param textrange: The text to parse
68
:return: the position and range, as a tuple
71
tmp = textrange.split(',')
82
def hunk_from_header(line):
83
if not line.startswith("@@") or not line.endswith("@@\n") \
85
raise MalformedHunkHeader("Does not start and end with @@.", line)
87
(orig, mod) = line[3:-4].split(" ")
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)
93
(orig_pos, orig_range) = parse_range(orig[1:])
94
(mod_pos, mod_range) = parse_range(mod[1:])
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)
103
def __init__(self, contents):
104
self.contents = contents
106
def get_str(self, leadchar):
107
if self.contents == "\n" and leadchar == " " and False:
109
return leadchar + self.contents
111
class ContextLine(HunkLine):
112
def __init__(self, contents):
113
HunkLine.__init__(self, contents)
116
return self.get_str(" ")
119
class InsertLine(HunkLine):
120
def __init__(self, contents):
121
HunkLine.__init__(self, contents)
124
return self.get_str("+")
127
class RemoveLine(HunkLine):
128
def __init__(self, contents):
129
HunkLine.__init__(self, contents)
132
return self.get_str("-")
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:])
145
raise MalformedLine("Unknown line type", line)
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
157
def get_header(self):
158
return "@@ -%s +%s @@\n" % (self.range_str(self.orig_pos,
160
self.range_str(self.mod_pos,
163
def range_str(self, pos, range):
164
"""Return a file range, special-casing for 1-line files.
166
:param pos: The position in the file
168
:range: The range in the file
170
:return: a string in the format 1,4 except when range == pos == 1
175
return "%i,%i" % (pos, range)
178
lines = [self.get_header()]
179
for line in self.lines:
180
lines.append(str(line))
181
return "".join(lines)
183
def shift_to_mod(self, pos):
184
if pos < self.orig_pos-1:
186
elif pos > self.orig_pos+self.orig_range:
187
return self.mod_range - self.orig_range
189
return self.shift_to_mod_lines(pos)
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
195
for line in self.lines:
196
if isinstance(line, InsertLine):
198
elif isinstance(line, RemoveLine):
203
elif isinstance(line, ContextLine):
209
def iter_hunks(iter_lines):
211
for line in iter_lines:
212
if line.startswith("@@"):
215
hunk = hunk_from_header(line)
217
hunk.lines.append(parse_line(line))
223
def __init__(self, oldname, newname):
224
self.oldname = oldname
225
self.newname = newname
229
ret = "--- %s\n+++ %s\n" % (self.oldname, self.newname)
230
ret += "".join([str(h) for h in self.hunks])
234
"""Return a string of patch statistics"""
237
for hunk in self.hunks:
238
for line in hunk.lines:
239
if isinstance(line, InsertLine):
241
elif isinstance(line, RemoveLine):
243
return "%i inserts, %i removes in %i hunks" % \
244
(inserts, removes, len(self.hunks))
246
def pos_in_mod(self, position):
248
for hunk in self.hunks:
249
shift = hunk.shift_to_mod(position)
255
def iter_inserted(self):
256
"""Iteraties through inserted lines
258
:return: Pair of line number, line
259
:rtype: iterator of (int, InsertLine)
261
for hunk in self.hunks:
262
pos = hunk.mod_pos - 1;
263
for line in hunk.lines:
264
if isinstance(line, InsertLine):
267
if isinstance(line, ContextLine):
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)
278
def iter_file_patch(iter_lines):
280
for line in iter_lines:
281
if line.startswith('*** '):
283
elif line.startswith('--- '):
284
if len(saved_lines) > 0:
287
saved_lines.append(line)
288
if len(saved_lines) > 0:
292
def parse_patches(iter_lines):
293
return [parse_patch(f.__iter__()) for f in iter_file_patch(iter_lines)]
296
def difference_index(atext, btext):
297
"""Find the indext of the first character that differs betweeen two texts
299
:param atext: The first text
301
:param btext: The second text
303
:return: The index, or None if there are no differences within the range
304
:rtype: int or NoneType
307
if len(btext) < length:
309
for i in range(length):
310
if atext[i] != btext[i]:
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")
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,
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)
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)
351
def makeMalformed(self, header):
352
self.assertRaises(MalformedHunkHeader, hunk_from_header, header)
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")
366
def lineThing(self,text, type):
367
line = parse_line(text)
368
assert(isinstance(line, type))
369
assert(str(line)==text)
371
def makeMalformedLine(self, text):
372
self.assertRaises(MalformedLine, parse_line, text)
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)
380
def testMalformedLine(self):
381
"""Parse invalid valid hunk lines"""
382
self.makeMalformedLine("hello\n")
384
def compare_parsed(self, patchtext):
385
lines = patchtext.splitlines(True)
386
patch = parse_patch(lines.__iter__())
388
i = difference_index(patchtext, pstr)
390
print "%i: \"%s\" != \"%s\"" % (i, patchtext[i], pstr[i])
391
assert (patchtext == str(patch))
394
"""Test parsing a whole patch"""
395
patchtext = """--- orig/commands.py
397
@@ -1337,7 +1337,8 @@
399
def set_title(self, command=None):
401
- version = self.tree.tree_version.nonarch
402
+ version = pylon.alias_or_version(self.tree.tree_version, self.tree,
405
version = "[no version]"
407
@@ -1983,7 +1984,11 @@
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)
416
+ mergestuff = cmdutil.log_for_merge(tree, comp_version)
417
log.description += mergestuff
421
self.compare_parsed(patchtext)
424
"""Handle patches missing half the position, range tuple"""
426
"""--- orig/__init__.py
429
__docformat__ = "restructuredtext en"
430
+__doc__ = An alternate Arch commandline interface"""
431
self.compare_parsed(patchtext)
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"))
441
for i in range(len(orig)):
442
mod_pos = patch.pos_in_mod(i)
444
removals.append(orig[i])
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,
455
assert(line.contents == next)
456
self.assertRaises(StopIteration, rem_iter.next)
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)
464
patchesTestSuite = unittest.makeSuite(PatchesTester,'test')
465
runner = unittest.TextTestRunner(verbosity=0)
466
return runner.run(patchesTestSuite)
469
if __name__ == "__main__":
471
# arch-tag: d1541a25-eac5-4de9-a476-08a7cecd5683