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.
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.
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
18 # Transform a unified diff from stdin to a colored
19 # side-by-side HTML page on stdout.
21 # Authors: Olivier MATZ <zer0@droids-corp.org>
22 # Alan De Smet <adesmet@cs.wisc.edu>
24 # Inspired by diff2html.rb from Dave Burt <dave (at) burt.id.au>
25 # (mainly for html theme)
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.
35 import sys, re, htmlentitydefs, getopt
37 # minimum line size, we add a zero-sized breakable space every
44 html_hdr = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
46 <meta name="generator" content="diff2html.rb" />
47 <title>HTML Diff</title>
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 }
60 tr.diffseparator td {}
82 add_cpt, del_cpt = 0, 0
84 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
87 # Characters we're willing to word wrap on
88 WORDBREAK = " \t;.,/):"
94 if i not in ['\t', '\n'] and ((j < 32) or (j >= 127)):
102 s = str(reduce(lambda x, y:x+y, [ sane(c) for c in s ]))
104 t = str(reduce(lambda x, y:x+y, [ sane(c) for c in t ]))
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)]
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))
117 for i in range(m+1)[1:]:
118 for j in range(n+1)[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)))
129 while coord != (0, 0):
139 child_val = d[cx][cy][0]
141 father_coord = d[cx][cy][1]
142 fx, fy = father_coord
143 father_val = d[fx][fy][0]
145 diff = (cx-fx, cy-fy)
149 l2.append(DIFFON + t[fy] + DIFFOFF)
151 l1.append(DIFFON + s[fx] + DIFFOFF)
153 elif child_val-father_val == 1:
154 l1.append(DIFFON + s[fx] + DIFFOFF)
155 l2.append(DIFFON + t[fy] + DIFFOFF)
160 r1, r2 = (reduce(lambda x, y:x+y, l1), reduce(lambda x, y:x+y, l2))
164 def convert(s, linesize=0, ponct=0):
170 t += '<span class="diffchanged2">'
175 elif htmlentitydefs.codepoint2name.has_key(ord(c)):
176 t += "&%s;" % (htmlentitydefs.codepoint2name[ord(c)])
179 # special highlighted chars
180 elif c == "\t" and ponct == 1:
181 n = tabsize-(i%tabsize)
184 t += ('<span class="diffponct">»</span>'+' '*(n-1))
185 elif c == " " and ponct == 1:
186 t += '<span class="diffponct">·</span>'
187 elif c == "\n" and ponct == 1:
189 t += '<span class="diffponct">\</span>'
194 if linesize and (WORDBREAK.count(c) == 1):
197 if linesize and i > linesize:
204 def add_comment(s, output_file):
205 output_file.write('<tr class="diffmisc"><td colspan="4">%s</td></tr>\n'%convert(s))
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))
211 def add_hunk(output_file, 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))
216 # ⋮ - vertical ellipsis
217 output_file.write('<tr class="diffhunk"><td colspan="2">⋮</td><td colspan="2">⋮</td></tr>')
220 def add_line(s1, s2, output_file):
224 if s1 == None and s2 == None:
225 type_name = "unmodified"
226 elif s1 == None or s1 == "":
228 elif s2 == None or s1 == "":
229 type_name = "deleted"
231 type_name = "unmodified"
233 type_name = "changed"
234 s1, s2 = linediff(s1, s2)
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>')
244 output_file.write('<td colspan="2"> </td>')
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>')
253 output_file.write('<td colspan="2"></td>')
255 output_file.write('</tr>\n')
263 def empty_buffer(output_file):
268 if del_cpt == 0 or add_cpt == 0:
270 add_line(l[0], l[1], output_file)
272 elif del_cpt != 0 and add_cpt != 0:
279 max_len = (len(l0) > len(l1)) and len(l0) or len(l1)
280 for i in range(max_len):
286 add_line(s0, s1, output_file)
288 add_cpt, del_cpt = 0, 0
292 def parse_input(input_file, output_file,
293 exclude_headers, show_hunk_infos):
294 global add_cpt, del_cpt
296 global hunk_off1, hunk_size1, hunk_off2, hunk_size2
298 if not exclude_headers:
299 output_file.write(html_hdr)
300 output_file.write(table_hdr)
303 l = input_file.readline()
307 m = re.match('^--- ([^\s]*)', l)
309 empty_buffer(output_file)
310 file1 = m.groups()[0]
311 l = input_file.readline()
312 m = re.match('^\+\+\+ ([^\s]*)', l)
314 file2 = m.groups()[0]
315 add_filename(file1, file2, output_file)
316 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
319 m = re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
321 empty_buffer(output_file)
322 hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
323 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
324 line1, line2 = hunk_off1, hunk_off2
325 add_hunk(output_file, show_hunk_infos)
328 if hunk_size1 == 0 and hunk_size2 == 0:
329 empty_buffer(output_file)
330 add_comment(l, output_file)
333 if re.match("^\+", l):
336 buf.append((None, l[1:]))
339 if re.match("^\-", l):
342 buf.append((l[1:], None))
345 if re.match("^\ ", l) and hunk_size1 and hunk_size2:
346 empty_buffer(output_file)
349 buf.append((l[1:], l[1:]))
352 empty_buffer(output_file)
353 add_comment(l, output_file)
355 empty_buffer(output_file)
356 output_file.write(table_footer)
357 if not exclude_headers:
358 output_file.write(html_footer)
363 diff2html.py [-i file] [-o file] [-x]
366 Transform a unified diff from stdin to a colored side-by-side HTML
369 -i file set input file, else use stdin
370 -o file set output file, else use stdout
371 -x exclude html header and footer
372 -t tabsize set tab size (default 8)
373 -l linesize set maximum line size is there is no word break (default 20)
374 -r show \\r characters
376 -h show help and exit
380 global linesize, tabsize
383 input_file = sys.stdin
384 output_file = sys.stdout
386 exclude_headers = False
387 show_hunk_infos = False
390 opts, args = getopt.getopt(sys.argv[1:], "hi:o:xt:l:rk",
391 ["help", "input=", "output=",
392 "exclude-html-headers", "tabsize=",
393 "linesize=", "show-cr", "show-hunk-infos"])
394 except getopt.GetoptError, err:
395 print str(err) # will print something like "option -a not recognized"
400 if o in ("-h", "--help"):
403 elif o in ("-i", "--input"):
404 input_file = open(a, "r")
405 elif o in ("-o", "--output"):
406 output_file = open(a, "w")
407 elif o in ("-x", "--exclude-html-headers"):
408 exclude_headers = True
409 elif o in ("-t", "--tabsize"):
411 elif o in ("-l", "--linesize"):
413 elif o in ("-r", "--show-cr"):
415 elif o in ("-k", "--show-hunk-infos"):
416 show_hunk_infos = True
418 assert False, "unhandled option"
419 parse_input(input_file, output_file,
420 exclude_headers, show_hunk_infos)
423 if __name__ == "__main__":