first release
[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
27 import sys, re, htmlentitydefs
28
29 html_hdr="""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
30             <html><head>
31                 <meta name="generator" content="diff2html.rb" />
32                 <title>HTML Diff</title>
33                 <style>
34                         table { border:0px; border-collapse:collapse; width: 100%; font-size:0.75em; font-family: Lucida Console, monospace }
35                         td.line { color:#8080a0 }
36                         th { background: black; color: white }
37                         tr.unmodified td { background: #D0D0E0 }
38                         tr.hunk td { background: #A0A0A0 }
39                         tr.added td { background: #CCFFCC }
40                         tr.deleted td { background: #FFCCCC }
41                         tr.changed td { background: #FFFFA0 }
42                         span.changed2 { background: #E0C880 }
43                         span.ponct { color: #B08080 }
44                         tr.misc td {}
45                         tr.separator td {}
46                 </style>
47                 </head>
48                 <body>
49                 <table>
50 """
51
52 html_footer="""
53 </table></body></html>
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=8
68
69 def sane(x):
70     r=""
71     for i in x:
72         j = ord(i)
73         if i not in ['\t', '\n'] and ((j < 32) or (j >= 127)):
74             r=r+"."
75         else:
76             r=r+i
77     return r
78
79 def linediff(s, t):
80     if len(s):
81         s=str(reduce(lambda x,y:x+y, [ sane(c) for c in s ]))
82     if len(t):
83         t=str(reduce(lambda x,y:x+y, [ sane(c) for c in t ]))
84     
85     m,n = len(s), len(t)
86     d=[[(0,0) for i in range(n+1)] for i in range(m+1)]
87     x=[[(0,0) for i in range(n+1)] for i in range(m+1)]
88
89     
90     d[0][0] = (0, (0,0))
91     for i in range(m+1)[1:]:
92         d[i][0] = (i,(i-1,0))
93     for j in range(n+1)[1:]:
94         d[0][j] = (j,(0,j-1))
95
96     for i in range(m+1)[1:]:
97         for j in range(n+1)[1:]:
98             if s[i-1] == t[j-1]:
99                 cost = 0
100             else:
101                 cost = 1
102             d[i][j] = min((d[i-1][j][0] + 1, (i-1,j)),
103                           (d[i][j-1][0] + 1, (i,j-1)),
104                           (d[i-1][j-1][0] + cost, (i-1,j-1)))
105             
106     l=[]
107     coord = (m,n)
108     while coord != (0,0):
109         l.insert(0, coord)
110         x,y = coord
111         coord = d[x][y][1]
112
113     l1 = []
114     l2 = []
115
116     for coord in l:
117         cx,cy = coord
118         child_val = d[cx][cy][0]
119         
120         father_coord = d[cx][cy][1]
121         fx,fy = father_coord
122         father_val = d[fx][fy][0]
123
124         diff = (cx-fx, cy-fy)
125
126         if diff == (0,1):
127             l1.append("")
128             l2.append(DIFFON + t[fy] + DIFFOFF)
129         elif diff == (1,0):
130             l1.append(DIFFON + s[fx] + DIFFOFF)
131             l2.append("")
132         elif child_val-father_val == 1:
133             l1.append(DIFFON + s[fx] + DIFFOFF)
134             l2.append(DIFFON + t[fy] + DIFFOFF)
135         else:
136             l1.append(s[fx])
137             l2.append(t[fy])
138
139     r1,r2 = (reduce(lambda x,y:x+y, l1), reduce(lambda x,y:x+y, l2))
140     return r1,r2
141
142
143 def convert(s, linesize=0, ponct=0):
144     i=0
145     t=""
146     l=[]
147     for c in s:
148         # used by diffs
149         if c==DIFFON:
150             t += '<spanclass="changed2">'
151         elif c==DIFFOFF:
152             t += "</span>"
153
154         # special html chars
155         elif htmlentitydefs.codepoint2name.has_key(ord(c)):
156             t += "&%s;"%(htmlentitydefs.codepoint2name[ord(c)])
157             i += 1
158
159         # special highlighted chars
160         elif c=="\t" and ponct==1:
161             n = TAB-(i%TAB)
162             if n==0:
163                 n=TAB
164             t += ('<spanclass="ponct">&raquo;</span>'+'&nbsp;'*(n-1))
165             i += n
166         elif c=="\n" and ponct==1:
167             t += '<spanclass="ponct">\</span>'
168         else:
169             t += c
170             i += 1
171         if linesize and i>linesize:
172             i=0
173             t += "&#8203;"
174
175     if ponct==1:
176         t = t.replace(' ', '<spanclass="ponct">&middot;</span>')
177     t = t.replace("spanclass", "span class")
178         
179     return t
180
181
182 def add_comment(s):
183     sys.stdout.write('<tr class="misc"><td colspan="4">%s</td></tr>\n'%convert(s))
184
185 def add_filename(f1, f2):
186     sys.stdout.write("<tr><th colspan='2'>%s</th>"%convert(f1, linesize=LINESIZE))
187     sys.stdout.write("<th colspan='2'>%s</th></tr>\n"%convert(f2, linesize=LINESIZE))
188
189 def add_hunk():
190     global hunk_off1
191     global hunk_size1
192     global hunk_off2
193     global hunk_size2
194     sys.stdout.write('<tr class="hunk"><td colspan="2">Offset %d, %d lines modified</td>'%(hunk_off1, hunk_size1))
195     sys.stdout.write('<td colspan="2">Offset %d, %d lines modified</td></tr>\n'%(hunk_off2, hunk_size2))
196
197 def add_line(s1, s2):
198     global line1
199     global line2
200
201     if s1==None and s2==None:
202         type="unmodified"
203     elif s1==None:
204         type="added"
205     elif s2==None:
206         type="deleted"
207     elif s1==s2:
208         type="unmodified"
209     else:
210         type="changed"
211         s1,s2 = linediff(s1, s2)
212
213     sys.stdout.write('<tr class="%s">'%type)
214     if s1!=None and s1!="":
215         sys.stdout.write('<td class="line">%d </td>'%line1)
216         sys.stdout.write('<td>')
217         sys.stdout.write(convert(s1, linesize=LINESIZE, ponct=1))
218         sys.stdout.write('</td>')
219     else:
220         s1=""
221         sys.stdout.write('<td colspan="2"> </td>')
222     
223     if s2!=None and s2!="":
224         sys.stdout.write('<td class="line">%d </td>'%line2)
225         sys.stdout.write('<td>')
226         sys.stdout.write(convert(s2, linesize=LINESIZE, ponct=1))
227         sys.stdout.write('</td>')
228     else:
229         s2=""
230         sys.stdout.write('<td colspan="2"></td>')
231
232     sys.stdout.write('</tr>\n')
233
234     if s1!="":
235         line1 += 1
236     if s2!="":
237         line2 += 1
238
239
240 def empty_buffer():
241     global buffer
242     global add_cpt
243     global del_cpt
244
245     if del_cpt == 0 or add_cpt == 0:
246         for l in buffer:
247             add_line(l[0], l[1])
248
249     elif del_cpt != 0 and add_cpt != 0:
250         l0, l1 = [], []
251         for l in buffer:
252             if l[0] != None:
253                 l0.append(l[0])
254             if l[1] != None:
255                 l1.append(l[1])
256         max = (len(l0) > len(l1)) and len(l0) or len(l1)
257         for i in range(max):
258             s0, s1 = "", ""
259             if i<len(l0):
260                 s0 = l0[i]
261             if i<len(l1):
262                 s1 = l1[i]
263             add_line(s0, s1)
264         
265     add_cpt, del_cpt = 0,0
266     buffer = []
267
268
269
270 sys.stdout.write(html_hdr)
271
272 while True:
273     l=sys.stdin.readline()
274     if l=="":
275         break
276     
277     m=re.match('^--- ([^\s]*)', l)
278     if m:
279         empty_buffer()
280         file1=m.groups()[0]
281         l=sys.stdin.readline()
282         m=re.match('^\+\+\+ ([^\s]*)', l)
283         if m:
284             file2=m.groups()[0]
285         add_filename(file1, file2)
286         hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0,0,0,0
287         continue
288
289     m=re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
290     if m:
291         empty_buffer()
292         hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
293         hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
294         line1, line2 = hunk_off1, hunk_off2
295         add_hunk()
296         continue
297         
298     if hunk_size1 == 0 and hunk_size2 == 0:
299         empty_buffer()
300         add_comment(l)
301         continue
302
303     if re.match("^\+", l):
304         add_cpt += 1
305         hunk_size2 -= 1
306         buffer.append((None, l[1:]))
307         continue
308
309     if re.match("^\-", l):
310         del_cpt += 1
311         hunk_size1 -= 1
312         buffer.append((l[1:], None))
313         continue
314
315     if re.match("^\ ", l) and hunk_size1 and hunk_size2:
316         empty_buffer()
317         hunk_size1 -= 1
318         hunk_size2 -= 1
319         buffer.append((l[1:], l[1:]))
320         continue
321
322     empty_buffer()
323     add_comment(l)
324
325
326 empty_buffer()
327 sys.stdout.write(html_footer)