This repository has been archived by the owner on Jun 8, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
luxembourg.py
executable file
·157 lines (131 loc) · 4.56 KB
/
luxembourg.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
#!/usr/bin/env python3
from pathlib import Path
from tempfile import NamedTemporaryFile
import re
import json
from urllib.parse import parse_qs
def walk(root):
hoover = root / '.hoover'
hoover.mkdir(exist_ok=True)
tmp = NamedTemporaryFile('wt', encoding='utf8',
dir=str(hoover), delete=False)
try:
with tmp:
for file in root.glob('**/*.html'):
path = file.relative_to(root)
mtime = file.stat().st_mtime
print(path, mtime, file=tmp)
Path(tmp.name).rename(hoover / 'index.txt')
except:
Path(tmp.name).unlink()
raise
def _walk_subparser(commands):
parser = commands.add_parser('walk')
parser.set_defaults(handler=lambda root, options: walk(root))
walk.subparser = _walk_subparser
def touch_all(root):
for file in root.glob('**/*.html'):
file.touch()
def _touch_all_subparser(commands):
parser = commands.add_parser('touch_all')
parser.set_defaults(handler=lambda root, options: touch_all(root))
touch_all.subparser = _touch_all_subparser
def _index(root):
with (root / '.hoover' / 'index.txt').open(encoding='utf8') as f:
lines = (line.strip().split() for line in f)
pairs = ((Path(p), t) for p, t in lines)
return {
p.stem: {
'path': p,
'version': v,
'sort': '{}:{}'.format(int(float(v)), p.stem),
}
for p, v in pairs
}
def _digest(id, path, version):
with path.open(encoding='latin1') as f:
html = f.read()
text = ' '.join(re.sub(r'<[^>]*>', ' ', html).split())
return {
'id': id,
'version': version,
'content': {
'title': path.stem,
'text': text,
},
'views': [
{'name': "html", 'url': str(path)},
],
}
def digest(root, id):
index = _index(root)
doc = index[id]
return _digest(id, root / doc['path'], doc['version'])
def _digest_subparser(commands):
parser = commands.add_parser('digest')
parser.add_argument('id')
parser.set_defaults(handler=lambda root, options:
print(digest(root, options.id)))
digest.subparser = _digest_subparser
def serve(root, listen):
from wsgiref.simple_server import make_server
(host, port) = listen.split(':')
index = _index(root)
sorted_ids = sorted(index, key=lambda i: index[i]['sort'], reverse=True)
def json_response(environ, start_response, data):
start_response('200 OK', [('Content-Type', 'application/json')])
data = json.dumps(data, indent=2, sort_keys=True) + '\n'
return [data.encode('utf8')]
def meta_view(environ, start_response):
return json_response(environ, start_response, {
'name': "Luxembourg Companies",
'feed': 'feed',
})
def feed_view(environ, start_response):
lt = parse_qs(environ['QUERY_STRING']).get('lt', [None])[0]
documents = []
for id in sorted_ids:
sort = index[id]['sort']
if lt is None or sort < lt:
path = index[id]['path']
documents.append(_digest(id, root / path, index[id]['version']))
if len(documents) >= 100:
break
resp = {'documents': documents}
if documents:
resp['next'] = '?lt={}'.format(sort)
return json_response(environ, start_response, resp)
routes = [
(r'/$', meta_view),
(r'/feed$', feed_view),
]
def wsgiapp(environ, start_response):
for rule, handler in routes:
match = re.match(rule, environ['PATH_INFO'])
if match:
return handler(environ, start_response, **match.groupdict())
start_response('404 Not Found', [])
return [b'noting here\n']
httpd = make_server(host, int(port), wsgiapp)
print('serving on', host, port)
httpd.serve_forever()
def _serve_subparser(commands):
parser = commands.add_parser('serve')
parser.add_argument('listen')
parser.set_defaults(handler=lambda root, options:
serve(root, options.listen))
serve.subparser = _serve_subparser
def main():
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('-d', '--data')
commands = parser.add_subparsers()
walk.subparser(commands)
touch_all.subparser(commands)
digest.subparser(commands)
serve.subparser(commands)
options = parser.parse_args()
root = Path(options.data).resolve()
options.handler(root, options)
if __name__ == '__main__':
main()