- Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathdiff2html.py
More file actions
Latest commit
executable file
·95 lines (85 loc) · 2.73 KB
/
Copy pathdiff2html.py
File metadata and controls
executable file
·95 lines (85 loc) · 2.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#!/usr/bin/env python3
from __future__ importprint_function, unicode_literals
importio
importre
importfileinput
importsys
fromargparseimportArgumentParser
fromfunctoolsimportpartial
defquote_html(s):
'''Quote html special chars and replace space with nbsp'''
defrepl_quote_html(m):
tokens= []
quote_dict= {
' ': ' ',
'<': '<',
'>': '>',
'&': '&',
'"': '"',
}
forcinm.group(0):
tokens.append(quote_dict[c])
return''.join(tokens)
returnre.sub('[ &<>"]', repl_quote_html, s)
defprint_html(print_function, lines, title, encoding):
p=print_function
q=quote_html
p('<?DOCTYPE html?>')
p('<html>')
p('<head>')
p('<meta http-equiv="Content-Type" content="text/html; charset={}">'
.format(q(encoding)))
iftitleisnotNone:
p('<title>{}</title>'.format(q(title)))
p('''
<style>
span.diffcommand { color: teal; }
span.removed { color: red; }
span.inserted { color: green; }
span.linenumber { color: purple; }
</style>
''')
p('</head>')
forlineinlines:
ifline.startswith('+++'):
p(q(line))
elifline.startswith('---'):
p(q(line))
elifline.startswith('+'):
p('<span class="inserted">{}</span>'.format(q(line)))
elifline.startswith('-'):
p('<span class="removed">{}</span>'.format(q(line)))
elifline.startswith('diff'):
p('<span class="diffcommand">{}</span>'.format(q(line)))
else:
m=re.match(r'^@@.*?@@', line)
ifm:
num=m.group(0)
rest=line[len(num):]
p('<span class="linenumber">{}</span>{}'
.format(q(num), q(rest)))
else:
p(q(line))
p('<br />')
p('</body>')
p('</html>')
defmain():
parser=ArgumentParser()
parser.add_argument('--output-file', '-o', action='store')
parser.add_argument('--output-encoding', action='store',
default=sys.getdefaultencoding())
parser.add_argument('--title', action='store')
parser.add_argument('files', nargs='*', action='store')
args=parser.parse_args()
encoding=args.output_encoding
ifargs.output_file:
output_file=io.open(args.output_file, 'w', encoding=encoding)
else:
output_file=sys.stdout
try:
print_html(partial(print, file=output_file),
fileinput.input(args.files), title=args.title, encoding=encoding)
finally:
output_file.close()
if__name__=='__main__':
main()