-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdeansi.py
executable file
·260 lines (219 loc) · 6.63 KB
/
deansi.py
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
#!/usr/bin/env python
"""
Copyright 2012 David Garcia Garzon
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
__doc__ = """\
This module provides functions to convert terminal output including
ansi terminal codes to stylable html.
The main entry point are 'deansi(input)' which performs the conversion
on an input string and 'styleSheet' which provides a minimal style sheet.
You can overwrite stylesheets by placing new rules after this minimal one.
"""
# TODO: Support empty m, being like 0m
# TODO: Support 38 and 38 (next attrib is a 256 palette color (xterm?))
# TODO: Support 51-55 decorations (framed, encircled, overlined, no frame/encircled, no overline)
import re
# python3 compatibility
try:
from html import escape as _htmlescape
htmlescape=lambda s: _htmlescape(s,quote=False)
except ImportError:
from cgi import escape as htmlescape
try:
xrange
except NameError:
xrange=range
colorCodes = {
0 : 'black',
1 : 'red',
2 : 'green',
3 : 'yellow',
4 : 'blue',
5 : 'magenta',
6 : 'cyan',
7 : 'white',
}
attribCodes = {
1 : 'bright',
2 : 'faint',
3 : 'italic',
4 : 'underscore',
5 : 'blink',
# TODO: Chek that 6 is ignored on enable and disable or enable it
# 6 : 'blink_rapid',
7 : 'reverse',
8 : 'hide',
9 : 'strike',
}
variations = [ # normal, pale, bright
('black', 'black', 'gray'),
('red', 'darkred', 'red'),
('green', 'darkgreen', 'green'),
('yellow', 'orange', 'yellow'),
('blue', 'darkblue', 'blue'),
('magenta', 'purple', 'magenta'),
('cyan', 'darkcyan', 'cyan'),
('white', 'lightgray', 'white'),
]
def styleSheet(brightColors=True) :
"""\
Returns a minimal css stylesheet so that deansi output
could be displayed properly in a browser.
You can append more rules to modify this default
stylesheet.
brightColors: set it to False to use the same color
when bright attribute is set and when not.
"""
simpleColors = [
".ansi_%s { color: %s; }" % (normal, normal)
for normal, pale, bright in variations]
paleColors = [
".ansi_%s { color: %s; }" % (normal, pale)
for normal, pale, bright in variations]
lightColors = [
".ansi_bright.ansi_%s { color: %s; }" % (normal, bright)
for normal, pale, bright in variations]
bgcolors = [
".ansi_bg%s { background-color: %s; }" % (normal, normal)
for normal, pale, bright in variations]
attributes = [
".ansi_bright { font-weight: bold; }",
".ansi_faint { opacity: .5; }",
".ansi_italic { font-style: italic; }",
".ansi_underscore { text-decoration: underline; }",
".ansi_blink { text-decoration: blink; }",
".ansi_reverse { border: 1pt solid; }",
".ansi_hide { opacity: 0; }",
".ansi_strike { text-decoration: line-through; }",
]
return '\n'.join(
[ ".ansi_terminal { white-space: pre; font-family: monospace; }", ]
+ (paleColors+lightColors if brightColors else simpleColors)
+ bgcolors
+ attributes
)
def ansiAttributes(block) :
"""Given a sequence "[XX;XX;XXmMy Text", where XX are ansi
attribute codes, returns a tuple with the list of extracted
ansi codes and the remaining text 'My Text'"""
attributeRe = re.compile( r'^[[](\d+(?:;\d+)*)?m')
match = attributeRe.match(block)
if not match : return [], block
if match.group(1) is None : return [0], block[2:]
return [int(code) for code in match.group(1).split(";")], block[match.end(1)+1:]
def ansiState(code, attribs, fg, bg) :
"""Keeps track of the ansi attribute state given a new code"""
if code == 0 : return set(), None, None # reset all
if code == 39 : return attribs, None, bg # default fg
if code == 49 : return attribs, fg, None # default bg
# foreground color
if code in xrange(30,38) :
return attribs, colorCodes[code-30], bg
# background color
if code in xrange(40,48) :
return attribs, fg, colorCodes[code-40]
# attribute setting
if code in attribCodes :
attribs.add(attribCodes[code])
# attribute resetting
if code in xrange(21,30) and code-20 in attribCodes :
toRemove = attribCodes[code-20]
if toRemove in attribs :
attribs.remove(toRemove)
return attribs, fg, bg
def stateToClasses(attribs, fg, bg) :
"""Returns css class names given a given ansi attribute state"""
return " ".join(
["ansi_"+attrib for attrib in sorted(attribs)]
+ (["ansi_"+fg] if fg else [])
+ (["ansi_bg"+bg] if bg else [])
)
def deansi(text) :
text = htmlescape(text)
blocks = text.split("\033")
state = set(), None, None
ansiBlocks = blocks[:1]
for block in blocks[1:] :
attributeCodes, plain = ansiAttributes(block)
for code in attributeCodes : state = ansiState(code, *state)
classes = stateToClasses(*state)
ansiBlocks.append(
(("<span class='%s'>"%classes) + plain + "</span>")
if classes else plain
)
text = "".join(ansiBlocks)
return text
def main():
import sys
import argparse
parser = argparse.ArgumentParser(
description="Converts coloured console output into equivalent HTML",
)
parser.add_argument(
'-s',
'--style',
metavar='FILE',
help="use FILE as stylesheet",
)
parser.add_argument(
'-t',
'--template',
metavar='FILE',
help="use FILE as html template",
)
parser.add_argument(
'--dark',
action='store_true',
help="use the dark background style",
)
parser.add_argument(
'input',
metavar="INPUT_FILE",
nargs='?',
help="the console input to convert (default stdin)"
)
parser.add_argument(
'output',
metavar="OUTPUT_FILE",
nargs='?',
help="the file where to drop the html output (default stdout)"
)
args = parser.parse_args()
default_template = """\
<style>
%s
</style>
<div class='ansi_terminal'>%s</div>
"""
with open(args.input) if args.input else sys.stdin as inputFile:
deansied = deansi(inputFile.read())
if args.template:
with open(args.template) as templateFile:
template = templateFile.read()
else:
template = default_template
if args.style:
with open(args.style) as styleFile:
style = styleFile.read()
else:
style = styleSheet()
if args.dark:
style += """\n.ansi_terminal { background-color: #222; color: #cfc; }"""
with open(args.output) if args.output else sys.stdout as outputFile:
outputFile.write(template % (
style,
deansied,
))
sys.exit(0)
if __name__ == "__main__" :
main()