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>
23 # Sergey Satskiy <sergey.satskiy@gmail.com>
25 # Inspired by diff2html.rb from Dave Burt <dave (at) burt.id.au>
26 # (mainly for html theme)
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.
36 import sys, re, htmlentitydefs, getopt, StringIO
38 # minimum line size, we add a zero-sized breakable space every
45 html_hdr = """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
47 <meta name="generator" content="diff2html.rb" />
48 <title>HTML Diff</title>
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 }
61 tr.diffseparator td {}
83 add_cpt, del_cpt = 0, 0
85 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
88 # Characters we're willing to word wrap on
89 WORDBREAK = " \t;.,/):"
95 if i not in ['\t', '\n'] and ((j < 32) or (j >= 127)):
103 s = str(reduce(lambda x, y:x+y, [ sane(c) for c in s ]))
105 t = str(reduce(lambda x, y:x+y, [ sane(c) for c in t ]))
107 m, n = len(s), len(t)
108 d = [[(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]
312 l = input_file.readline()
313 m = re.match('^\+\+\+ ([^\s]*)', l)
315 file2 = m.groups()[0]
317 add_filename(file1, file2, output_file)
318 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
321 m = re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
323 empty_buffer(output_file)
324 hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
325 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
326 line1, line2 = hunk_off1, hunk_off2
327 add_hunk(output_file, show_hunk_infos)
330 if hunk_size1 == 0 and hunk_size2 == 0:
331 empty_buffer(output_file)
332 add_comment(l, output_file)
335 if re.match("^\+", l):
338 buf.append((None, l[1:]))
341 if re.match("^\-", l):
344 buf.append((l[1:], None))
347 if re.match("^\ ", l) and hunk_size1 and hunk_size2:
348 empty_buffer(output_file)
351 buf.append((l[1:], l[1:]))
354 empty_buffer(output_file)
355 add_comment(l, output_file)
357 empty_buffer(output_file)
358 output_file.write(table_footer)
359 if not exclude_headers:
360 output_file.write(html_footer)
365 diff2html.py [-i file] [-o file] [-x]
368 Transform a unified diff from stdin to a colored side-by-side HTML
371 -i file set input file, else use stdin
372 -o file set output file, else use stdout
373 -x exclude html header and footer
374 -t tabsize set tab size (default 8)
375 -l linesize set maximum line size is there is no word break (default 20)
376 -r show \\r characters
378 -h show help and exit
382 global linesize, tabsize
385 input_file = sys.stdin
386 output_file = sys.stdout
388 exclude_headers = False
389 show_hunk_infos = False
392 opts, args = getopt.getopt(sys.argv[1:], "hi:o:xt:l:rk",
393 ["help", "input=", "output=",
394 "exclude-html-headers", "tabsize=",
395 "linesize=", "show-cr", "show-hunk-infos"])
396 except getopt.GetoptError, err:
397 print str(err) # will print something like "option -a not recognized"
402 if o in ("-h", "--help"):
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"):
413 elif o in ("-l", "--linesize"):
415 elif o in ("-r", "--show-cr"):
417 elif o in ("-k", "--show-hunk-infos"):
418 show_hunk_infos = True
420 assert False, "unhandled option"
421 parse_input(input_file, output_file,
422 exclude_headers, show_hunk_infos)
424 def parse_from_memory(txt, exclude_headers, show_hunk_infos):
425 " Parses diff from memory and returns a string with html "
426 input_stream = StringIO.StringIO(txt)
427 output_stream = StringIO.StringIO()
428 parse_input(input_stream, output_stream, exclude_headers, show_hunk_infos)
429 return output_stream.getvalue()
432 if __name__ == "__main__":