4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 # Transform a unified diff from stdin to a colored
20 # side-by-side HTML page on stdout.
22 # Authors: Olivier MATZ <zer0@droids-corp.org>
23 # Alan De Smet <adesmet@cs.wisc.edu>
24 # Sergey Satskiy <sergey.satskiy@gmail.com>
25 # scito <info at scito.ch>
27 # Inspired by diff2html.rb from Dave Burt <dave (at) burt.id.au>
28 # (mainly for html theme)
31 # - The sane function currently mashes non-ASCII characters to "."
32 # Instead be clever and convert to something like "xF0"
33 # (the hex value), and mark with a <span>. Even more clever:
34 # Detect if the character is "printable" for whatever definition,
35 # and display those directly.
38 import sys, re, htmlentitydefs, getopt, StringIO, codecs
40 # minimum line size, we add a zero-sized breakable space every
48 html_hdr = """<!DOCTYPE html>
50 <meta charset="{0}" />
51 <meta name="generator" content="diff2html.rb" />
52 <title>HTML Diff</title>
54 table {{ border:0px; border-collapse:collapse; width: 100%; font-size:0.75em; font-family: Lucida Console, monospace }}
55 td.line {{ color:#8080a0 }}
56 th {{ background: black; color: white }}
57 tr.diffunmodified td {{ background: #D0D0E0 }}
58 tr.diffhunk td {{ background: #A0A0A0 }}
59 tr.diffadded td {{ background: #CCFFCC }}
60 tr.diffdeleted td {{ background: #FFCCCC }}
61 tr.diffchanged td {{ background: #FFFFA0 }}
62 span.diffchanged2 {{ background: #E0C880 }}
63 span.diffponct {{ color: #B08080 }}
65 tr.diffseparator td {{}}
87 add_cpt, del_cpt = 0, 0
89 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
92 # Characters we're willing to word wrap on
93 WORDBREAK = " \t;.,/):"
99 if i not in ['\t', '\n'] and (j < 32):
107 s = unicode(reduce(lambda x, y:x+y, [ sane(c) for c in s ]))
109 t = unicode(reduce(lambda x, y:x+y, [ sane(c) for c in t ]))
111 m, n = len(s), len(t)
112 d = [[(0, 0) for i in range(n+1)] for i in range(m+1)]
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))
121 for i in range(m+1)[1:]:
122 for j in range(n+1)[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)))
133 while coord != (0, 0):
143 child_val = d[cx][cy][0]
145 father_coord = d[cx][cy][1]
146 fx, fy = father_coord
147 father_val = d[fx][fy][0]
149 diff = (cx-fx, cy-fy)
153 l2.append(DIFFON + t[fy] + DIFFOFF)
155 l1.append(DIFFON + s[fx] + DIFFOFF)
157 elif child_val-father_val == 1:
158 l1.append(DIFFON + s[fx] + DIFFOFF)
159 l2.append(DIFFON + t[fy] + DIFFOFF)
164 r1, r2 = (reduce(lambda x, y:x+y, l1), reduce(lambda x, y:x+y, l2))
168 def convert(s, linesize=0, ponct=0):
174 t += u'<span class="diffchanged2">'
179 elif htmlentitydefs.codepoint2name.has_key(ord(c)):
180 t += u"&%s;" % (htmlentitydefs.codepoint2name[ord(c)])
183 # special highlighted chars
184 elif c == "\t" and ponct == 1:
185 n = tabsize-(i%tabsize)
188 t += (u'<span class="diffponct">»</span>'+' '*(n-1))
189 elif c == " " and ponct == 1:
190 t += u'<span class="diffponct">·</span>'
191 elif c == "\n" and ponct == 1:
193 t += u'<span class="diffponct">\</span>'
198 if linesize and (WORDBREAK.count(c) == 1):
201 if linesize and i > linesize:
208 def add_comment(s, output_file):
209 output_file.write(('<tr class="diffmisc"><td colspan="4">%s</td></tr>\n'%convert(s)).encode(encoding))
212 def add_filename(f1, f2, output_file):
213 output_file.write(("<tr><th colspan='2'>%s</th>"%convert(f1, linesize=linesize)).encode(encoding))
214 output_file.write(("<th colspan='2'>%s</th></tr>\n"%convert(f2, linesize=linesize)).encode(encoding))
217 def add_hunk(output_file, show_hunk_infos):
219 output_file.write('<tr class="diffhunk"><td colspan="2">Offset %d, %d lines modified</td>'%(hunk_off1, hunk_size1))
220 output_file.write('<td colspan="2">Offset %d, %d lines modified</td></tr>\n'%(hunk_off2, hunk_size2))
222 # ⋮ - vertical ellipsis
223 output_file.write('<tr class="diffhunk"><td colspan="2">⋮</td><td colspan="2">⋮</td></tr>')
226 def add_line(s1, s2, output_file):
230 if s1 == None and s2 == None:
231 type_name = "unmodified"
232 elif s1 == None or s1 == "":
234 elif s2 == None or s1 == "":
235 type_name = "deleted"
237 type_name = "unmodified"
239 type_name = "changed"
240 s1, s2 = linediff(s1, s2)
242 output_file.write(('<tr class="diff%s">' % type_name).encode(encoding))
243 if s1 != None and s1 != "":
244 output_file.write(('<td class="diffline">%d </td>' % line1).encode(encoding))
245 output_file.write('<td class="diffpresent">'.encode(encoding))
246 output_file.write(convert(s1, linesize=linesize, ponct=1).encode(encoding))
247 output_file.write('</td>')
250 output_file.write('<td colspan="2"> </td>')
252 if s2 != None and s2 != "":
253 output_file.write(('<td class="diffline">%d </td>'%line2).encode(encoding))
254 output_file.write('<td class="diffpresent">')
255 output_file.write(convert(s2, linesize=linesize, ponct=1).encode(encoding))
256 output_file.write('</td>')
259 output_file.write('<td colspan="2"></td>')
261 output_file.write('</tr>\n')
269 def empty_buffer(output_file):
274 if del_cpt == 0 or add_cpt == 0:
276 add_line(l[0], l[1], output_file)
278 elif del_cpt != 0 and add_cpt != 0:
285 max_len = (len(l0) > len(l1)) and len(l0) or len(l1)
286 for i in range(max_len):
292 add_line(s0, s1, output_file)
294 add_cpt, del_cpt = 0, 0
298 def parse_input(input_file, output_file,
299 exclude_headers, show_hunk_infos):
300 global add_cpt, del_cpt
302 global hunk_off1, hunk_size1, hunk_off2, hunk_size2
304 if not exclude_headers:
305 output_file.write(html_hdr.format(encoding).encode(encoding))
306 output_file.write(table_hdr.encode(encoding))
309 l = input_file.readline()
313 m = re.match('^--- ([^\s]*)', l)
315 empty_buffer(output_file)
316 file1 = m.groups()[0]
318 l = input_file.readline()
319 m = re.match('^\+\+\+ ([^\s]*)', l)
321 file2 = m.groups()[0]
323 add_filename(file1, file2, output_file)
324 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
327 m = re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
329 empty_buffer(output_file)
330 hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
331 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
332 line1, line2 = hunk_off1, hunk_off2
333 add_hunk(output_file, show_hunk_infos)
336 if hunk_size1 == 0 and hunk_size2 == 0:
337 empty_buffer(output_file)
338 add_comment(l, output_file)
341 if re.match("^\+", l):
344 buf.append((None, l[1:]))
347 if re.match("^\-", l):
350 buf.append((l[1:], None))
353 if re.match("^\ ", l) and hunk_size1 and hunk_size2:
354 empty_buffer(output_file)
357 buf.append((l[1:], l[1:]))
360 empty_buffer(output_file)
361 add_comment(l, output_file)
363 empty_buffer(output_file)
364 output_file.write(table_footer.encode(encoding))
365 if not exclude_headers:
366 output_file.write(html_footer.encode(encoding))
371 diff2html.py [-e encoding] [-i file] [-o file] [-x]
374 Transform a unified diff from stdin to a colored side-by-side HTML
376 stdout may not work with UTF-8, instead use -o option.
378 -i file set input file, else use stdin
379 -e encoding set file encoding (default utf-8)
380 -o file set output file, else use stdout
381 -x exclude html header and footer
382 -t tabsize set tab size (default 8)
383 -l linesize set maximum line size is there is no word break (default 20)
384 -r show \\r characters
386 -h show help and exit
390 global linesize, tabsize
394 input_file = sys.stdin
395 output_file = sys.stdout
397 exclude_headers = False
398 show_hunk_infos = False
401 opts, args = getopt.getopt(sys.argv[1:], "he:i:o:xt:l:rk",
402 ["help", "encoding=", "input=", "output=",
403 "exclude-html-headers", "tabsize=",
404 "linesize=", "show-cr", "show-hunk-infos"])
405 except getopt.GetoptError, err:
406 print unicode(err) # will print something like "option -a not recognized"
411 if o in ("-h", "--help"):
414 elif o in ("-e", "--encoding"):
416 elif o in ("-i", "--input"):
417 input_file = codecs.open(a, "r", encoding)
418 elif o in ("-o", "--output"):
419 output_file = codecs.open(a, "w")
420 elif o in ("-x", "--exclude-html-headers"):
421 exclude_headers = True
422 elif o in ("-t", "--tabsize"):
424 elif o in ("-l", "--linesize"):
426 elif o in ("-r", "--show-cr"):
428 elif o in ("-k", "--show-hunk-infos"):
429 show_hunk_infos = True
431 assert False, "unhandled option"
432 parse_input(input_file, output_file,
433 exclude_headers, show_hunk_infos)
435 def parse_from_memory(txt, exclude_headers, show_hunk_infos):
436 " Parses diff from memory and returns a string with html "
437 input_stream = StringIO.StringIO(txt)
438 output_stream = StringIO.StringIO()
439 parse_input(input_stream, output_stream, exclude_headers, show_hunk_infos)
440 return output_stream.getvalue()
443 if __name__ == "__main__":