59d445dbf9cdf9dfd655a6bacf881feafd56c7bf
[diff2html.git] / diff2html.py
1 #! /usr/bin/python
2 #
3 # This program is free software; you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation; either version 2 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program; if not, write to the Free Software
15 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16 #
17 #
18 # Transform a unified diff from stdin to a colored
19 # side-by-side HTML page on stdout.
20 #
21 # Author: Olivier MATZ <zer0@droids-corp.org>
22 #
23 # Inspired by diff2html.rb from Dave Burt <dave (at) burt.id.au>
24 # (mainly for html theme)
25 #
26 # Changed by Alan De Smet <adesmet@cs.wisc.edu> 2009-01-25
27 # - Remove headers and footers that are undesirable for for CVSTrac
28 #   integration.
29 # - Change style sheet to own preferences
30 # - Adjust LINESIZE code to reset counter and allow breaks whenever 
31 #   WORDBREAK characters are encountered.
32 # - Don't display offset info (it's redundant with the line numbers)
33 #   instead show vertical ellipsis
34 # - If part of a "change" is actually blank, it's an addition or
35 #   deletion, not a "change" where the entire line changed.
36 # - Don't display "\" for end of line; unnecessary noise.
37
38 # TODO:
39 # - The sane function currently mashes non-ASCII characters to "."
40 #   Instead be clever and convert to something like "xF0" 
41 #   (the hex value), and mark with a <span>.  Even more clever:
42 #   Detect if the character is "printable" for whatever definition,
43 #   and display those directly.
44
45
46 import sys, re, htmlentitydefs
47
48 html_hdr="""
49                 <table class="diff">
50 """
51
52 html_footer="""
53 </table>
54 """
55
56 DIFFON="\x01"
57 DIFFOFF="\x02"
58
59 buffer=[]
60 add_cpt, del_cpt = 0,0
61 line1, line2 = 0,0
62 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0,0,0,0
63
64 # minimum line size, we add a zero-sized breakable space every
65 # LINESIZE characters
66 LINESIZE=20
67 TAB=4
68
69 # Characters we're willing to word wrap on
70 WORDBREAK=" \t;.,/):"
71
72 def sane(x):
73     r=""
74     for i in x:
75         j = ord(i)
76         if i not in ['\t', '\n'] and ((j < 32) or (j >= 127)):
77             r=r+"."
78         else:
79             r=r+i
80     return r
81
82 def linediff(s, t):
83     if len(s):
84         s=str(reduce(lambda x,y:x+y, [ sane(c) for c in s ]))
85     if len(t):
86         t=str(reduce(lambda x,y:x+y, [ sane(c) for c in t ]))
87     
88     m,n = len(s), len(t)
89     d=[[(0,0) for i in range(n+1)] for i in range(m+1)]
90     x=[[(0,0) for i in range(n+1)] for i in range(m+1)]
91
92     
93     d[0][0] = (0, (0,0))
94     for i in range(m+1)[1:]:
95         d[i][0] = (i,(i-1,0))
96     for j in range(n+1)[1:]:
97         d[0][j] = (j,(0,j-1))
98
99     for i in range(m+1)[1:]:
100         for j in range(n+1)[1:]:
101             if s[i-1] == t[j-1]:
102                 cost = 0
103             else:
104                 cost = 1
105             d[i][j] = min((d[i-1][j][0] + 1, (i-1,j)),
106                           (d[i][j-1][0] + 1, (i,j-1)),
107                           (d[i-1][j-1][0] + cost, (i-1,j-1)))
108             
109     l=[]
110     coord = (m,n)
111     while coord != (0,0):
112         l.insert(0, coord)
113         x,y = coord
114         coord = d[x][y][1]
115
116     l1 = []
117     l2 = []
118
119     for coord in l:
120         cx,cy = coord
121         child_val = d[cx][cy][0]
122         
123         father_coord = d[cx][cy][1]
124         fx,fy = father_coord
125         father_val = d[fx][fy][0]
126
127         diff = (cx-fx, cy-fy)
128
129         if diff == (0,1):
130             l1.append("")
131             l2.append(DIFFON + t[fy] + DIFFOFF)
132         elif diff == (1,0):
133             l1.append(DIFFON + s[fx] + DIFFOFF)
134             l2.append("")
135         elif child_val-father_val == 1:
136             l1.append(DIFFON + s[fx] + DIFFOFF)
137             l2.append(DIFFON + t[fy] + DIFFOFF)
138         else:
139             l1.append(s[fx])
140             l2.append(t[fy])
141
142     r1,r2 = (reduce(lambda x,y:x+y, l1), reduce(lambda x,y:x+y, l2))
143     return r1,r2
144
145
146 def convert(s, linesize=0, ponct=0):
147     i=0
148     t=""
149     l=[]
150     for c in s:
151         # used by diffs
152         if c==DIFFON:
153             t += '<span class="diffchanged2">'
154         elif c==DIFFOFF:
155             t += "</span>"
156
157         # special html chars
158         elif htmlentitydefs.codepoint2name.has_key(ord(c)):
159             t += "&%s;"%(htmlentitydefs.codepoint2name[ord(c)])
160             i += 1
161
162         # special highlighted chars
163         elif c=="\t" and ponct==1:
164             n = TAB-(i%TAB)
165             if n==0:
166                 n=TAB
167             t += ('<span class="diffponct">&raquo;</span>'+'&nbsp;'*(n-1))
168         elif c==" " and ponct==1:
169             t += '<span class="diffponct">&middot;</span>'
170         elif c=="\n" and ponct==1:
171             1 # Quietly drop it.
172             #t += '<span class="diffponct">\</span>'
173         else:
174             t += c
175             i += 1
176
177         if linesize and (WORDBREAK.count(c)==1):
178             t += '&#8203;'
179             i=0
180         if linesize and i>linesize:
181             i=0
182             t += "&#8203;"
183         
184     return t
185
186
187 def add_comment(s):
188     sys.stdout.write('<tr class="diffmisc"><td colspan="4">%s</td></tr>\n'%convert(s))
189
190 def add_filename(f1, f2):
191     sys.stdout.write("<tr><th colspan='2'>%s</th>"%convert(f1, linesize=LINESIZE))
192     sys.stdout.write("<th colspan='2'>%s</th></tr>\n"%convert(f2, linesize=LINESIZE))
193
194 def add_hunk():
195     global hunk_off1
196     global hunk_size1
197     global hunk_off2
198     global hunk_size2
199         # Don't bother displaying, it's redundant with the line numbers.
200     #sys.stdout.write('<tr class="diffhunk"><td colspan="2">Offset %d, %d lines modified</td>'%(hunk_off1, hunk_size1))
201     #sys.stdout.write('<td colspan="2">Offset %d, %d lines modified</td></tr>\n'%(hunk_off2, hunk_size2))
202         # &#8942; - vertical ellipsis
203     sys.stdout.write('<tr class="diffhunk"><td colspan="2">&#8942;</td><td colspan="2">&#8942;</td></tr>');
204
205
206 def add_line(s1, s2):
207     global line1
208     global line2
209
210     if s1==None and s2==None:
211         type="unmodified"
212     elif s1==None or s1=="":
213         type="added"
214     elif s2==None or s1=="":
215         type="deleted"
216     elif s1==s2:
217         type="unmodified"
218     else:
219         type="changed"
220         s1,s2 = linediff(s1, s2)
221
222     sys.stdout.write('<tr class="diff%s">'%type)
223     if s1!=None and s1!="":
224         sys.stdout.write('<td class="diffline">%d </td>'%line1)
225         sys.stdout.write('<td class="diffpresent">')
226         sys.stdout.write(convert(s1, linesize=LINESIZE, ponct=1))
227         sys.stdout.write('</td>')
228     else:
229         s1=""
230         sys.stdout.write('<td colspan="2"> </td>')
231     
232     if s2!=None and s2!="":
233         sys.stdout.write('<td class="diffline">%d </td>'%line2)
234         sys.stdout.write('<td class="diffpresent">')
235         sys.stdout.write(convert(s2, linesize=LINESIZE, ponct=1))
236         sys.stdout.write('</td>')
237     else:
238         s2=""
239         sys.stdout.write('<td colspan="2"></td>')
240
241     sys.stdout.write('</tr>\n')
242
243     if s1!="":
244         line1 += 1
245     if s2!="":
246         line2 += 1
247
248
249 def empty_buffer():
250     global buffer
251     global add_cpt
252     global del_cpt
253
254     if del_cpt == 0 or add_cpt == 0:
255         for l in buffer:
256             add_line(l[0], l[1])
257
258     elif del_cpt != 0 and add_cpt != 0:
259         l0, l1 = [], []
260         for l in buffer:
261             if l[0] != None:
262                 l0.append(l[0])
263             if l[1] != None:
264                 l1.append(l[1])
265         max = (len(l0) > len(l1)) and len(l0) or len(l1)
266         for i in range(max):
267             s0, s1 = "", ""
268             if i<len(l0):
269                 s0 = l0[i]
270             if i<len(l1):
271                 s1 = l1[i]
272             add_line(s0, s1)
273         
274     add_cpt, del_cpt = 0,0
275     buffer = []
276
277
278
279 sys.stdout.write(html_hdr)
280
281 while True:
282     l=sys.stdin.readline()
283     if l=="":
284         break
285     
286     m=re.match('^--- ([^\s]*)', l)
287     if m:
288         empty_buffer()
289         file1=m.groups()[0]
290         l=sys.stdin.readline()
291         m=re.match('^\+\+\+ ([^\s]*)', l)
292         if m:
293             file2=m.groups()[0]
294         add_filename(file1, file2)
295         hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0,0,0,0
296         continue
297
298     m=re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
299     if m:
300         empty_buffer()
301         hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
302         hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
303         line1, line2 = hunk_off1, hunk_off2
304         add_hunk()
305         continue
306         
307     if hunk_size1 == 0 and hunk_size2 == 0:
308         empty_buffer()
309         add_comment(l)
310         continue
311
312     if re.match("^\+", l):
313         add_cpt += 1
314         hunk_size2 -= 1
315         buffer.append((None, l[1:]))
316         continue
317
318     if re.match("^\-", l):
319         del_cpt += 1
320         hunk_size1 -= 1
321         buffer.append((l[1:], None))
322         continue
323
324     if re.match("^\ ", l) and hunk_size1 and hunk_size2:
325         empty_buffer()
326         hunk_size1 -= 1
327         hunk_size2 -= 1
328         buffer.append((l[1:], l[1:]))
329         continue
330
331     empty_buffer()
332     add_comment(l)
333
334
335 empty_buffer()
336 sys.stdout.write(html_footer)