]> git.openstreetmap.org Git - osqa.git/blob - forum/utils/diff.py
Fixed yahoo openid auth
[osqa.git] / forum / utils / diff.py
1 #!/usr/bin/python2.2
2 """HTML Diff: http://www.aaronsw.com/2002/diff
3 Rough code, badly documented. Send me comments and patches."""
4
5 __author__ = 'Aaron Swartz <me@aaronsw.com>'
6 __copyright__ = '(C) 2003 Aaron Swartz. GNU GPL 2.'
7 __version__ = '0.22'
8
9 import difflib, string
10
11 def isTag(x): return x[0] == "<" and x[-1] == ">"
12
13 def textDiff(a, b):
14         """Takes in strings a and b and returns a human-readable HTML diff."""
15
16         out = []
17         a, b = html2list(a), html2list(b)
18         s = difflib.SequenceMatcher(None, a, b)
19         for e in s.get_opcodes():
20                 if e[0] == "replace":
21                         # @@ need to do something more complicated here
22                         # call textDiff but not for html, but for some html... ugh
23                         # gonna cop-out for now
24                         out.append('<del>'+''.join(a[e[1]:e[2]]) + '</del><ins>'+''.join(b[e[3]:e[4]])+"</ins>")
25                 elif e[0] == "delete":
26                         out.append('<del >'+ ''.join(a[e[1]:e[2]]) + "</del>")
27                 elif e[0] == "insert":
28                         out.append('<ins >'+''.join(b[e[3]:e[4]]) + "</ins>")
29                 elif e[0] == "equal":
30                         out.append(''.join(b[e[3]:e[4]]))
31                 else: 
32                         raise "Um, something's broken. I didn't expect a '" + `e[0]` + "'."
33         return ''.join(out)
34
35 def html2list(x, b=0):
36         mode = 'char'
37         cur = ''
38         out = []
39         for c in x:
40                 if mode == 'tag':
41                         if c == '>': 
42                                 if b: cur += ']'
43                                 else: cur += c
44                                 out.append(cur); cur = ''; mode = 'char'
45                         else: cur += c
46                 elif mode == 'char':
47                         if c == '<': 
48                                 out.append(cur)
49                                 if b: cur = '['
50                                 else: cur = c
51                                 mode = 'tag'
52                         elif c in string.whitespace: out.append(cur+c); cur = ''
53                         else: cur += c
54         out.append(cur)
55         return filter(lambda x: x is not '', out)
56
57 if __name__ == '__main__':
58         import sys
59         try:
60                 a, b = sys.argv[1:3]
61         except ValueError:
62                 print "htmldiff: highlight the differences between two html files"
63                 print "usage: " + sys.argv[0] + " a b"
64                 sys.exit(1)
65         print textDiff(open(a).read(), open(b).read())
66