allow to be called with strings instead of IO files
[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     x = [[(0, 0) for i in range(n+1)] for i in range(m+1)]
110
111
112     d[0][0] = (0, (0, 0))
113     for i in range(m+1)[1:]:
114         d[i][0] = (i,(i-1, 0))
115     for j in range(n+1)[1:]:
116         d[0][j] = (j,(0, j-1))
117
118     for i in range(m+1)[1:]:
119         for j in range(n+1)[1:]:
120             if s[i-1] == t[j-1]:
121                 cost = 0
122             else:
123                 cost = 1
124             d[i][j] = min((d[i-1][j][0] + 1, (i-1, j)),
125                           (d[i][j-1][0] + 1, (i, j-1)),
126                           (d[i-1][j-1][0] + cost, (i-1, j-1)))
127
128     l = []
129     coord = (m, n)
130     while coord != (0, 0):
131         l.insert(0, coord)
132         x, y = coord
133         coord = d[x][y][1]
134
135     l1 = []
136     l2 = []
137
138     for coord in l:
139         cx, cy = coord
140         child_val = d[cx][cy][0]
141
142         father_coord = d[cx][cy][1]
143         fx, fy = father_coord
144         father_val = d[fx][fy][0]
145
146         diff = (cx-fx, cy-fy)
147
148         if diff == (0, 1):
149             l1.append("")
150             l2.append(DIFFON + t[fy] + DIFFOFF)
151         elif diff == (1, 0):
152             l1.append(DIFFON + s[fx] + DIFFOFF)
153             l2.append("")
154         elif child_val-father_val == 1:
155             l1.append(DIFFON + s[fx] + DIFFOFF)
156             l2.append(DIFFON + t[fy] + DIFFOFF)
157         else:
158             l1.append(s[fx])
159             l2.append(t[fy])
160
161     r1, r2 = (reduce(lambda x, y:x+y, l1), reduce(lambda x, y:x+y, l2))
162     return r1, r2
163
164
165 def convert(s, linesize=0, ponct=0):
166     i = 0
167     t = ""
168     for c in s:
169         # used by diffs
170         if c == DIFFON:
171             t += '<span class="diffchanged2">'
172         elif c == DIFFOFF:
173             t += "</span>"
174
175         # special html chars
176         elif htmlentitydefs.codepoint2name.has_key(ord(c)):
177             t += "&%s;" % (htmlentitydefs.codepoint2name[ord(c)])
178             i += 1
179
180         # special highlighted chars
181         elif c == "\t" and ponct == 1:
182             n = tabsize-(i%tabsize)
183             if n == 0:
184                 n = tabsize
185             t += ('<span class="diffponct">&raquo;</span>'+'&nbsp;'*(n-1))
186         elif c == " " and ponct == 1:
187             t += '<span class="diffponct">&middot;</span>'
188         elif c == "\n" and ponct == 1:
189             if show_CR:
190                 t += '<span class="diffponct">\</span>'
191         else:
192             t += c
193             i += 1
194
195         if linesize and (WORDBREAK.count(c) == 1):
196             t += '&#8203;'
197             i = 0
198         if linesize and i > linesize:
199             i = 0
200             t += "&#8203;"
201
202     return t
203
204
205 def add_comment(s, output_file):
206     output_file.write('<tr class="diffmisc"><td colspan="4">%s</td></tr>\n'%convert(s))
207
208 def add_filename(f1, f2, output_file):
209     output_file.write("<tr><th colspan='2'>%s</th>"%convert(f1, linesize=linesize))
210     output_file.write("<th colspan='2'>%s</th></tr>\n"%convert(f2, linesize=linesize))
211
212 def add_hunk(output_file, show_hunk_infos):
213     if show_hunk_infos:
214         output_file.write('<tr class="diffhunk"><td colspan="2">Offset %d, %d lines modified</td>'%(hunk_off1, hunk_size1))
215         output_file.write('<td colspan="2">Offset %d, %d lines modified</td></tr>\n'%(hunk_off2, hunk_size2))
216     else:
217         # &#8942; - vertical ellipsis
218         output_file.write('<tr class="diffhunk"><td colspan="2">&#8942;</td><td colspan="2">&#8942;</td></tr>')
219
220
221 def add_line(s1, s2, output_file):
222     global line1
223     global line2
224
225     if s1 == None and s2 == None:
226         type_name = "unmodified"
227     elif s1 == None or s1 == "":
228         type_name = "added"
229     elif s2 == None or s1 == "":
230         type_name = "deleted"
231     elif s1 == s2:
232         type_name = "unmodified"
233     else:
234         type_name = "changed"
235         s1, s2 = linediff(s1, s2)
236
237     output_file.write('<tr class="diff%s">' % type_name)
238     if s1 != None and s1 != "":
239         output_file.write('<td class="diffline">%d </td>' % line1)
240         output_file.write('<td class="diffpresent">')
241         output_file.write(convert(s1, linesize=linesize, ponct=1))
242         output_file.write('</td>')
243     else:
244         s1 = ""
245         output_file.write('<td colspan="2"> </td>')
246
247     if s2 != None and s2 != "":
248         output_file.write('<td class="diffline">%d </td>'%line2)
249         output_file.write('<td class="diffpresent">')
250         output_file.write(convert(s2, linesize=linesize, ponct=1))
251         output_file.write('</td>')
252     else:
253         s2 = ""
254         output_file.write('<td colspan="2"></td>')
255
256     output_file.write('</tr>\n')
257
258     if s1 != "":
259         line1 += 1
260     if s2 != "":
261         line2 += 1
262
263
264 def empty_buffer(output_file):
265     global buf
266     global add_cpt
267     global del_cpt
268
269     if del_cpt == 0 or add_cpt == 0:
270         for l in buf:
271             add_line(l[0], l[1], output_file)
272
273     elif del_cpt != 0 and add_cpt != 0:
274         l0, l1 = [], []
275         for l in buf:
276             if l[0] != None:
277                 l0.append(l[0])
278             if l[1] != None:
279                 l1.append(l[1])
280         max_len = (len(l0) > len(l1)) and len(l0) or len(l1)
281         for i in range(max_len):
282             s0, s1 = "", ""
283             if i < len(l0):
284                 s0 = l0[i]
285             if i < len(l1):
286                 s1 = l1[i]
287             add_line(s0, s1, output_file)
288
289     add_cpt, del_cpt = 0, 0
290     buf = []
291
292
293 def parse_input(input_file, output_file,
294                 exclude_headers, show_hunk_infos):
295     global add_cpt, del_cpt
296     global line1, line2
297     global hunk_off1, hunk_size1, hunk_off2, hunk_size2
298
299     if not exclude_headers:
300         output_file.write(html_hdr)
301     output_file.write(table_hdr)
302
303     while True:
304         l = input_file.readline()
305         if l == "":
306             break
307
308         m = re.match('^--- ([^\s]*)', l)
309         if m:
310             empty_buffer(output_file)
311             file1 = m.groups()[0]
312             while True:
313                 l = input_file.readline()
314                 m = re.match('^\+\+\+ ([^\s]*)', l)
315                 if m:
316                     file2 = m.groups()[0]
317                     break
318             add_filename(file1, file2, output_file)
319             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
320             continue
321
322         m = re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
323         if m:
324             empty_buffer(output_file)
325             hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
326             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
327             line1, line2 = hunk_off1, hunk_off2
328             add_hunk(output_file, show_hunk_infos)
329             continue
330
331         if hunk_size1 == 0 and hunk_size2 == 0:
332             empty_buffer(output_file)
333             add_comment(l, output_file)
334             continue
335
336         if re.match("^\+", l):
337             add_cpt += 1
338             hunk_size2 -= 1
339             buf.append((None, l[1:]))
340             continue
341
342         if re.match("^\-", l):
343             del_cpt += 1
344             hunk_size1 -= 1
345             buf.append((l[1:], None))
346             continue
347
348         if re.match("^\ ", l) and hunk_size1 and hunk_size2:
349             empty_buffer(output_file)
350             hunk_size1 -= 1
351             hunk_size2 -= 1
352             buf.append((l[1:], l[1:]))
353             continue
354
355         empty_buffer(output_file)
356         add_comment(l, output_file)
357
358     empty_buffer(output_file)
359     output_file.write(table_footer)
360     if not exclude_headers:
361         output_file.write(html_footer)
362
363
364 def usage():
365     print '''
366 diff2html.py [-i file] [-o file] [-x]
367 diff2html.py -h
368
369 Transform a unified diff from stdin to a colored side-by-side HTML
370 page on stdout.
371
372    -i file     set input file, else use stdin
373    -o file     set output file, else use stdout
374    -x          exclude html header and footer
375    -t tabsize  set tab size (default 8)
376    -l linesize set maximum line size is there is no word break (default 20)
377    -r          show \\r characters
378    -k          show hunk infos
379    -h          show help and exit
380 '''
381
382 def main():
383     global linesize, tabsize
384     global show_CR
385
386     input_file = sys.stdin
387     output_file = sys.stdout
388
389     exclude_headers = False
390     show_hunk_infos = False
391
392     try:
393         opts, args = getopt.getopt(sys.argv[1:], "hi:o:xt:l:rk",
394                                    ["help",  "input=", "output=",
395                                     "exclude-html-headers", "tabsize=",
396                                     "linesize=", "show-cr", "show-hunk-infos"])
397     except getopt.GetoptError, err:
398         print str(err) # will print something like "option -a not recognized"
399         usage()
400         sys.exit(2)
401     verbose = False
402     for o, a in opts:
403         if o in ("-h", "--help"):
404             usage()
405             sys.exit()
406         elif o in ("-i", "--input"):
407             input_file = open(a, "r")
408         elif o in ("-o", "--output"):
409             output_file = open(a, "w")
410         elif o in ("-x", "--exclude-html-headers"):
411             exclude_headers = True
412         elif o in ("-t", "--tabsize"):
413             tabsize = int(a)
414         elif o in ("-l", "--linesize"):
415             linesize = int(a)
416         elif o in ("-r", "--show-cr"):
417             show_CR = True
418         elif o in ("-k", "--show-hunk-infos"):
419             show_hunk_infos = True
420         else:
421             assert False, "unhandled option"
422     parse_input(input_file, output_file,
423                 exclude_headers, show_hunk_infos)
424
425 def parse_from_memory(txt, exclude_headers, show_hunk_infos):
426     " Parses diff from memory and returns a string with html "
427     stream = StringIO.StringIO(txt)
428     parse_input(stream, stream, exclude_headers, show_hunk_infos)
429     return stream.buf
430
431 if __name__ == "__main__":
432     main()