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