-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwww.py
executable file
·274 lines (246 loc) · 8.37 KB
/
www.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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env python3
# On Windows OS piping might not work as expected for an app started by file association.
# For example:
# echo 123 | www.py
# Workarounds:
# * either call python explicitly: echo 123 | python www.py
# * or use a registry patch, ref: http://support.microsoft.com/default.aspx?kbid=321788
# (see also https://stackoverflow.com/questions/37451510/python-2-7-no-console-output-in-windows-10)
import sys
import os
import re
import platform
import subprocess
import tempfile
import codecs
def text_to_html(s):
s = s.replace("&", "&") # note: order maters
s = s.replace("<", "<")
s = s.replace(">", ">")
s = s.replace('"', """)
s = s.replace(' ', " ")
s = s.replace('\t', " ")
return s
def handle_input(i_f, o_f):
total_lines_generated = 0
total_lines_fetched = 0
total_chars_fetched = 0
template = get_html_template()
for tmpl_line in template.split("\n"):
if -1 == tmpl_line.find("<!-- OUTPUT -->"):
o_f.write(tmpl_line + "\n")
total_lines_generated += 1
else:
for line in i_f.readlines():
total_lines_fetched += 1
total_chars_fetched += len(line)
line = line.rstrip()
if len(line) == 0:
line = " "
htmline = "<div>" + text_to_html(line) + "</div>"
o_f.write(htmline + "\n")
total_lines_generated += 1
return { "total_lines_fetched": total_lines_fetched, "total_lines_generated": total_lines_generated, "total_chars_fetched": total_chars_fetched}
def get_html_template():
return """
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Dummy</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<style type="text/css">
.sys
{
font-size: small;
font-family: arial;
}
div
{
font-size: normal;
font-family: monospace;
white-space: nowrap;
}
</style>
<script type="text/javascript" charset="utf-8">
function enum_elements(predicate, action) {
var ps = document.getElementsByTagName("div");
for (var i = 0; i < ps.length; i++) {
var str = ps[i].textContent;
action(ps[i], predicate(str));
}
}
function get_template()
{
return document.getElementById("grep_template").value;
}
function get_inverse()
{
return document.getElementById("grep_inverse").checked;
}
function grep_predicate(s)
{
template = get_template();
inverse = get_inverse();
result = true;
if (template.length > 0)
{
var re = new RegExp(template);
result = re.test(s);
}
return inverse ? !result : result;
}
function grep_action(e, state) {
if (!state) {
e.style.display = 'none'
} else {
e.style.display = 'block'
}
}
function mark_action(e, state) {
if (state) {
e.style.background = document.getElementById("mark_color").value
} else {
}
}
function update_color() {
o = document.getElementById("mark_color")
o.style.background = o.value
}
function grep() {
enum_elements(grep_predicate, grep_action);
}
function mark() {
enum_elements(grep_predicate, mark_action);
}
function auto_action() {
if (document.getElementById("action_grep").checked)
grep();
else if (document.getElementById("action_mark").checked)
mark();
}
var grep_timer;
function auto_grep(e) {
clearTimeout(grep_timer);
is_online = document.getElementById("online_grep").checked;
if (is_online) {
grep_timer = setTimeout( grep, 200 );
} else if (e && e.keyCode == 13) {
grep();
}
}
var color_timer;
function auto_color(e) {
clearTimeout(color_timer);
if (e && e.keyCode == 13) {
update_color();
}
else {
color_timer = setTimeout( update_color, 200 );
};
}
</script>
</head>
<body>
<table class="sys">
<tr>
<td>
<input type="text" id="grep_template" onkeyup="auto_grep(event)" />
<input type="checkbox" name="online_grep" id="online_grep" checked="checked" />incremental
<input type="checkbox" name="grep_inverse" id="grep_inverse" />inverse
<input type="button" value="apply color" onclick="mark()" />
<input type="text" id="mark_color" value="" onkeyup="auto_color(event)" />
</td>
</tr>
</table>
<!-- OUTPUT -->
</body>
</html>
"""
def shell_open_file(filename):
if platform.system() == "Windows":
os.startfile(filename)
return True
elif platform.system() == "Linux":
prc = subprocess.Popen(['xdg-open', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
prc.wait()
return True
elif platform.system() == "Darwin":
prc = subprocess.Popen(['open', filename], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
prc.wait()
return True
return False
def get_flag(flag, args=sys.argv):
try:
args.index(flag)
return True
except:
return False
def get_option(option, args=sys.argv):
try:
idx = args.index(option)
return args[idx + 1]
except:
return None
def get_help_msg():
return """
--help prints this help message
--input value explicitly specifies an input file (otherwise input is read from STDIN)
--encoding value defines encoding to be used with an input file (valid only with --input), e.g. utf_8, utf_16_le, cp1251
--test (for testing purposes) performs all the work without actually opening the browser
--stat (for testing purposes) outputs number of lines fetched & generated while handling the input
"""
def htmlize(args=sys.argv):
if get_flag("--help", args=args):
print (get_help_msg())
exit(0)
stdout_data = []
testmode = get_flag("--test", args=args)
verbose = testmode or get_flag("--verbose", args=args)
statmode = get_flag("--stat", args=args)
encoding = get_option("--encoding", args=args)
input_filename = get_option("--input", args=args)
if None != input_filename:
assert os.path.isfile(input_filename), "--input keyword should be followed with an existing file name"
in_file = codecs.open(input_filename, "r", encoding=encoding)
else:
in_file = sys.stdin
(o_fd, o_filename) = tempfile.mkstemp('-www.html')
o_fp = os.fdopen(o_fd, "w")
stats = handle_input(in_file, o_fp)
o_fp.close()
if not testmode:
shell_open_file(o_filename)
if statmode:
for (k, v) in stats.items():
stdout_data.append("%s: %s" % (k, v))
if verbose:
stdout_data.append("output: %s" % (o_filename))
return stdout_data
def selftest(testdir):
root = os.path.abspath(testdir)
for item in sorted(os.listdir(root)):
fullname = os.path.join(root, item)
if not os.path.isfile(fullname):
continue
m = re.search(r'\-enc\-([\w\d\_\-]+)\.', item)
if m:
encoding = m.group(1)
args = [
"--input", fullname,
"--encoding", encoding,
"--test",
"--stat"
]
print ("invoking:", " ".join(args))
try:
res = htmlize(args=args)
except Exception as e:
res = [ "Exception: %s" % (str(e)) ]
for s in res: print (s)
if __name__=="__main__":
sanitydir = get_option("--sanitydir")
if sanitydir and os.path.isdir(sanitydir):
selftest(sanitydir)
else:
res = htmlize(sys.argv)
for s in res: print (s)
exit()