-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathneptyne.py
237 lines (199 loc) · 6.5 KB
/
neptyne.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
from pprint import pprint, pformat
import jupyter_kernel_mgmt as jkm
import asyncio
import aionotify
import aiohttp
from aiohttp import web
import os
from utils import *
import document
from document import Document
connections = []
docs = {}
async def watch(connections, initial_files=[]):
assert not docs, 'Watch already started'
async def doc(filename):
if filename not in docs:
docs[filename] = await Document(filename, connections)
return docs[filename]
async def do(filename, body):
d = await doc(filename)
d.new_body(body)
for filename in initial_files:
await do(filename, open(filename, 'r').read())
watcher = aionotify.Watcher()
watcher.watch(path='.', flags=aionotify.Flags.CLOSE_WRITE)
loop = asyncio.get_event_loop()
await watcher.setup(asyncio.get_event_loop())
while True:
event = await watcher.get_event()
# print('event:', event)
filename = event.name
if filename in initial_files:
body = open(filename, 'r').read()
await do(filename, body)
if filename == '.requests':
contents = open('.requests', 'r').read()
params = dotdict()
lines = contents.split('\n')
for i, line in enumerate(lines):
if ' ' not in line:
continue
k, v = line.split(' ', 1)
if k == '---':
body = '\n'.join(lines[i+1:])
break
params[k] = v
params.body = body
for k, v in params.items():
if 'cursor_' in k:
params[k] = int(v)
# print(pformat(params))
if params.type == 'process':
await do(params.bufname, body)
elif params.type in {'restart', 'complete', 'inspect'}:
d = await doc(params.bufname)
await d[params.type](**params)
else:
print('Unknown request:', pformat(params))
app = web.Application()
routes = web.RouteTableDef()
@routes.get('/ws')
async def websocket_connection(request):
websocket = web.WebSocketResponse()
await websocket.prepare(request)
q = asyncio.Queue()
async def fwd(filename, state):
await q.put((filename, state))
connections.append(fwd)
for _, d in docs.items():
d.broadcast()
sent = set()
while True:
filename, state = await q.get()
await websocket.send_json(state.all)
return websocket
def track(url):
url = repr(url)
track="""
"use strict";
{
let i = 0
const reimported = {}
const sloppy = s => s.replace(/.*\//g, '')
window.reimport = src => {
// console.log('Reimporting', src)
reimported[sloppy(src)] = true
return import('./static/' + src + '#' + i++)
}
const tracked = {}
window.track = src => {
if (!tracked[src]) {
console.log('Tracking', src)
tracked[src] = true;
reimport(src)
}
}
try {
if (window.track_ws.readyState != websocket.OPEN) {
window.track_ws.close()
}
} catch {}
const ws_url = 'ws://' + window.location.host + '/inotify'
window.track_ws = new WebSocket(ws_url)
window.track_ws.onmessage = msg => {
// console.log(sloppy(msg.data), ...Object.keys(reimported))
const upd = sloppy(msg.data)
if (reimported[upd]) {
Object.keys(tracked).forEach(src => {
console.log('Reloading', src, 'because', upd, 'was updated')
reimport(src)
})
}
}
}
"""
text=f"""
<html>
<head>
<script type="module">
{track}
track({url})
</script>
</head>
<body></body>
</html>
"""
return web.Response(text=text, content_type='text/html')
@routes.get('/{track}.js')
def _track(request):
return track(request.match_info.get('track') + '.js')
@routes.get('/')
def root(request):
return track('index.js')
static_dir = os.environ.get('NEPTYNE_DEV_DIR', os.path.dirname(__file__) or '.')
app.add_routes([
web.static('/static/', static_dir, show_index=True, append_version=True),
])
@routes.get('/inotify')
async def inotify_websocket(request):
print('request', request)
websocket = web.WebSocketResponse()
await websocket.prepare(request)
watcher = aionotify.Watcher()
watcher.watch(path=static_dir, flags=aionotify.Flags.CLOSE_WRITE)
loop = asyncio.get_event_loop()
await watcher.setup(loop)
while True:
event = await watcher.get_event()
# print(event)
await websocket.send_str(event.name)
watcher.close()
return websocket
app.router.add_routes(routes)
async def main():
import sys
if sys.argv[1:2] == ['test']:
await document.test()
elif sys.argv[1:2] == ['kak_source']:
print(open(os.path.join(static_dir, 'neptyne.kak'), 'r').read())
else:
connections.append(document.stdout_connection)
port = 8234
host = '127.0.0.1'
args = list(sys.argv[1:])
browser = False
while len(args) >= 1 and args[0].startswith('-'):
two = len(args) >= 2
if args[0] == '--browser':
browser = True
args = args[1:]
elif two and args[0].startswith('-p'):
port = int(args[1])
args = args[2:]
elif two and args[0].startswith('-b'):
host = args[1]
args = args[2:]
elif two and args[0].startswith('-h'):
print('neptyne [-p PORT] [-b BIND_ADDR] --browser [FILES...]')
sys.exit(0)
else:
raise 'Unknown flag: ' + args[0]
if browser:
import subprocess
subprocess.Popen(f'chromium --app=http://localhost:{port} & disown', shell=True)
runner = web.AppRunner(app, access_log_format='%t %a %s %r')
await runner.setup()
site = web.TCPSite(runner, host, port)
await site.start()
await watch(connections, args)
await runner.cleanup()
def sync_main():
try:
asyncio.run(main())
except Exception as e:
import traceback as tb
tb.print_exc()
asyncio.run(document.close_documents())
if __name__ == '__main__':
sync_main()