fix some typos
[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 import sys, re, htmlentitydefs, getopt, StringIO, codecs, datetime
38 try:
39     from simplediff import diff, string_diff
40 except ImportError:
41     sys.stderr.write("info: simplediff module not found, only linediff is available\n")
42     sys.stderr.write("info: it can be downloaded at https://github.com/paulgb/simplediff\n")
43
44 # minimum line size, we add a zero-sized breakable space every
45 # LINESIZE characters
46 linesize = 20
47 tabsize = 8
48 show_CR = False
49 encoding = "utf-8"
50 lang = "en"
51 algorithm = 0
52
53 desc = "File comparison"
54 dtnow = datetime.datetime.now()
55 modified_date = "%s+01:00"%dtnow.isoformat()
56
57 html_hdr = """<!DOCTYPE html>
58 <html lang="{5}" dir="ltr"
59     xmlns:dc="http://purl.org/dc/terms/">
60 <head>
61     <meta charset="{1}" />
62     <meta name="generator" content="diff2html.py (http://git.droids-corp.org/gitweb/?p=diff2html)" />
63     <!--meta name="author" content="Fill in" /-->
64     <title>HTML Diff{0}</title>
65     <link rel="shortcut icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAACVBMVEXAAAAAgAD///+K/HwIAAAAJUlEQVQI12NYBQQM2IgGBQ4mCIEQW7oyK4phampkGIQAc1G1AQCRxCNbyW92oQAAAABJRU5ErkJggg==" type="image/png" />
66     <meta property="dc:language" content="{5}" />
67     <!--meta property="dc:date" content="{3}" /-->
68     <meta property="dc:modified" content="{4}" />
69     <meta name="description" content="{2}" />
70     <meta property="dc:abstract" content="{2}" />
71     <style>
72         table {{ border:0px; border-collapse:collapse; width: 100%; font-size:0.75em; font-family: Lucida Console, monospace }}
73         td.line {{ color:#8080a0 }}
74         th {{ background: black; color: white }}
75         tr.diffunmodified td {{ background: #D0D0E0 }}
76         tr.diffhunk td {{ background: #A0A0A0 }}
77         tr.diffadded td {{ background: #CCFFCC }}
78         tr.diffdeleted td {{ background: #FFCCCC }}
79         tr.diffchanged td {{ background: #FFFFA0 }}
80         span.diffchanged2 {{ background: #E0C880 }}
81         span.diffponct {{ color: #B08080 }}
82         tr.diffmisc td {{}}
83         tr.diffseparator td {{}}
84     </style>
85 </head>
86 <body>
87 """
88
89 html_footer = """
90 <footer>
91     <p>Modified at {1}. HTML formatting created by <a href="http://git.droids-corp.org/gitweb/?p=diff2html;a=summary">diff2html</a>.    </p>
92 </footer>
93 </body></html>
94 """
95
96 table_hdr = """
97                 <table class="diff">
98 """
99
100 table_footer = """
101 </table>
102 """
103
104 DIFFON = "\x01"
105 DIFFOFF = "\x02"
106
107 buf = []
108 add_cpt, del_cpt = 0, 0
109 line1, line2 = 0, 0
110 hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
111
112
113 # Characters we're willing to word wrap on
114 WORDBREAK = " \t;.,/):-"
115
116 def sane(x):
117     r = ""
118     for i in x:
119         j = ord(i)
120         if i not in ['\t', '\n'] and (j < 32):
121             r = r + "."
122         else:
123             r = r + i
124     return r
125
126 def linediff(s, t):
127     '''
128     Original line diff algorithm of diff2html. It's character based.
129     '''
130     if len(s):
131         s = unicode(reduce(lambda x, y:x+y, [ sane(c) for c in s ]))
132     if len(t):
133         t = unicode(reduce(lambda x, y:x+y, [ sane(c) for c in t ]))
134
135     m, n = len(s), len(t)
136     d = [[(0, 0) for i in range(n+1)] for i in range(m+1)]
137
138
139     d[0][0] = (0, (0, 0))
140     for i in range(m+1)[1:]:
141         d[i][0] = (i,(i-1, 0))
142     for j in range(n+1)[1:]:
143         d[0][j] = (j,(0, j-1))
144
145     for i in range(m+1)[1:]:
146         for j in range(n+1)[1:]:
147             if s[i-1] == t[j-1]:
148                 cost = 0
149             else:
150                 cost = 1
151             d[i][j] = min((d[i-1][j][0] + 1, (i-1, j)),
152                           (d[i][j-1][0] + 1, (i, j-1)),
153                           (d[i-1][j-1][0] + cost, (i-1, j-1)))
154
155     l = []
156     coord = (m, n)
157     while coord != (0, 0):
158         l.insert(0, coord)
159         x, y = coord
160         coord = d[x][y][1]
161
162     l1 = []
163     l2 = []
164
165     for coord in l:
166         cx, cy = coord
167         child_val = d[cx][cy][0]
168
169         father_coord = d[cx][cy][1]
170         fx, fy = father_coord
171         father_val = d[fx][fy][0]
172
173         diff = (cx-fx, cy-fy)
174
175         if diff == (0, 1):
176             l1.append("")
177             l2.append(DIFFON + t[fy] + DIFFOFF)
178         elif diff == (1, 0):
179             l1.append(DIFFON + s[fx] + DIFFOFF)
180             l2.append("")
181         elif child_val-father_val == 1:
182             l1.append(DIFFON + s[fx] + DIFFOFF)
183             l2.append(DIFFON + t[fy] + DIFFOFF)
184         else:
185             l1.append(s[fx])
186             l2.append(t[fy])
187
188     r1, r2 = (reduce(lambda x, y:x+y, l1), reduce(lambda x, y:x+y, l2))
189     return r1, r2
190
191
192 def diff_changed(old, new):
193     '''
194     Returns the differences basend on characters between two strings
195     wrapped with DIFFON and DIFFOFF using `diff`.
196     '''
197     con = {'=': (lambda x: x),
198            '+': (lambda x: DIFFON + x + DIFFOFF),
199            '-': (lambda x: '')}
200     return "".join([(con[a])("".join(b)) for a, b in diff(old, new)])
201
202
203 def diff_changed_ts(old, new):
204     '''
205     Returns a tuple for a two sided comparison based on characters, see `diff_changed`.
206     '''
207     return (diff_changed(new, old), diff_changed(old, new))
208
209
210 def word_diff(old, new):
211     '''
212     Returns the difference between the old and new strings based on words. Punctuation is not part of the word.
213
214     Params:
215         old the old string
216         new the new string
217
218     Returns:
219         the output of `diff` on the two strings after splitting them
220         on whitespace (a list of change instructions; see the docstring
221         of `diff`)
222     '''
223     separator_pattern = '(\W+)';
224     return diff(re.split(separator_pattern, old, flags=re.UNICODE), re.split(separator_pattern, new, flags=re.UNICODE))
225
226
227 def diff_changed_words(old, new):
228     '''
229     Returns the difference between two strings based on words (see `word_diff`)
230     wrapped with DIFFON and DIFFOFF.
231
232     Returns:
233         the output of the diff expressed delimited with DIFFON and DIFFOFF.
234     '''
235     con = {'=': (lambda x: x),
236            '+': (lambda x: DIFFON + x + DIFFOFF),
237            '-': (lambda x: '')}
238     return "".join([(con[a])("".join(b)) for a, b in word_diff(old, new)])
239
240
241 def diff_changed_words_ts(old, new):
242     '''
243     Returns a tuple for a two sided comparison based on words, see `diff_changed_words`.
244     '''
245     return (diff_changed_words(new, old), diff_changed_words(old, new))
246
247
248 def convert(s, linesize=0, ponct=0):
249     i = 0
250     t = u""
251     for c in s:
252         # used by diffs
253         if c == DIFFON:
254             t += u'<span class="diffchanged2">'
255         elif c == DIFFOFF:
256             t += u"</span>"
257
258         # special html chars
259         elif htmlentitydefs.codepoint2name.has_key(ord(c)):
260             t += u"&%s;" % (htmlentitydefs.codepoint2name[ord(c)])
261             i += 1
262
263         # special highlighted chars
264         elif c == "\t" and ponct == 1:
265             n = tabsize-(i%tabsize)
266             if n == 0:
267                 n = tabsize
268             t += (u'<span class="diffponct">&raquo;</span>'+'&nbsp;'*(n-1))
269         elif c == " " and ponct == 1:
270             t += u'<span class="diffponct">&middot;</span>'
271         elif c == "\n" and ponct == 1:
272             if show_CR:
273                 t += u'<span class="diffponct">\</span>'
274         else:
275             t += c
276             i += 1
277
278         if linesize and (WORDBREAK.count(c) == 1):
279             t += u'&#8203;'
280             i = 0
281         if linesize and i > linesize:
282             i = 0
283             t += u"&#8203;"
284
285     return t
286
287
288 def add_comment(s, output_file):
289     output_file.write(('<tr class="diffmisc"><td colspan="4">%s</td></tr>\n'%convert(s)).encode(encoding))
290
291
292 def add_filename(f1, f2, output_file):
293     output_file.write(("<tr><th colspan='2'>%s</th>"%convert(f1, linesize=linesize)).encode(encoding))
294     output_file.write(("<th colspan='2'>%s</th></tr>\n"%convert(f2, linesize=linesize)).encode(encoding))
295
296
297 def add_hunk(output_file, show_hunk_infos):
298     if show_hunk_infos:
299         output_file.write('<tr class="diffhunk"><td colspan="2">Offset %d, %d lines modified</td>'%(hunk_off1, hunk_size1))
300         output_file.write('<td colspan="2">Offset %d, %d lines modified</td></tr>\n'%(hunk_off2, hunk_size2))
301     else:
302         # &#8942; - vertical ellipsis
303         output_file.write('<tr class="diffhunk"><td colspan="2">&#8942;</td><td colspan="2">&#8942;</td></tr>')
304
305
306 def add_line(s1, s2, output_file):
307     global line1
308     global line2
309
310     orig1 = s1
311     orig2 = s2
312
313     if s1 == None and s2 == None:
314         type_name = "unmodified"
315     elif s1 == None or s1 == "":
316         type_name = "added"
317     elif s2 == None or s1 == "":
318         type_name = "deleted"
319     elif s1 == s2:
320         type_name = "unmodified"
321     else:
322         type_name = "changed"
323         if algorithm == 1:
324             s1, s2 = diff_changed_words_ts(orig1, orig2)
325         elif algorithm == 2:
326             s1, s2 = diff_changed_ts(orig1, orig2)
327         else: # default
328             s1, s2 = linediff(orig1, orig2)
329
330     output_file.write(('<tr class="diff%s">' % type_name).encode(encoding))
331     if s1 != None and s1 != "":
332         output_file.write(('<td class="diffline">%d </td>' % line1).encode(encoding))
333         output_file.write('<td class="diffpresent">'.encode(encoding))
334         output_file.write(convert(s1, linesize=linesize, ponct=1).encode(encoding))
335         output_file.write('</td>')
336     else:
337         s1 = ""
338         output_file.write('<td colspan="2"> </td>')
339
340     if s2 != None and s2 != "":
341         output_file.write(('<td class="diffline">%d </td>'%line2).encode(encoding))
342         output_file.write('<td class="diffpresent">')
343         output_file.write(convert(s2, linesize=linesize, ponct=1).encode(encoding))
344         output_file.write('</td>')
345     else:
346         s2 = ""
347         output_file.write('<td colspan="2"></td>')
348
349     output_file.write('</tr>\n')
350
351     if s1 != "":
352         line1 += 1
353     if s2 != "":
354         line2 += 1
355
356
357 def empty_buffer(output_file):
358     global buf
359     global add_cpt
360     global del_cpt
361
362     if del_cpt == 0 or add_cpt == 0:
363         for l in buf:
364             add_line(l[0], l[1], output_file)
365
366     elif del_cpt != 0 and add_cpt != 0:
367         l0, l1 = [], []
368         for l in buf:
369             if l[0] != None:
370                 l0.append(l[0])
371             if l[1] != None:
372                 l1.append(l[1])
373         max_len = (len(l0) > len(l1)) and len(l0) or len(l1)
374         for i in range(max_len):
375             s0, s1 = "", ""
376             if i < len(l0):
377                 s0 = l0[i]
378             if i < len(l1):
379                 s1 = l1[i]
380             add_line(s0, s1, output_file)
381
382     add_cpt, del_cpt = 0, 0
383     buf = []
384
385
386 def parse_input(input_file, output_file, input_file_name, output_file_name,
387                 exclude_headers, show_hunk_infos):
388     global add_cpt, del_cpt
389     global line1, line2
390     global hunk_off1, hunk_size1, hunk_off2, hunk_size2
391
392     if not exclude_headers:
393         title_suffix = ' ' + input_file_name
394         output_file.write(html_hdr.format(title_suffix, encoding, desc, "", modified_date, lang).encode(encoding))
395     output_file.write(table_hdr.encode(encoding))
396
397     while True:
398         l = input_file.readline()
399         if l == "":
400             break
401
402         m = re.match('^--- ([^\s]*)', l)
403         if m:
404             empty_buffer(output_file)
405             file1 = m.groups()[0]
406             while True:
407                 l = input_file.readline()
408                 m = re.match('^\+\+\+ ([^\s]*)', l)
409                 if m:
410                     file2 = m.groups()[0]
411                     break
412             add_filename(file1, file2, output_file)
413             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = 0, 0, 0, 0
414             continue
415
416         m = re.match("@@ -(\d+),?(\d*) \+(\d+),?(\d*)", l)
417         if m:
418             empty_buffer(output_file)
419             hunk_data = map(lambda x:x=="" and 1 or int(x), m.groups())
420             hunk_off1, hunk_size1, hunk_off2, hunk_size2 = hunk_data
421             line1, line2 = hunk_off1, hunk_off2
422             add_hunk(output_file, show_hunk_infos)
423             continue
424
425         if hunk_size1 == 0 and hunk_size2 == 0:
426             empty_buffer(output_file)
427             add_comment(l, output_file)
428             continue
429
430         if re.match("^\+", l):
431             add_cpt += 1
432             hunk_size2 -= 1
433             buf.append((None, l[1:]))
434             continue
435
436         if re.match("^\-", l):
437             del_cpt += 1
438             hunk_size1 -= 1
439             buf.append((l[1:], None))
440             continue
441
442         if re.match("^\ ", l) and hunk_size1 and hunk_size2:
443             empty_buffer(output_file)
444             hunk_size1 -= 1
445             hunk_size2 -= 1
446             buf.append((l[1:], l[1:]))
447             continue
448
449         empty_buffer(output_file)
450         add_comment(l, output_file)
451
452     empty_buffer(output_file)
453     output_file.write(table_footer.encode(encoding))
454     if not exclude_headers:
455         output_file.write(html_footer.format("", dtnow.strftime("%d.%m.%Y")).encode(encoding))
456
457
458 def usage():
459     print '''
460 diff2html.py [-e encoding] [-i file] [-o file] [-x]
461 diff2html.py -h
462
463 Transform a unified diff from stdin to a colored side-by-side HTML
464 page on stdout.
465 stdout may not work with UTF-8, instead use -o option.
466
467    -i file     set input file, else use stdin
468    -e encoding set file encoding (default utf-8)
469    -o file     set output file, else use stdout
470    -x          exclude html header and footer
471    -t tabsize  set tab size (default 8)
472    -l linesize set maximum line size is there is no word break (default 20)
473    -r          show \\r characters
474    -k          show hunk infos
475    -a algo     line diff algorithm (0: linediff characters, 1: word, 2: simplediff characters) (default 0)
476    -h          show help and exit
477 '''
478
479 def main():
480     global linesize, tabsize
481     global show_CR
482     global encoding
483     global algorithm
484
485     input_file_name = ''
486     output_file_name = ''
487
488     exclude_headers = False
489     show_hunk_infos = False
490
491     try:
492         opts, args = getopt.getopt(sys.argv[1:], "he:i:o:xt:l:rka:",
493                                    ["help", "encoding=", "input=", "output=",
494                                     "exclude-html-headers", "tabsize=",
495                                     "linesize=", "show-cr", "show-hunk-infos", "algorithm="])
496     except getopt.GetoptError, err:
497         print unicode(err) # will print something like "option -a not recognized"
498         usage()
499         sys.exit(2)
500     verbose = False
501     for o, a in opts:
502         if o in ("-h", "--help"):
503             usage()
504             sys.exit()
505         elif o in ("-e", "--encoding"):
506             encoding = a
507         elif o in ("-i", "--input"):
508             input_file = codecs.open(a, "r", encoding)
509             input_file_name = a
510         elif o in ("-o", "--output"):
511             output_file = codecs.open(a, "w")
512             output_file_name = a
513         elif o in ("-x", "--exclude-html-headers"):
514             exclude_headers = True
515         elif o in ("-t", "--tabsize"):
516             tabsize = int(a)
517         elif o in ("-l", "--linesize"):
518             linesize = int(a)
519         elif o in ("-r", "--show-cr"):
520             show_CR = True
521         elif o in ("-k", "--show-hunk-infos"):
522             show_hunk_infos = True
523         elif o in ("-a", "--algorithm"):
524             algorithm = int(a)
525         else:
526             assert False, "unhandled option"
527
528     # Use stdin if not input file is set
529     if not ('input_file' in locals()):
530         input_file = codecs.getreader(encoding)(sys.stdin)
531
532     # Use stdout if not output file is set
533     if not ('output_file' in locals()):
534         output_file = codecs.getwriter(encoding)(sys.stdout)
535
536     parse_input(input_file, output_file, input_file_name, output_file_name,
537                 exclude_headers, show_hunk_infos)
538
539 def parse_from_memory(txt, exclude_headers, show_hunk_infos):
540     " Parses diff from memory and returns a string with html "
541     input_stream = StringIO.StringIO(txt)
542     output_stream = StringIO.StringIO()
543     parse_input(input_stream, output_stream, '', '', exclude_headers, show_hunk_infos)
544     return output_stream.getvalue()
545
546
547 if __name__ == "__main__":
548     main()