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, datetime
40 # minimum line size, we add a zero-sized breakable space every
48 desc = "File comparison"
49 dtnow = datetime.datetime.now()
50 modified_date = "%s+01:00"%dtnow.isoformat()
52 html_hdr = """<!DOCTYPE html>
53 <html lang="{5}" dir="ltr"
54 xmlns:dc="http://purl.org/dc/terms/">
56 <meta charset="{1}" />
57 <meta name="generator" content="diff2html.py (http://git.droids-corp.org/gitweb/?p=diff2html)" />
58 <!--meta name="author" content="Fill in" /-->
59 <title>HTML Diff{0}</title>
60 <link rel="shortcut icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAACVBMVEXAAAAAgAD///+K/HwIAAAAJUlEQVQI12NYBQQM2IgGBQ4mCIEQW7oyK4phampkGIQAc1G1AQCRxCNbyW92oQAAAABJRU5ErkJggg==" type="image/png" />
61 <meta property="dc:language" content="{5}" />
62 <!--meta property="dc:date" content="{3}" /-->
63 <meta property="dc:modified" content="{4}" />
64 <meta name="description" content="{2}" />
65 <meta property="dc:abstract" content="{2}" />
67 table {{ border:0px; border-collapse:collapse; width: 100%; font-size:0.75em; font-family: Lucida Console, monospace }}
68 td.line {{ color:#8080a0 }}
69 th {{ background: black; color: white }}
70 tr.diffunmodified td {{ background: #D0D0E0 }}
71 tr.diffhunk td {{ background: #A0A0A0 }}
72 tr.diffadded td {{ background: #CCFFCC }}
73 tr.diffdeleted td {{ background: #FFCCCC }}
74 tr.diffchanged td {{ background: #FFFFA0 }}
75 span.diffchanged2 {{ background: #E0C880 }}
76 span.diffponct {{ color: #B08080 }}
78 tr.diffseparator td {{}}
86 <p>Modified at {1}. HTML formatting created by <a href="http://git.droids-corp.org/gitweb/?p=diff2html;a=summary">diff2html</a>. </p>
103 add_cpt, del_cpt = 0, 0
105 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
108 # Characters we're willing to word wrap on
109 WORDBREAK = " \t;.,/):"
115 if i not in ['\t', '\n'] and (j < 32):
123 s = unicode(reduce(lambda x, y:x+y, [ sane(c) for c in s ]))
125 t = unicode(reduce(lambda x, y:x+y, [ sane(c) for c in t ]))
127 m, n = len(s), len(t)
128 d = [[(0, 0) for i in range(n+1)] for i in range(m+1)]
131 d[0][0] = (0, (0, 0))
132 for i in range(m+1)[1:]:
133 d[i][0] = (i,(i-1, 0))
134 for j in range(n+1)[1:]:
135 d[0][j] = (j,(0, j-1))
137 for i in range(m+1)[1:]:
138 for j in range(n+1)[1:]:
143 d[i][j] = min((d[i-1][j][0] + 1, (i-1, j)),
144 (d[i][j-1][0] + 1, (i, j-1)),
145 (d[i-1][j-1][0] + cost, (i-1, j-1)))
149 while coord != (0, 0):
159 child_val = d[cx][cy][0]
161 father_coord = d[cx][cy][1]
162 fx, fy = father_coord
163 father_val = d[fx][fy][0]
165 diff = (cx-fx, cy-fy)
169 l2.append(DIFFON + t[fy] + DIFFOFF)
171 l1.append(DIFFON + s[fx] + DIFFOFF)
173 elif child_val-father_val == 1:
174 l1.append(DIFFON + s[fx] + DIFFOFF)
175 l2.append(DIFFON + t[fy] + DIFFOFF)
180 r1, r2 = (reduce(lambda x, y:x+y, l1), reduce(lambda x, y:x+y, l2))
184 def convert(s, linesize=0, ponct=0):
190 t += u'<span class="diffchanged2">'
195 elif htmlentitydefs.codepoint2name.has_key(ord(c)):
196 t += u"&%s;" % (htmlentitydefs.codepoint2name[ord(c)])
199 # special highlighted chars
200 elif c == "\t" and ponct == 1:
201 n = tabsize-(i%tabsize)
204 t += (u'<span class="diffponct">»</span>'+' '*(n-1))
205 elif c == " " and ponct == 1:
206 t += u'<span class="diffponct">·</span>'
207 elif c == "\n" and ponct == 1:
209 t += u'<span class="diffponct">\</span>'
214 if linesize and (WORDBREAK.count(c) == 1):
217 if linesize and i > linesize:
224 def add_comment(s, output_file):
225 output_file.write(('<tr class="diffmisc"><td colspan="4">%s</td></tr>\n'%convert(s)).encode(encoding))
228 def add_filename(f1, f2, output_file):
229 output_file.write(("<tr><th colspan='2'>%s</th>"%convert(f1, linesize=linesize)).encode(encoding))
230 output_file.write(("<th colspan='2'>%s</th></tr>\n"%convert(f2, linesize=linesize)).encode(encoding))
233 def add_hunk(output_file, show_hunk_infos):
235 output_file.write('<tr class="diffhunk"><td colspan="2">Offset %d, %d lines modified</td>'%(hunk_off1, hunk_size1))
236 output_file.write('<td colspan="2">Offset %d, %d lines modified</td></tr>\n'%(hunk_off2, hunk_size2))
238 # ⋮ - vertical ellipsis
239 output_file.write('<tr class="diffhunk"><td colspan="2">⋮</td><td colspan="2">⋮</td></tr>')
242 def add_line(s1, s2, output_file):
246 if s1 == None and s2 == None:
247 type_name = "unmodified"
248 elif s1 == None or s1 == "":
250 elif s2 == None or s1 == "":
251 type_name = "deleted"
253 type_name = "unmodified"
255 type_name = "changed"
256 s1, s2 = linediff(s1, s2)
258 output_file.write(('<tr class="diff%s">' % type_name).encode(encoding))
259 if s1 != None and s1 != "":
260 output_file.write(('<td class="diffline">%d </td>' % line1).encode(encoding))
261 output_file.write('<td class="diffpresent">'.encode(encoding))
262 output_file.write(convert(s1, linesize=linesize, ponct=1).encode(encoding))
263 output_file.write('</td>')
266 output_file.write('<td colspan="2"> </td>')
268 if s2 != None and s2 != "":
269 output_file.write(('<td class="diffline">%d </td>'%line2).encode(encoding))
270 output_file.write('<td class="diffpresent">')
271 output_file.write(convert(s2, linesize=linesize, ponct=1).encode(encoding))
272 output_file.write('</td>')
275 output_file.write('<td colspan="2"></td>')
277 output_file.write('</tr>\n')
285 def empty_buffer(output_file):
290 if del_cpt == 0 or add_cpt == 0:
292 add_line(l[0], l[1], output_file)
294 elif del_cpt != 0 and add_cpt != 0:
301 max_len = (len(l0) > len(l1)) and len(l0) or len(l1)
302 for i in range(max_len):
308 add_line(s0, s1, output_file)
310 add_cpt, del_cpt = 0, 0
314 def parse_input(input_file, output_file, input_file_name, output_file_name,
315 exclude_headers, show_hunk_infos):
316 global add_cpt, del_cpt
318 global hunk_off1, hunk_size1, hunk_off2, hunk_size2
320 if not exclude_headers:
321 title_suffix = ' ' + input_file_name
322 output_file.write(html_hdr.format(title_suffix, encoding, desc, "", modified_date, lang).encode(encoding))
323 output_file.write(table_hdr.encode(encoding))
326 l = input_file.readline()
330 m = re.match('^--- ([^\s]*)', l)
332 empty_buffer(output_file)
333 file1 = m.groups()[0]
335 l = input_file.readline()
336 m = re.match('^\+\+\+ ([^\s]*)', l)
338 file2 = m.groups()[0]
340 add_filename(file1, file2, output_file)
341 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
344 m = re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
346 empty_buffer(output_file)
347 hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
348 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
349 line1, line2 = hunk_off1, hunk_off2
350 add_hunk(output_file, show_hunk_infos)
353 if hunk_size1 == 0 and hunk_size2 == 0:
354 empty_buffer(output_file)
355 add_comment(l, output_file)
358 if re.match("^\+", l):
361 buf.append((None, l[1:]))
364 if re.match("^\-", l):
367 buf.append((l[1:], None))
370 if re.match("^\ ", l) and hunk_size1 and hunk_size2:
371 empty_buffer(output_file)
374 buf.append((l[1:], l[1:]))
377 empty_buffer(output_file)
378 add_comment(l, output_file)
380 empty_buffer(output_file)
381 output_file.write(table_footer.encode(encoding))
382 if not exclude_headers:
383 output_file.write(html_footer.format("", dtnow.strftime("%d.%m.%Y")).encode(encoding))
388 diff2html.py [-e encoding] [-i file] [-o file] [-x]
391 Transform a unified diff from stdin to a colored side-by-side HTML
393 stdout may not work with UTF-8, instead use -o option.
395 -i file set input file, else use stdin
396 -e encoding set file encoding (default utf-8)
397 -o file set output file, else use stdout
398 -x exclude html header and footer
399 -t tabsize set tab size (default 8)
400 -l linesize set maximum line size is there is no word break (default 20)
401 -r show \\r characters
403 -h show help and exit
407 global linesize, tabsize
412 output_file_name = ''
414 exclude_headers = False
415 show_hunk_infos = False
418 opts, args = getopt.getopt(sys.argv[1:], "he:i:o:xt:l:rk",
419 ["help", "encoding=", "input=", "output=",
420 "exclude-html-headers", "tabsize=",
421 "linesize=", "show-cr", "show-hunk-infos"])
422 except getopt.GetoptError, err:
423 print unicode(err) # will print something like "option -a not recognized"
428 if o in ("-h", "--help"):
431 elif o in ("-e", "--encoding"):
433 elif o in ("-i", "--input"):
434 input_file = codecs.open(a, "r", encoding)
436 elif o in ("-o", "--output"):
437 output_file = codecs.open(a, "w")
439 elif o in ("-x", "--exclude-html-headers"):
440 exclude_headers = True
441 elif o in ("-t", "--tabsize"):
443 elif o in ("-l", "--linesize"):
445 elif o in ("-r", "--show-cr"):
447 elif o in ("-k", "--show-hunk-infos"):
448 show_hunk_infos = True
450 assert False, "unhandled option"
452 # Use stdin if not input file is set
453 if not ('input_file' in locals()):
454 input_file = codecs.getreader(encoding)(sys.stdin)
456 # Use stdout if not output file is set
457 if not ('output_file' in locals()):
458 output_file = codecs.getwriter(encoding)(sys.stdout)
460 parse_input(input_file, output_file, input_file_name, output_file_name,
461 exclude_headers, show_hunk_infos)
463 def parse_from_memory(txt, exclude_headers, show_hunk_infos):
464 " Parses diff from memory and returns a string with html "
465 input_stream = StringIO.StringIO(txt)
466 output_stream = StringIO.StringIO()
467 parse_input(input_stream, output_stream, '', '', exclude_headers, show_hunk_infos)
468 return output_stream.getvalue()
471 if __name__ == "__main__":