-
Notifications
You must be signed in to change notification settings - Fork 12
/
kernel.py
232 lines (188 loc) · 6.86 KB
/
kernel.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
from collections import deque
import contextlib
import io
from ipykernel.kernelbase import Kernel
import os
import shutil
import subprocess
import sys
from tempfile import TemporaryDirectory
class ElmKernel(Kernel):
implementation = 'elm_kernel'
implementation_version = '0.21.1'
language = 'no-op'
language_version = '0.19.1'
language_info = {'name': 'elm',
'codemirror_mode': 'elm',
'mimetype': 'text/x-elm',
'file_extension': '.elm'}
banner = "Display Elm output"
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._code = []
self._tempdir = TemporaryDirectory()
def do_shutdown(self, restart):
self._tempdir.cleanup()
def do_execute(self, code, silent,
store_history=True,
user_expressions=None,
allow_stdin=False):
self._code.append(code)
if self._should_compile():
try:
code = "\n".join(self._code)
self._code = []
self._compile(code)
except Exception as exc:
self._send_error_result(str(exc))
return {
'status': 'error',
'execution_count': self.execution_count,
}
return {
'status': 'ok',
'execution_count': self.execution_count,
'payload': [],
'user_expressions': {},
}
@contextlib.contextmanager
def _temp_path(self, filename):
"""Yield `filename` inside the tempdir, but don't actually create the file.
Then, on exit, delete the file if it exists.
"""
try:
path = os.path.join(self._tempdir.name, filename)
yield path
finally:
with contextlib.suppress(OSError):
if os.path.isfile(path) or os.path.islink(path):
os.remove(path)
else:
shutil.rmtree(path, ignore_errors=True)
def _elm_init(self):
''' Generate an init file in the temporary directory
'''
proc = subprocess.Popen(
['elm', 'init'],
cwd=self._tempdir.name,
stdin=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding=sys.getdefaultencoding())
# respond to prompt in 'elm init'
proc.communicate(input="y\n")
proc.wait()
def _elm_make(self, infile, outfile):
subprocess.run(
['elm', 'make',
infile, '--output={}'.format(outfile)],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
cwd=self._tempdir.name,
encoding=sys.getdefaultencoding())
def _compile(self, code):
self._link_build_environment()
with self._temp_path('input.elm') as infile,\
self._temp_path('index.js') as outfile,\
self._temp_path('elm.json') as elm_json,\
self._temp_path('src') as src_path:
with open(infile, mode='wt') as f:
f.write(code)
try:
# if elm.json doesn't exist yet, create it
if not os.path.lexists(elm_json):
self._elm_init()
if not os.path.lexists(src_path):
os.mkdir(src_path)
self._elm_make(infile, outfile)
with open(outfile, mode='rt') as f:
javascript = f.read()
self._send_success_result(javascript)
except subprocess.CalledProcessError as err:
# When compilation fails we send the compiler output to the
# user but we don't count this as an error. A compiler error
# might actually be the desired output of the cell.
self._send_error_result(err.stdout)
except Exception as err:
self._send_error_result(repr(err))
raise
def _should_compile(self):
assert self._code, "Should not be querying for compilation with no code!"
lines = deque(io.StringIO(self._code[-1]), 1)
return lines[0] == '-- compile-code' if lines else False
def _send_error_result(self, msg):
"""Send an error message to the client.
`msg` is the message to be sent to the client.
"""
self.send_response(
self.iopub_socket,
'display_data',
{
'metadata': {},
'data': {
'text/html': '<pre>{}</pre>'.format(msg)
}
}
)
def _send_success_result(self, javascript):
"""Send messages to the client with the results of a successful compilation.
`javascript` is the javascript generated by elm-make.
"""
# TODO: pull module name from `code`
module_name = "Main"
div_id = 'elm-div-' + str(self.execution_count)
template = """
var defineElm = function(cb) {{
if (this.Elm) {{
this.oldElm = this.Elm;
}}
var define = null;
{js}
cb();
}}
;
var obj = new Object();
defineElm.bind(obj)(function(){{
var mountNode = document.getElementById('{div_id}');
obj.Elm. {module_name}.init({{ node: mountNode }});
}});
"""
javascript = template.format(
js=javascript,
module_name=module_name,
div_id=div_id)
self.send_response(
self.iopub_socket,
'display_data',
{
'metadata': {},
'data': {
'text/html': '<div id="' + div_id + '"></div>'
}
}
)
self.send_response(
self.iopub_socket,
'display_data',
{
'metadata': {},
'data': {
'application/javascript': javascript
}
})
def _link_build_environment(self):
"""Link elm.json and src to temporary directory where elm code is compiled
"""
# existence of elm.json is not mandatory
if os.path.isfile('elm.json'):
# symlink requires abolute path
os.symlink(
os.path.join(os.getcwd(), 'elm.json'),
os.path.join(self._tempdir.name, 'elm.json'))
if os.path.isdir('src'):
os.symlink(
os.path.join(os.getcwd(), 'src'),
os.path.join(self._tempdir.name, 'src'))
if __name__ == '__main__':
from ipykernel.kernelapp import IPKernelApp
IPKernelApp.launch_instance(kernel_class=ElmKernel)