cosmetic: rename {in,out}putfile to {in,out}put_file
[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 input_file = sys.stdin
42 output_file = sys.stdout
43 exclude_headers = False
44 show_CR = False
45 show_hunk_infos = False
46
47
48 html_hdr = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
49             <html><head>
50                 <meta name="generator" content="diff2html.rb" />
51                 <title>HTML Diff</title>
52                 <style>
53                         table { border:0px; border-collapse:collapse; width: 100%; font-size:0.75em; font-family: Lucida Console, monospace }
54                         td.line { color:#8080a0 }
55                         th { background: black; color: white }
56                         tr.diffunmodified td { background: #D0D0E0 }
57                         tr.diffhunk td { background: #A0A0A0 }
58                         tr.diffadded td { background: #CCFFCC }
59                         tr.diffdeleted td { background: #FFCCCC }
60                         tr.diffchanged td { background: #FFFFA0 }
61                         span.diffchanged2 { background: #E0C880 }
62                         span.diffponct { color: #B08080 }
63                         tr.diffmisc td {}
64                         tr.diffseparator td {}
65                 </style>
66                 </head>
67                 <body>
68 """
69
70 html_footer = """
71 </body></html>
72 """
73
74 table_hdr = """
75                 <table class="diff">
76 """
77
78 table_footer = """
79 </table>
80 """
81
82 DIFFON = "\x01"
83 DIFFOFF = "\x02"
84
85 buf = []
86 add_cpt, del_cpt = 0, 0
87 line1, line2 = 0, 0
88 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
89
90
91 # Characters we're willing to word wrap on
92 WORDBREAK = " \t;.,/):"
93
94 def sane(x):
95     r = ""
96     for i in x:
97         j = ord(i)
98         if i not in ['\t', '\n'] and ((j < 32) or (j >= 127)):
99             r = r + "."
100         else:
101             r = r + i
102     return r
103
104 def linediff(s, t):
105     if len(s):
106         s = str(reduce(lambda x, y:x+y, [ sane(c) for c in s ]))
107     if len(t):
108         t = str(reduce(lambda x, y:x+y, [ sane(c) for c in t ]))
109
110     m, n = len(s), len(t)
111     d = [[(0, 0) for i in range(n+1)] for i in range(m+1)]
112     x = [[(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 = ""
171     l=[]
172     for c in s:
173         # used by diffs
174         if c == DIFFON:
175             t += '<span class="diffchanged2">'
176         elif c == DIFFOFF:
177             t += "</span>"
178
179         # special html chars
180         elif htmlentitydefs.codepoint2name.has_key(ord(c)):
181             t += "&%s;" % (htmlentitydefs.codepoint2name[ord(c)])
182             i += 1
183
184         # special highlighted chars
185         elif c == "\t" and ponct == 1:
186             n = tabsize-(i%tabsize)
187             if n == 0:
188                 n = tabsize
189             t += ('<span class="diffponct">&raquo;</span>'+'&nbsp;'*(n-1))
190         elif c == " " and ponct == 1:
191             t += '<span class="diffponct">&middot;</span>'
192         elif c == "\n" and ponct == 1:
193             if show_CR:
194                 t += '<span class="diffponct">\</span>'
195         else:
196             t += c
197             i += 1
198
199         if linesize and (WORDBREAK.count(c) == 1):
200             t += '&#8203;'
201             i = 0
202         if linesize and i > linesize:
203             i = 0
204             t += "&#8203;"
205
206     return t
207
208
209 def add_comment(s):
210     output_file.write('<tr class="diffmisc"><td colspan="4">%s</td></tr>\n'%convert(s))
211
212 def add_filename(f1, f2):
213     output_file.write("<tr><th colspan='2'>%s</th>"%convert(f1, linesize=linesize))
214     output_file.write("<th colspan='2'>%s</th></tr>\n"%convert(f2, linesize=linesize))
215
216 def add_hunk():
217     global hunk_off1, hunk_size1, hunk_off2, hunk_size2
218     global show_hunk_infos
219     if show_hunk_infos:
220         output_file.write('<tr class="diffhunk"><td colspan="2">Offset %d, %d lines modified</td>'%(hunk_off1, hunk_size1))
221         output_file.write('<td colspan="2">Offset %d, %d lines modified</td></tr>\n'%(hunk_off2, hunk_size2))
222     else:
223         # &#8942; - vertical ellipsis
224         output_file.write('<tr class="diffhunk"><td colspan="2">&#8942;</td><td colspan="2">&#8942;</td></tr>')
225
226
227 def add_line(s1, s2):
228     global line1
229     global line2
230
231     if s1 == None and s2 == None:
232         type_name = "unmodified"
233     elif s1 == None or s1 == "":
234         type_name = "added"
235     elif s2 == None or s1 == "":
236         type_name = "deleted"
237     elif s1 == s2:
238         type_name = "unmodified"
239     else:
240         type_name = "changed"
241         s1, s2 = linediff(s1, s2)
242
243     output_file.write('<tr class="diff%s">' % type_name)
244     if s1 != None and s1 != "":
245         output_file.write('<td class="diffline">%d </td>' % line1)
246         output_file.write('<td class="diffpresent">')
247         output_file.write(convert(s1, linesize=linesize, ponct=1))
248         output_file.write('</td>')
249     else:
250         s1 = ""
251         output_file.write('<td colspan="2"> </td>')
252
253     if s2 != None and s2 != "":
254         output_file.write('<td class="diffline">%d </td>'%line2)
255         output_file.write('<td class="diffpresent">')
256         output_file.write(convert(s2, linesize=linesize, ponct=1))
257         output_file.write('</td>')
258     else:
259         s2 = ""
260         output_file.write('<td colspan="2"></td>')
261
262     output_file.write('</tr>\n')
263
264     if s1 != "":
265         line1 += 1
266     if s2 != "":
267         line2 += 1
268
269
270 def empty_buffer():
271     global buf
272     global add_cpt
273     global del_cpt
274
275     if del_cpt == 0 or add_cpt == 0:
276         for l in buf:
277             add_line(l[0], l[1])
278
279     elif del_cpt != 0 and add_cpt != 0:
280         l0, l1 = [], []
281         for l in buf:
282             if l[0] != None:
283                 l0.append(l[0])
284             if l[1] != None:
285                 l1.append(l[1])
286         max_len = (len(l0) > len(l1)) and len(l0) or len(l1)
287         for i in range(max_len):
288             s0, s1 = "", ""
289             if i < len(l0):
290                 s0 = l0[i]
291             if i < len(l1):
292                 s1 = l1[i]
293             add_line(s0, s1)
294
295     add_cpt, del_cpt = 0, 0
296     buf = []
297
298
299 def parse_input():
300     global buf, 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)
306     output_file.write(table_hdr)
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()
316             file1 = m.groups()[0]
317             l = input_file.readline()
318             m = re.match('^\+\+\+ ([^\s]*)', l)
319             if m:
320                 file2 = m.groups()[0]
321             add_filename(file1, file2)
322             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
323             continue
324
325         m = re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
326         if m:
327             empty_buffer()
328             hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
329             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
330             line1, line2 = hunk_off1, hunk_off2
331             add_hunk()
332             continue
333
334         if hunk_size1 == 0 and hunk_size2 == 0:
335             empty_buffer()
336             add_comment(l)
337             continue
338
339         if re.match("^\+", l):
340             add_cpt += 1
341             hunk_size2 -= 1
342             buf.append((None, l[1:]))
343             continue
344
345         if re.match("^\-", l):
346             del_cpt += 1
347             hunk_size1 -= 1
348             buf.append((l[1:], None))
349             continue
350
351         if re.match("^\ ", l) and hunk_size1 and hunk_size2:
352             empty_buffer()
353             hunk_size1 -= 1
354             hunk_size2 -= 1
355             buf.append((l[1:], l[1:]))
356             continue
357
358         empty_buffer()
359         add_comment(l)
360
361     empty_buffer()
362     output_file.write(table_footer)
363     if not exclude_headers:
364         output_file.write(html_footer)
365
366
367 def usage():
368     print '''
369 diff2html.py [-i file] [-o file] [-x]
370 diff2html.py -h
371
372 Transform a unified diff from stdin to a colored side-by-side HTML
373 page on stdout.
374
375    -i file     set input file, else use stdin
376    -o file     set output file, else use stdout
377    -x          exclude html header and footer
378    -t tabsize  set tab size (default 8)
379    -l linesize set maximum line size is there is no word break (default 20)
380    -r          show \\r characters
381    -k          show hunk infos
382    -h          show help and exit
383 '''
384
385 def main():
386     global linesize, tabsize
387     global input_file, output_file
388     global exclude_headers, show_CR, show_hunk_infos
389
390     try:
391         opts, args = getopt.getopt(sys.argv[1:], "hi:o:xt:l:rk",
392                                    ["help",  "input=", "output=",
393                                     "exclude-html-headers", "tabsize=",
394                                     "linesize=", "show-cr", "show-hunk-infos"])
395     except getopt.GetoptError, err:
396         print str(err) # will print something like "option -a not recognized"
397         usage()
398         sys.exit(2)
399     output = None
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()
422
423 if __name__ == "__main__":
424     main()