5704270b6e7c06a35bb4bdee0b2137c4ba9f2572
[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 # Authors: Olivier MATZ <zer0@droids-corp.org>
22 #          Alan De Smet <adesmet@cs.wisc.edu>
23 #
24 # Inspired by diff2html.rb from Dave Burt <dave (at) burt.id.au>
25 # (mainly for html theme)
26 #
27 # TODO:
28 # - The sane function currently mashes non-ASCII characters to "."
29 #   Instead be clever and convert to something like "xF0" 
30 #   (the hex value), and mark with a <span>.  Even more clever:
31 #   Detect if the character is "printable" for whatever definition,
32 #   and display those directly.
33
34
35 import sys, re, htmlentitydefs, getopt
36
37 # minimum line size, we add a zero-sized breakable space every
38 # LINESIZE characters
39 linesize = 20
40 tabsize = 8
41 show_CR = False
42
43
44 html_hdr = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
45             <html><head>
46                 <meta name="generator" content="diff2html.rb" />
47                 <title>HTML Diff</title>
48                 <style>
49                         table { border:0px; border-collapse:collapse; width: 100%; font-size:0.75em; font-family: Lucida Console, monospace }
50                         td.line { color:#8080a0 }
51                         th { background: black; color: white }
52                         tr.diffunmodified td { background: #D0D0E0 }
53                         tr.diffhunk td { background: #A0A0A0 }
54                         tr.diffadded td { background: #CCFFCC }
55                         tr.diffdeleted td { background: #FFCCCC }
56                         tr.diffchanged td { background: #FFFFA0 }
57                         span.diffchanged2 { background: #E0C880 }
58                         span.diffponct { color: #B08080 }
59                         tr.diffmisc td {}
60                         tr.diffseparator td {}
61                 </style>
62                 </head>
63                 <body>
64 """
65
66 html_footer = """
67 </body></html>
68 """
69
70 table_hdr = """
71                 <table class="diff">
72 """
73
74 table_footer = """
75 </table>
76 """
77
78 DIFFON = "\x01"
79 DIFFOFF = "\x02"
80
81 buf = []
82 add_cpt, del_cpt = 0, 0
83 line1, line2 = 0, 0
84 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
85
86
87 # Characters we're willing to word wrap on
88 WORDBREAK = " \t;.,/):"
89
90 def sane(x):
91     r = ""
92     for i in x:
93         j = ord(i)
94         if i not in ['\t', '\n'] and ((j < 32) or (j >= 127)):
95             r = r + "."
96         else:
97             r = r + i
98     return r
99
100 def linediff(s, t):
101     if len(s):
102         s = str(reduce(lambda x, y:x+y, [ sane(c) for c in s ]))
103     if len(t):
104         t = str(reduce(lambda x, y:x+y, [ sane(c) for c in t ]))
105
106     m, n = len(s), len(t)
107     d = [[(0, 0) for i in range(n+1)] for i in range(m+1)]
108     x = [[(0, 0) for i in range(n+1)] for i in range(m+1)]
109
110
111     d[0][0] = (0, (0, 0))
112     for i in range(m+1)[1:]:
113         d[i][0] = (i,(i-1, 0))
114     for j in range(n+1)[1:]:
115         d[0][j] = (j,(0, j-1))
116
117     for i in range(m+1)[1:]:
118         for j in range(n+1)[1:]:
119             if s[i-1] == t[j-1]:
120                 cost = 0
121             else:
122                 cost = 1
123             d[i][j] = min((d[i-1][j][0] + 1, (i-1, j)),
124                           (d[i][j-1][0] + 1, (i, j-1)),
125                           (d[i-1][j-1][0] + cost, (i-1, j-1)))
126
127     l = []
128     coord = (m, n)
129     while coord != (0, 0):
130         l.insert(0, coord)
131         x, y = coord
132         coord = d[x][y][1]
133
134     l1 = []
135     l2 = []
136
137     for coord in l:
138         cx, cy = coord
139         child_val = d[cx][cy][0]
140
141         father_coord = d[cx][cy][1]
142         fx, fy = father_coord
143         father_val = d[fx][fy][0]
144
145         diff = (cx-fx, cy-fy)
146
147         if diff == (0, 1):
148             l1.append("")
149             l2.append(DIFFON + t[fy] + DIFFOFF)
150         elif diff == (1, 0):
151             l1.append(DIFFON + s[fx] + DIFFOFF)
152             l2.append("")
153         elif child_val-father_val == 1:
154             l1.append(DIFFON + s[fx] + DIFFOFF)
155             l2.append(DIFFON + t[fy] + DIFFOFF)
156         else:
157             l1.append(s[fx])
158             l2.append(t[fy])
159
160     r1, r2 = (reduce(lambda x, y:x+y, l1), reduce(lambda x, y:x+y, l2))
161     return r1, r2
162
163
164 def convert(s, linesize=0, ponct=0):
165     i = 0
166     t = ""
167     for c in s:
168         # used by diffs
169         if c == DIFFON:
170             t += '<span class="diffchanged2">'
171         elif c == DIFFOFF:
172             t += "</span>"
173
174         # special html chars
175         elif htmlentitydefs.codepoint2name.has_key(ord(c)):
176             t += "&%s;" % (htmlentitydefs.codepoint2name[ord(c)])
177             i += 1
178
179         # special highlighted chars
180         elif c == "\t" and ponct == 1:
181             n = tabsize-(i%tabsize)
182             if n == 0:
183                 n = tabsize
184             t += ('<span class="diffponct">&raquo;</span>'+'&nbsp;'*(n-1))
185         elif c == " " and ponct == 1:
186             t += '<span class="diffponct">&middot;</span>'
187         elif c == "\n" and ponct == 1:
188             if show_CR:
189                 t += '<span class="diffponct">\</span>'
190         else:
191             t += c
192             i += 1
193
194         if linesize and (WORDBREAK.count(c) == 1):
195             t += '&#8203;'
196             i = 0
197         if linesize and i > linesize:
198             i = 0
199             t += "&#8203;"
200
201     return t
202
203
204 def add_comment(s, output_file):
205     output_file.write('<tr class="diffmisc"><td colspan="4">%s</td></tr>\n'%convert(s))
206
207 def add_filename(f1, f2, output_file):
208     output_file.write("<tr><th colspan='2'>%s</th>"%convert(f1, linesize=linesize))
209     output_file.write("<th colspan='2'>%s</th></tr>\n"%convert(f2, linesize=linesize))
210
211 def add_hunk(output_file, show_hunk_infos):
212     if show_hunk_infos:
213         output_file.write('<tr class="diffhunk"><td colspan="2">Offset %d, %d lines modified</td>'%(hunk_off1, hunk_size1))
214         output_file.write('<td colspan="2">Offset %d, %d lines modified</td></tr>\n'%(hunk_off2, hunk_size2))
215     else:
216         # &#8942; - vertical ellipsis
217         output_file.write('<tr class="diffhunk"><td colspan="2">&#8942;</td><td colspan="2">&#8942;</td></tr>')
218
219
220 def add_line(s1, s2, output_file):
221     global line1
222     global line2
223
224     if s1 == None and s2 == None:
225         type_name = "unmodified"
226     elif s1 == None or s1 == "":
227         type_name = "added"
228     elif s2 == None or s1 == "":
229         type_name = "deleted"
230     elif s1 == s2:
231         type_name = "unmodified"
232     else:
233         type_name = "changed"
234         s1, s2 = linediff(s1, s2)
235
236     output_file.write('<tr class="diff%s">' % type_name)
237     if s1 != None and s1 != "":
238         output_file.write('<td class="diffline">%d </td>' % line1)
239         output_file.write('<td class="diffpresent">')
240         output_file.write(convert(s1, linesize=linesize, ponct=1))
241         output_file.write('</td>')
242     else:
243         s1 = ""
244         output_file.write('<td colspan="2"> </td>')
245
246     if s2 != None and s2 != "":
247         output_file.write('<td class="diffline">%d </td>'%line2)
248         output_file.write('<td class="diffpresent">')
249         output_file.write(convert(s2, linesize=linesize, ponct=1))
250         output_file.write('</td>')
251     else:
252         s2 = ""
253         output_file.write('<td colspan="2"></td>')
254
255     output_file.write('</tr>\n')
256
257     if s1 != "":
258         line1 += 1
259     if s2 != "":
260         line2 += 1
261
262
263 def empty_buffer(output_file):
264     global buf
265     global add_cpt
266     global del_cpt
267
268     if del_cpt == 0 or add_cpt == 0:
269         for l in buf:
270             add_line(l[0], l[1], output_file)
271
272     elif del_cpt != 0 and add_cpt != 0:
273         l0, l1 = [], []
274         for l in buf:
275             if l[0] != None:
276                 l0.append(l[0])
277             if l[1] != None:
278                 l1.append(l[1])
279         max_len = (len(l0) > len(l1)) and len(l0) or len(l1)
280         for i in range(max_len):
281             s0, s1 = "", ""
282             if i < len(l0):
283                 s0 = l0[i]
284             if i < len(l1):
285                 s1 = l1[i]
286             add_line(s0, s1, output_file)
287
288     add_cpt, del_cpt = 0, 0
289     buf = []
290
291
292 def parse_input(input_file, output_file,
293                 exclude_headers, show_hunk_infos):
294     global add_cpt, del_cpt
295     global line1, line2
296     global hunk_off1, hunk_size1, hunk_off2, hunk_size2
297
298     if not exclude_headers:
299         output_file.write(html_hdr)
300     output_file.write(table_hdr)
301
302     while True:
303         l = input_file.readline()
304         if l == "":
305             break
306
307         m = re.match('^--- ([^\s]*)', l)
308         if m:
309             empty_buffer(output_file)
310             file1 = m.groups()[0]
311             l = input_file.readline()
312             m = re.match('^\+\+\+ ([^\s]*)', l)
313             if m:
314                 file2 = m.groups()[0]
315             add_filename(file1, file2, output_file)
316             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
317             continue
318
319         m = re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
320         if m:
321             empty_buffer(output_file)
322             hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
323             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
324             line1, line2 = hunk_off1, hunk_off2
325             add_hunk(output_file, show_hunk_infos)
326             continue
327
328         if hunk_size1 == 0 and hunk_size2 == 0:
329             empty_buffer(output_file)
330             add_comment(l, output_file)
331             continue
332
333         if re.match("^\+", l):
334             add_cpt += 1
335             hunk_size2 -= 1
336             buf.append((None, l[1:]))
337             continue
338
339         if re.match("^\-", l):
340             del_cpt += 1
341             hunk_size1 -= 1
342             buf.append((l[1:], None))
343             continue
344
345         if re.match("^\ ", l) and hunk_size1 and hunk_size2:
346             empty_buffer(output_file)
347             hunk_size1 -= 1
348             hunk_size2 -= 1
349             buf.append((l[1:], l[1:]))
350             continue
351
352         empty_buffer(output_file)
353         add_comment(l, output_file)
354
355     empty_buffer(output_file)
356     output_file.write(table_footer)
357     if not exclude_headers:
358         output_file.write(html_footer)
359
360
361 def usage():
362     print '''
363 diff2html.py [-i file] [-o file] [-x]
364 diff2html.py -h
365
366 Transform a unified diff from stdin to a colored side-by-side HTML
367 page on stdout.
368
369    -i file     set input file, else use stdin
370    -o file     set output file, else use stdout
371    -x          exclude html header and footer
372    -t tabsize  set tab size (default 8)
373    -l linesize set maximum line size is there is no word break (default 20)
374    -r          show \\r characters
375    -k          show hunk infos
376    -h          show help and exit
377 '''
378
379 def main():
380     global linesize, tabsize
381     global show_CR
382
383     input_file = sys.stdin
384     output_file = sys.stdout
385
386     exclude_headers = False
387     show_hunk_infos = False
388
389     try:
390         opts, args = getopt.getopt(sys.argv[1:], "hi:o:xt:l:rk",
391                                    ["help",  "input=", "output=",
392                                     "exclude-html-headers", "tabsize=",
393                                     "linesize=", "show-cr", "show-hunk-infos"])
394     except getopt.GetoptError, err:
395         print str(err) # will print something like "option -a not recognized"
396         usage()
397         sys.exit(2)
398     output = None
399     verbose = False
400     for o, a in opts:
401         if o in ("-h", "--help"):
402             usage()
403             sys.exit()
404         elif o in ("-i", "--input"):
405             input_file = open(a, "r")
406         elif o in ("-o", "--output"):
407             output_file = open(a, "w")
408         elif o in ("-x", "--exclude-html-headers"):
409             exclude_headers = True
410         elif o in ("-t", "--tabsize"):
411             tabsize = int(a)
412         elif o in ("-l", "--linesize"):
413             linesize = int(a)
414         elif o in ("-r", "--show-cr"):
415             show_CR = True
416         elif o in ("-k", "--show-hunk-infos"):
417             show_hunk_infos = True
418         else:
419             assert False, "unhandled option"
420     parse_input(input_file, output_file,
421                 exclude_headers, show_hunk_infos)
422
423
424 if __name__ == "__main__":
425     main()