cosmetic: remove some global variables
[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     l=[]
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             l = input_file.readline()
313             m = re.match('^\+\+\+ ([^\s]*)', l)
314             if m:
315                 file2 = m.groups()[0]
316             add_filename(file1, file2, output_file)
317             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
318             continue
319
320         m = re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
321         if m:
322             empty_buffer(output_file)
323             hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
324             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
325             line1, line2 = hunk_off1, hunk_off2
326             add_hunk(output_file, show_hunk_infos)
327             continue
328
329         if hunk_size1 == 0 and hunk_size2 == 0:
330             empty_buffer(output_file)
331             add_comment(l, output_file)
332             continue
333
334         if re.match("^\+", l):
335             add_cpt += 1
336             hunk_size2 -= 1
337             buf.append((None, l[1:]))
338             continue
339
340         if re.match("^\-", l):
341             del_cpt += 1
342             hunk_size1 -= 1
343             buf.append((l[1:], None))
344             continue
345
346         if re.match("^\ ", l) and hunk_size1 and hunk_size2:
347             empty_buffer(output_file)
348             hunk_size1 -= 1
349             hunk_size2 -= 1
350             buf.append((l[1:], l[1:]))
351             continue
352
353         empty_buffer(output_file)
354         add_comment(l, output_file)
355
356     empty_buffer(output_file)
357     output_file.write(table_footer)
358     if not exclude_headers:
359         output_file.write(html_footer)
360
361
362 def usage():
363     print '''
364 diff2html.py [-i file] [-o file] [-x]
365 diff2html.py -h
366
367 Transform a unified diff from stdin to a colored side-by-side HTML
368 page on stdout.
369
370    -i file     set input file, else use stdin
371    -o file     set output file, else use stdout
372    -x          exclude html header and footer
373    -t tabsize  set tab size (default 8)
374    -l linesize set maximum line size is there is no word break (default 20)
375    -r          show \\r characters
376    -k          show hunk infos
377    -h          show help and exit
378 '''
379
380 def main():
381     global linesize, tabsize
382     global show_CR
383
384     input_file = sys.stdin
385     output_file = sys.stdout
386
387     exclude_headers = False
388     show_hunk_infos = False
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(input_file, output_file,
422                 exclude_headers, show_hunk_infos)
423
424
425 if __name__ == "__main__":
426     main()