##// END OF EJS Templates
unidiff: punt on comparing empty files
mpm@selenic.com -
r35:9197c26a default
parent child Browse files
Show More
@@ -1,76 +1,77 b''
1 1 #!/usr/bin/python
2 2 import difflib, struct
3 3 from cStringIO import StringIO
4 4
5 5 def unidiff(a, b, fn):
6 if not a and not b: return ""
6 7 a = a.splitlines(1)
7 8 b = b.splitlines(1)
8 l = difflib.unified_diff(a, b, fn, fn)
9 l = list(difflib.unified_diff(a, b, fn, fn))
9 10 return "".join(l)
10 11
11 12 def textdiff(a, b):
12 13 return diff(a.splitlines(1), b.splitlines(1))
13 14
14 15 def sortdiff(a, b):
15 16 la = lb = 0
16 17
17 18 while 1:
18 19 if la >= len(a) or lb >= len(b): break
19 20 if b[lb] < a[la]:
20 21 si = lb
21 22 while lb < len(b) and b[lb] < a[la] : lb += 1
22 23 yield "insert", la, la, si, lb
23 24 elif a[la] < b[lb]:
24 25 si = la
25 26 while la < len(a) and a[la] < b[lb]: la += 1
26 27 yield "delete", si, la, lb, lb
27 28 else:
28 29 la += 1
29 30 lb += 1
30 31
31 32 si = lb
32 33 while lb < len(b):
33 34 lb += 1
34 35 yield "insert", la, la, si, lb
35 36
36 37 si = la
37 38 while la < len(a):
38 39 la += 1
39 40 yield "delete", si, la, lb, lb
40 41
41 42 def diff(a, b, sorted=0):
42 43 bin = []
43 44 p = [0]
44 45 for i in a: p.append(p[-1] + len(i))
45 46
46 47 if sorted:
47 48 d = sortdiff(a, b)
48 49 else:
49 50 d = difflib.SequenceMatcher(None, a, b).get_opcodes()
50 51
51 52 for o, m, n, s, t in d:
52 53 if o == 'equal': continue
53 54 s = "".join(b[s:t])
54 55 bin.append(struct.pack(">lll", p[m], p[n], len(s)) + s)
55 56
56 57 return "".join(bin)
57 58
58 59 def patch(a, bin):
59 60 last = pos = 0
60 61 r = []
61 62
62 63 while pos < len(bin):
63 64 p1, p2, l = struct.unpack(">lll", bin[pos:pos + 12])
64 65 pos += 12
65 66 r.append(a[last:p1])
66 67 r.append(bin[pos:pos + l])
67 68 pos += l
68 69 last = p2
69 70 r.append(a[last:])
70 71
71 72 return "".join(r)
72 73
73 74
74 75
75 76
76 77
General Comments 0
You need to be logged in to leave comments. Login now