3e527000af39a89d9003b35e5579b4584b909d67
[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 #          Sergey Satskiy <sergey.satskiy@gmail.com>
24 #
25 # Inspired by diff2html.rb from Dave Burt <dave (at) burt.id.au>
26 # (mainly for html theme)
27 #
28 # TODO:
29 # - The sane function currently mashes non-ASCII characters to "."
30 #   Instead be clever and convert to something like "xF0" 
31 #   (the hex value), and mark with a <span>.  Even more clever:
32 #   Detect if the character is "printable" for whatever definition,
33 #   and display those directly.
34
35
36 import sys, re, htmlentitydefs, getopt, StringIO
37
38 # minimum line size, we add a zero-sized breakable space every
39 # LINESIZE characters
40 linesize = 20
41 tabsize = 8
42 show_CR = False
43
44
45 html_hdr = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
46             <html><head>
47                 <meta name="generator" content="diff2html.rb" />
48                 <title>HTML Diff</title>
49                 <style>
50                         table { border:0px; border-collapse:collapse; width: 100%; font-size:0.75em; font-family: Lucida Console, monospace }
51                         td.line { color:#8080a0 }
52                         th { background: black; color: white }
53                         tr.diffunmodified td { background: #D0D0E0 }
54                         tr.diffhunk td { background: #A0A0A0 }
55                         tr.diffadded td { background: #CCFFCC }
56                         tr.diffdeleted td { background: #FFCCCC }
57                         tr.diffchanged td { background: #FFFFA0 }
58                         span.diffchanged2 { background: #E0C880 }
59                         span.diffponct { color: #B08080 }
60                         tr.diffmisc td {}
61                         tr.diffseparator td {}
62                 </style>
63                 </head>
64                 <body>
65 """
66
67 html_footer = """
68 </body></html>
69 """
70
71 table_hdr = """
72                 <table class="diff">
73 """
74
75 table_footer = """
76 </table>
77 """
78
79 DIFFON = "\x01"
80 DIFFOFF = "\x02"
81
82 buf = []
83 add_cpt, del_cpt = 0, 0
84 line1, line2 = 0, 0
85 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
86
87
88 # Characters we're willing to word wrap on
89 WORDBREAK = " \t;.,/):"
90
91 def sane(x):
92     r = ""
93     for i in x:
94         j = ord(i)
95         if i not in ['\t', '\n'] and ((j < 32) or (j >= 127)):
96             r = r + "."
97         else:
98             r = r + i
99     return r
100
101 def linediff(s, t):
102     if len(s):
103         s = str(reduce(lambda x, y:x+y, [ sane(c) for c in s ]))
104     if len(t):
105         t = str(reduce(lambda x, y:x+y, [ sane(c) for c in t ]))
106
107     m, n = len(s), len(t)
108     d = [[(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             while True:
312                 l = input_file.readline()
313                 m = re.match('^\+\+\+ ([^\s]*)', l)
314                 if m:
315                     file2 = m.groups()[0]
316                     break
317             add_filename(file1, file2, output_file)
318             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
319             continue
320
321         m = re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
322         if m:
323             empty_buffer(output_file)
324             hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
325             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
326             line1, line2 = hunk_off1, hunk_off2
327             add_hunk(output_file, show_hunk_infos)
328             continue
329
330         if hunk_size1 == 0 and hunk_size2 == 0:
331             empty_buffer(output_file)
332             add_comment(l, output_file)
333             continue
334
335         if re.match("^\+", l):
336             add_cpt += 1
337             hunk_size2 -= 1
338             buf.append((None, l[1:]))
339             continue
340
341         if re.match("^\-", l):
342             del_cpt += 1
343             hunk_size1 -= 1
344             buf.append((l[1:], None))
345             continue
346
347         if re.match("^\ ", l) and hunk_size1 and hunk_size2:
348             empty_buffer(output_file)
349             hunk_size1 -= 1
350             hunk_size2 -= 1
351             buf.append((l[1:], l[1:]))
352             continue
353
354         empty_buffer(output_file)
355         add_comment(l, output_file)
356
357     empty_buffer(output_file)
358     output_file.write(table_footer)
359     if not exclude_headers:
360         output_file.write(html_footer)
361
362
363 def usage():
364     print '''
365 diff2html.py [-i file] [-o file] [-x]
366 diff2html.py -h
367
368 Transform a unified diff from stdin to a colored side-by-side HTML
369 page on stdout.
370
371    -i file     set input file, else use stdin
372    -o file     set output file, else use stdout
373    -x          exclude html header and footer
374    -t tabsize  set tab size (default 8)
375    -l linesize set maximum line size is there is no word break (default 20)
376    -r          show \\r characters
377    -k          show hunk infos
378    -h          show help and exit
379 '''
380
381 def main():
382     global linesize, tabsize
383     global show_CR
384
385     input_file = sys.stdin
386     output_file = sys.stdout
387
388     exclude_headers = False
389     show_hunk_infos = False
390
391     try:
392         opts, args = getopt.getopt(sys.argv[1:], "hi:o:xt:l:rk",
393                                    ["help",  "input=", "output=",
394                                     "exclude-html-headers", "tabsize=",
395                                     "linesize=", "show-cr", "show-hunk-infos"])
396     except getopt.GetoptError, err:
397         print str(err) # will print something like "option -a not recognized"
398         usage()
399         sys.exit(2)
400     verbose = False
401     for o, a in opts:
402         if o in ("-h", "--help"):
403             usage()
404             sys.exit()
405         elif o in ("-i", "--input"):
406             input_file = open(a, "r")
407         elif o in ("-o", "--output"):
408             output_file = open(a, "w")
409         elif o in ("-x", "--exclude-html-headers"):
410             exclude_headers = True
411         elif o in ("-t", "--tabsize"):
412             tabsize = int(a)
413         elif o in ("-l", "--linesize"):
414             linesize = int(a)
415         elif o in ("-r", "--show-cr"):
416             show_CR = True
417         elif o in ("-k", "--show-hunk-infos"):
418             show_hunk_infos = True
419         else:
420             assert False, "unhandled option"
421     parse_input(input_file, output_file,
422                 exclude_headers, show_hunk_infos)
423
424 def parse_from_memory(txt, exclude_headers, show_hunk_infos):
425     " Parses diff from memory and returns a string with html "
426     input_stream = StringIO.StringIO(txt)
427     output_stream = StringIO.StringIO()
428     parse_input(input_stream, output_stream, exclude_headers, show_hunk_infos)
429     return output_stream.getvalue()
430
431
432 if __name__ == "__main__":
433     main()