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
17
class PatchSyntax(Exception):
18
def __init__(self, msg):
19
Exception.__init__(self, msg)
22
class MalformedPatchHeader(PatchSyntax):
23
def __init__(self, desc, line):
26
msg = "Malformed patch header. %s\n%s" % (self.desc, self.line)
27
PatchSyntax.__init__(self, msg)
29
class MalformedHunkHeader(PatchSyntax):
30
def __init__(self, desc, line):
33
msg = "Malformed hunk header. %s\n%s" % (self.desc, self.line)
34
PatchSyntax.__init__(self, msg)
36
class MalformedLine(PatchSyntax):
37
def __init__(self, desc, line):
40
msg = "Malformed line. %s\n%s" % (self.desc, self.line)
41
PatchSyntax.__init__(self, msg)
43
def get_patch_names(iter_lines):
45
line = iter_lines.next()
46
if not line.startswith("--- "):
47
raise MalformedPatchHeader("No orig name", line)
49
orig_name = line[4:].rstrip("\n")
51
raise MalformedPatchHeader("No orig line", "")
53
line = iter_lines.next()
54
if not line.startswith("+++ "):
55
raise PatchSyntax("No mod name")
57
mod_name = line[4:].rstrip("\n")
59
raise MalformedPatchHeader("No mod line", "")
60
return (orig_name, mod_name)
62
def parse_range(textrange):
63
"""Parse a patch range, handling the "1" special-case
65
:param textrange: The text to parse
67
:return: the position and range, as a tuple
70
tmp = textrange.split(',')
81
def hunk_from_header(line):
82
if not line.startswith("@@") or not line.endswith("@@\n") \
84
raise MalformedHunkHeader("Does not start and end with @@.", line)
86
(orig, mod) = line[3:-4].split(" ")
88
raise MalformedHunkHeader(str(e), line)
89
if not orig.startswith('-') or not mod.startswith('+'):
90
raise MalformedHunkHeader("Positions don't start with + or -.", line)
92
(orig_pos, orig_range) = parse_range(orig[1:])
93
(mod_pos, mod_range) = parse_range(mod[1:])
95
raise MalformedHunkHeader(str(e), line)
96
if mod_range < 0 or orig_range < 0:
97
raise MalformedHunkHeader("Hunk range is negative", line)
98
return Hunk(orig_pos, orig_range, mod_pos, mod_range)
102
def __init__(self, contents):
103
self.contents = contents
105
def get_str(self, leadchar):
106
if self.contents == "\n" and leadchar == " " and False:
108
return leadchar + self.contents
110
class ContextLine(HunkLine):
111
def __init__(self, contents):
112
HunkLine.__init__(self, contents)
115
return self.get_str(" ")
118
class InsertLine(HunkLine):
119
def __init__(self, contents):
120
HunkLine.__init__(self, contents)
123
return self.get_str("+")
126
class RemoveLine(HunkLine):
127
def __init__(self, contents):
128
HunkLine.__init__(self, contents)
131
return self.get_str("-")
133
__pychecker__="no-returnvalues"
134
def parse_line(line):
135
if line.startswith("\n"):
136
return ContextLine(line)
137
elif line.startswith(" "):
138
return ContextLine(line[1:])
139
elif line.startswith("+"):
140
return InsertLine(line[1:])
141
elif line.startswith("-"):
142
return RemoveLine(line[1:])
144
raise MalformedLine("Unknown line type", line)
149
def __init__(self, orig_pos, orig_range, mod_pos, mod_range):
150
self.orig_pos = orig_pos
151
self.orig_range = orig_range
152
self.mod_pos = mod_pos
153
self.mod_range = mod_range
156
def get_header(self):
157
return "@@ -%s +%s @@\n" % (self.range_str(self.orig_pos,
159
self.range_str(self.mod_pos,
162
def range_str(self, pos, range):
163
"""Return a file range, special-casing for 1-line files.
165
:param pos: The position in the file
167
:range: The range in the file
169
:return: a string in the format 1,4 except when range == pos == 1
174
return "%i,%i" % (pos, range)
177
lines = [self.get_header()]
178
for line in self.lines:
179
lines.append(str(line))
180
return "".join(lines)
182
def shift_to_mod(self, pos):
183
if pos < self.orig_pos-1:
185
elif pos > self.orig_pos+self.orig_range:
186
return self.mod_range - self.orig_range
188
return self.shift_to_mod_lines(pos)
190
def shift_to_mod_lines(self, pos):
191
assert (pos >= self.orig_pos-1 and pos <= self.orig_pos+self.orig_range)
192
position = self.orig_pos-1
194
for line in self.lines:
195
if isinstance(line, InsertLine):
197
elif isinstance(line, RemoveLine):
202
elif isinstance(line, ContextLine):
208
def iter_hunks(iter_lines):
210
for line in iter_lines:
211
if line.startswith("@@"):
214
hunk = hunk_from_header(line)
216
hunk.lines.append(parse_line(line))
222
def __init__(self, oldname, newname):
223
self.oldname = oldname
224
self.newname = newname
228
ret = "--- %s\n+++ %s\n" % (self.oldname, self.newname)
229
ret += "".join([str(h) for h in self.hunks])
233
"""Return a string of patch statistics"""
236
for hunk in self.hunks:
237
for line in hunk.lines:
238
if isinstance(line, InsertLine):
240
elif isinstance(line, RemoveLine):
242
return "%i inserts, %i removes in %i hunks" % \
243
(inserts, removes, len(self.hunks))
245
def pos_in_mod(self, position):
247
for hunk in self.hunks:
248
shift = hunk.shift_to_mod(position)
254
def iter_inserted(self):
255
"""Iteraties through inserted lines
257
:return: Pair of line number, line
258
:rtype: iterator of (int, InsertLine)
260
for hunk in self.hunks:
261
pos = hunk.mod_pos - 1;
262
for line in hunk.lines:
263
if isinstance(line, InsertLine):
266
if isinstance(line, ContextLine):
269
def parse_patch(iter_lines):
270
(orig_name, mod_name) = get_patch_names(iter_lines)
271
patch = Patch(orig_name, mod_name)
272
for hunk in iter_hunks(iter_lines):
273
patch.hunks.append(hunk)
277
def iter_file_patch(iter_lines):
279
for line in iter_lines:
280
if line.startswith('*** '):
282
elif line.startswith('--- '):
283
if len(saved_lines) > 0:
286
saved_lines.append(line)
287
if len(saved_lines) > 0:
291
def parse_patches(iter_lines):
292
return [parse_patch(f.__iter__()) for f in iter_file_patch(iter_lines)]
295
def difference_index(atext, btext):
296
"""Find the indext of the first character that differs betweeen two texts
298
:param atext: The first text
300
:param btext: The second text
302
:return: The index, or None if there are no differences within the range
303
:rtype: int or NoneType
306
if len(btext) < length:
308
for i in range(length):
309
if atext[i] != btext[i]:
316
class PatchesTester(unittest.TestCase):
317
def testValidPatchHeader(self):
318
"""Parse a valid patch header"""
319
lines = "--- orig/commands.py\n+++ mod/dommands.py\n".split('\n')
320
(orig, mod) = get_patch_names(lines.__iter__())
321
assert(orig == "orig/commands.py")
322
assert(mod == "mod/dommands.py")
324
def testInvalidPatchHeader(self):
325
"""Parse an invalid patch header"""
326
lines = "-- orig/commands.py\n+++ mod/dommands.py".split('\n')
327
self.assertRaises(MalformedPatchHeader, get_patch_names,
330
def testValidHunkHeader(self):
331
"""Parse a valid hunk header"""
332
header = "@@ -34,11 +50,6 @@\n"
333
hunk = hunk_from_header(header);
334
assert (hunk.orig_pos == 34)
335
assert (hunk.orig_range == 11)
336
assert (hunk.mod_pos == 50)
337
assert (hunk.mod_range == 6)
338
assert (str(hunk) == header)
340
def testValidHunkHeader2(self):
341
"""Parse a tricky, valid hunk header"""
342
header = "@@ -1 +0,0 @@\n"
343
hunk = hunk_from_header(header);
344
assert (hunk.orig_pos == 1)
345
assert (hunk.orig_range == 1)
346
assert (hunk.mod_pos == 0)
347
assert (hunk.mod_range == 0)
348
assert (str(hunk) == header)
350
def makeMalformed(self, header):
351
self.assertRaises(MalformedHunkHeader, hunk_from_header, header)
353
def testInvalidHeader(self):
354
"""Parse an invalid hunk header"""
355
self.makeMalformed(" -34,11 +50,6 \n")
356
self.makeMalformed("@@ +50,6 -34,11 @@\n")
357
self.makeMalformed("@@ -34,11 +50,6 @@")
358
self.makeMalformed("@@ -34.5,11 +50,6 @@\n")
359
self.makeMalformed("@@-34,11 +50,6@@\n")
360
self.makeMalformed("@@ 34,11 50,6 @@\n")
361
self.makeMalformed("@@ -34,11 @@\n")
362
self.makeMalformed("@@ -34,11 +50,6.5 @@\n")
363
self.makeMalformed("@@ -34,11 +50,-6 @@\n")
365
def lineThing(self,text, type):
366
line = parse_line(text)
367
assert(isinstance(line, type))
368
assert(str(line)==text)
370
def makeMalformedLine(self, text):
371
self.assertRaises(MalformedLine, parse_line, text)
373
def testValidLine(self):
374
"""Parse a valid hunk line"""
375
self.lineThing(" hello\n", ContextLine)
376
self.lineThing("+hello\n", InsertLine)
377
self.lineThing("-hello\n", RemoveLine)
379
def testMalformedLine(self):
380
"""Parse invalid valid hunk lines"""
381
self.makeMalformedLine("hello\n")
383
def compare_parsed(self, patchtext):
384
lines = patchtext.splitlines(True)
385
patch = parse_patch(lines.__iter__())
387
i = difference_index(patchtext, pstr)
389
print "%i: \"%s\" != \"%s\"" % (i, patchtext[i], pstr[i])
390
assert (patchtext == str(patch))
393
"""Test parsing a whole patch"""
394
patchtext = """--- orig/commands.py
396
@@ -1337,7 +1337,8 @@
398
def set_title(self, command=None):
400
- version = self.tree.tree_version.nonarch
401
+ version = pylon.alias_or_version(self.tree.tree_version, self.tree,
404
version = "[no version]"
406
@@ -1983,7 +1984,11 @@
408
if len(new_merges) > 0:
409
if cmdutil.prompt("Log for merge"):
410
- mergestuff = cmdutil.log_for_merge(tree, comp_version)
411
+ if cmdutil.prompt("changelog for merge"):
412
+ mergestuff = "Patches applied:\\n"
413
+ mergestuff += pylon.changelog_for_merge(new_merges)
415
+ mergestuff = cmdutil.log_for_merge(tree, comp_version)
416
log.description += mergestuff
420
self.compare_parsed(patchtext)
423
"""Handle patches missing half the position, range tuple"""
425
"""--- orig/__init__.py
428
__docformat__ = "restructuredtext en"
429
+__doc__ = An alternate Arch commandline interface"""
430
self.compare_parsed(patchtext)
434
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