##// END OF EJS Templates
unidiff: handle empty diffs more gracefully...
mpm@selenic.com -
r278:777e388c default
parent child Browse files
Show More
@@ -1,94 +1,95 b''
1 1 # mdiff.py - diff and patch routines for mercurial
2 2 #
3 3 # Copyright 2005 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms
6 6 # of the GNU General Public License, incorporated herein by reference.
7 7
8 8 import difflib, struct
9 9 from mercurial.mpatch import *
10 10
11 11 def unidiff(a, ad, b, bd, fn):
12 12 if not a and not b: return ""
13 13
14 14 if a == None:
15 15 b = b.splitlines(1)
16 16 l1 = "--- %s\t%s\n" % ("/dev/null", ad)
17 17 l2 = "+++ %s\t%s\n" % ("b/" + fn, bd)
18 18 l3 = "@@ -0,0 +1,%d @@\n" % len(b)
19 19 l = [l1, l2, l3] + ["+" + e for e in b]
20 20 elif b == None:
21 21 a = a.splitlines(1)
22 22 l1 = "--- %s\t%s\n" % ("a/" + fn, ad)
23 23 l2 = "+++ %s\t%s\n" % ("/dev/null", bd)
24 24 l3 = "@@ -1,%d +0,0 @@\n" % len(a)
25 25 l = [l1, l2, l3] + ["-" + e for e in a]
26 26 else:
27 27 a = a.splitlines(1)
28 28 b = b.splitlines(1)
29 29 l = list(difflib.unified_diff(a, b, "a/" + fn, "b/" + fn))
30 if not l: return ""
30 31 # difflib uses a space, rather than a tab
31 32 l[0] = l[0][:-2] + "\t" + ad + "\n"
32 33 l[1] = l[1][:-2] + "\t" + bd + "\n"
33 34
34 35 for ln in xrange(len(l)):
35 36 if l[ln][-1] != '\n':
36 37 l[ln] += "\n\ No newline at end of file\n"
37 38
38 39 return "".join(l)
39 40
40 41 def textdiff(a, b):
41 42 return diff(a.splitlines(1), b.splitlines(1))
42 43
43 44 def sortdiff(a, b):
44 45 la = lb = 0
45 46 lena = len(a)
46 47 lenb = len(b)
47 48 while 1:
48 49 am, bm, = la, lb
49 50 while lb < lenb and la < len and a[la] == b[lb] :
50 51 la += 1
51 52 lb += 1
52 53 if la>am: yield (am, bm, la-am)
53 54 while lb < lenb and b[lb] < a[la]: lb += 1
54 55 if lb>=lenb: break
55 56 while la < lena and b[lb] > a[la]: la += 1
56 57 if la>=lena: break
57 58 yield (lena, lenb, 0)
58 59
59 60 def diff(a, b, sorted=0):
60 61 if not a:
61 62 s = "".join(b)
62 63 return s and (struct.pack(">lll", 0, 0, len(s)) + s)
63 64
64 65 bin = []
65 66 p = [0]
66 67 for i in a: p.append(p[-1] + len(i))
67 68
68 69 if sorted:
69 70 d = sortdiff(a, b)
70 71 else:
71 72 d = difflib.SequenceMatcher(None, a, b).get_matching_blocks()
72 73 la = 0
73 74 lb = 0
74 75 for am, bm, size in d:
75 76 s = "".join(b[lb:bm])
76 77 if am > la or s:
77 78 bin.append(struct.pack(">lll", p[la], p[am], len(s)) + s)
78 79 la = am + size
79 80 lb = bm + size
80 81
81 82 return "".join(bin)
82 83
83 84 def patchtext(bin):
84 85 pos = 0
85 86 t = []
86 87 while pos < len(bin):
87 88 p1, p2, l = struct.unpack(">lll", bin[pos:pos + 12])
88 89 pos += 12
89 90 t.append(bin[pos:pos + l])
90 91 pos += l
91 92 return "".join(t)
92 93
93 94 def patch(a, bin):
94 95 return patches(a, [bin])
General Comments 0
You need to be logged in to leave comments. Login now