enhance meta info in generated html
[diff2html.git] / diff2html.py
1 #! /usr/bin/python
2 # coding=utf-8
3 #
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.
8 #
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.
13 #
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
17 #
18 #
19 # Transform a unified diff from stdin to a colored
20 # side-by-side HTML page on stdout.
21 #
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>
26 #
27 # Inspired by diff2html.rb from Dave Burt <dave (at) burt.id.au>
28 # (mainly for html theme)
29 #
30 # TODO:
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.
36
37
38 import sys, re, htmlentitydefs, getopt, StringIO, codecs, datetime
39
40 # minimum line size, we add a zero-sized breakable space every
41 # LINESIZE characters
42 linesize = 20
43 tabsize = 8
44 show_CR = False
45 encoding = "utf-8"
46 lang = "en"
47
48 desc = "File comparison"
49 dtnow = datetime.datetime.now()
50 modified_date = "%s+01:00"%dtnow.isoformat()
51
52 html_hdr = """<!DOCTYPE html>
53 <html lang="{5}" dir="ltr"
54     xmlns:dc="http://purl.org/dc/terms/">
55 <head>
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}" />
66     <style>
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 }}
77         tr.diffmisc td {{}}
78         tr.diffseparator td {{}}
79     </style>
80 </head>
81 <body>
82 """
83
84 html_footer = """
85 <footer>
86     <p>Modified at {1}. HTML formatting created by <a href="http://git.droids-corp.org/gitweb/?p=diff2html;a=summary">diff2html</a>.    </p>
87 </footer>
88 </body></html>
89 """
90
91 table_hdr = """
92                 <table class="diff">
93 """
94
95 table_footer = """
96 </table>
97 """
98
99 DIFFON = "\x01"
100 DIFFOFF = "\x02"
101
102 buf = []
103 add_cpt, del_cpt = 0, 0
104 line1, line2 = 0, 0
105 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
106
107
108 # Characters we're willing to word wrap on
109 WORDBREAK = " \t;.,/):"
110
111 def sane(x):
112     r = ""
113     for i in x:
114         j = ord(i)
115         if i not in ['\t', '\n'] and (j < 32):
116             r = r + "."
117         else:
118             r = r + i
119     return r
120
121 def linediff(s, t):
122     if len(s):
123         s = unicode(reduce(lambda x, y:x+y, [ sane(c) for c in s ]))
124     if len(t):
125         t = unicode(reduce(lambda x, y:x+y, [ sane(c) for c in t ]))
126
127     m, n = len(s), len(t)
128     d = [[(0, 0) for i in range(n+1)] for i in range(m+1)]
129
130
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))
136
137     for i in range(m+1)[1:]:
138         for j in range(n+1)[1:]:
139             if s[i-1] == t[j-1]:
140                 cost = 0
141             else:
142                 cost = 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)))
146
147     l = []
148     coord = (m, n)
149     while coord != (0, 0):
150         l.insert(0, coord)
151         x, y = coord
152         coord = d[x][y][1]
153
154     l1 = []
155     l2 = []
156
157     for coord in l:
158         cx, cy = coord
159         child_val = d[cx][cy][0]
160
161         father_coord = d[cx][cy][1]
162         fx, fy = father_coord
163         father_val = d[fx][fy][0]
164
165         diff = (cx-fx, cy-fy)
166
167         if diff == (0, 1):
168             l1.append("")
169             l2.append(DIFFON + t[fy] + DIFFOFF)
170         elif diff == (1, 0):
171             l1.append(DIFFON + s[fx] + DIFFOFF)
172             l2.append("")
173         elif child_val-father_val == 1:
174             l1.append(DIFFON + s[fx] + DIFFOFF)
175             l2.append(DIFFON + t[fy] + DIFFOFF)
176         else:
177             l1.append(s[fx])
178             l2.append(t[fy])
179
180     r1, r2 = (reduce(lambda x, y:x+y, l1), reduce(lambda x, y:x+y, l2))
181     return r1, r2
182
183
184 def convert(s, linesize=0, ponct=0):
185     i = 0
186     t = u""
187     for c in s:
188         # used by diffs
189         if c == DIFFON:
190             t += u'<span class="diffchanged2">'
191         elif c == DIFFOFF:
192             t += u"</span>"
193
194         # special html chars
195         elif htmlentitydefs.codepoint2name.has_key(ord(c)):
196             t += u"&%s;" % (htmlentitydefs.codepoint2name[ord(c)])
197             i += 1
198
199         # special highlighted chars
200         elif c == "\t" and ponct == 1:
201             n = tabsize-(i%tabsize)
202             if n == 0:
203                 n = tabsize
204             t += (u'<span class="diffponct">&raquo;</span>'+'&nbsp;'*(n-1))
205         elif c == " " and ponct == 1:
206             t += u'<span class="diffponct">&middot;</span>'
207         elif c == "\n" and ponct == 1:
208             if show_CR:
209                 t += u'<span class="diffponct">\</span>'
210         else:
211             t += c
212             i += 1
213
214         if linesize and (WORDBREAK.count(c) == 1):
215             t += u'&#8203;'
216             i = 0
217         if linesize and i > linesize:
218             i = 0
219             t += u"&#8203;"
220
221     return t
222
223
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))
226
227
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))
231
232
233 def add_hunk(output_file, show_hunk_infos):
234     if 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))
237     else:
238         # &#8942; - vertical ellipsis
239         output_file.write('<tr class="diffhunk"><td colspan="2">&#8942;</td><td colspan="2">&#8942;</td></tr>')
240
241
242 def add_line(s1, s2, output_file):
243     global line1
244     global line2
245
246     if s1 == None and s2 == None:
247         type_name = "unmodified"
248     elif s1 == None or s1 == "":
249         type_name = "added"
250     elif s2 == None or s1 == "":
251         type_name = "deleted"
252     elif s1 == s2:
253         type_name = "unmodified"
254     else:
255         type_name = "changed"
256         s1, s2 = linediff(s1, s2)
257
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>')
264     else:
265         s1 = ""
266         output_file.write('<td colspan="2"> </td>')
267
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>')
273     else:
274         s2 = ""
275         output_file.write('<td colspan="2"></td>')
276
277     output_file.write('</tr>\n')
278
279     if s1 != "":
280         line1 += 1
281     if s2 != "":
282         line2 += 1
283
284
285 def empty_buffer(output_file):
286     global buf
287     global add_cpt
288     global del_cpt
289
290     if del_cpt == 0 or add_cpt == 0:
291         for l in buf:
292             add_line(l[0], l[1], output_file)
293
294     elif del_cpt != 0 and add_cpt != 0:
295         l0, l1 = [], []
296         for l in buf:
297             if l[0] != None:
298                 l0.append(l[0])
299             if l[1] != None:
300                 l1.append(l[1])
301         max_len = (len(l0) > len(l1)) and len(l0) or len(l1)
302         for i in range(max_len):
303             s0, s1 = "", ""
304             if i < len(l0):
305                 s0 = l0[i]
306             if i < len(l1):
307                 s1 = l1[i]
308             add_line(s0, s1, output_file)
309
310     add_cpt, del_cpt = 0, 0
311     buf = []
312
313
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
317     global line1, line2
318     global hunk_off1, hunk_size1, hunk_off2, hunk_size2
319
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))
324
325     while True:
326         l = input_file.readline()
327         if l == "":
328             break
329
330         m = re.match('^--- ([^\s]*)', l)
331         if m:
332             empty_buffer(output_file)
333             file1 = m.groups()[0]
334             while True:
335                 l = input_file.readline()
336                 m = re.match('^\+\+\+ ([^\s]*)', l)
337                 if m:
338                     file2 = m.groups()[0]
339                     break
340             add_filename(file1, file2, output_file)
341             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
342             continue
343
344         m = re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
345         if m:
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)
351             continue
352
353         if hunk_size1 == 0 and hunk_size2 == 0:
354             empty_buffer(output_file)
355             add_comment(l, output_file)
356             continue
357
358         if re.match("^\+", l):
359             add_cpt += 1
360             hunk_size2 -= 1
361             buf.append((None, l[1:]))
362             continue
363
364         if re.match("^\-", l):
365             del_cpt += 1
366             hunk_size1 -= 1
367             buf.append((l[1:], None))
368             continue
369
370         if re.match("^\ ", l) and hunk_size1 and hunk_size2:
371             empty_buffer(output_file)
372             hunk_size1 -= 1
373             hunk_size2 -= 1
374             buf.append((l[1:], l[1:]))
375             continue
376
377         empty_buffer(output_file)
378         add_comment(l, output_file)
379
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))
384
385
386 def usage():
387     print '''
388 diff2html.py [-e encoding] [-i file] [-o file] [-x]
389 diff2html.py -h
390
391 Transform a unified diff from stdin to a colored side-by-side HTML
392 page on stdout.
393 stdout may not work with UTF-8, instead use -o option.
394
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
402    -k          show hunk infos
403    -h          show help and exit
404 '''
405
406 def main():
407     global linesize, tabsize
408     global show_CR
409     global encoding
410
411     input_file_name = ''
412     output_file_name = ''
413
414     exclude_headers = False
415     show_hunk_infos = False
416
417     try:
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"
424         usage()
425         sys.exit(2)
426     verbose = False
427     for o, a in opts:
428         if o in ("-h", "--help"):
429             usage()
430             sys.exit()
431         elif o in ("-e", "--encoding"):
432             encoding = a
433         elif o in ("-i", "--input"):
434             input_file = codecs.open(a, "r", encoding)
435             input_file_name = a
436         elif o in ("-o", "--output"):
437             output_file = codecs.open(a, "w")
438             output_file_name = a
439         elif o in ("-x", "--exclude-html-headers"):
440             exclude_headers = True
441         elif o in ("-t", "--tabsize"):
442             tabsize = int(a)
443         elif o in ("-l", "--linesize"):
444             linesize = int(a)
445         elif o in ("-r", "--show-cr"):
446             show_CR = True
447         elif o in ("-k", "--show-hunk-infos"):
448             show_hunk_infos = True
449         else:
450             assert False, "unhandled option"
451
452     # Use stdin if not input file is set
453     if not ('input_file' in locals()):
454         input_file = codecs.getreader(encoding)(sys.stdin)
455
456     # Use stdout if not output file is set
457     if not ('output_file' in locals()):
458         output_file = codecs.getwriter(encoding)(sys.stdout)
459
460     parse_input(input_file, output_file, input_file_name, output_file_name,
461                 exclude_headers, show_hunk_infos)
462
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()
469
470
471 if __name__ == "__main__":
472     main()