| 1 |
""" |
| 2 |
MIT License |
| 3 |
|
| 4 |
Copyright (c) 2021-2026 Tobias Enderle |
| 5 |
|
| 6 |
Permission is hereby granted, free of charge, to any person obtaining a |
| 7 |
copy of this software and associated documentation files (the "Software"), |
| 8 |
to deal in the Software without restriction, including without limitation |
| 9 |
the rights to use, copy, modify, merge, publish, distribute, sublicense, |
| 10 |
and/or sell copies of the Software, and to permit persons to whom the |
| 11 |
Software is furnished to do so, subject to the following conditions: |
| 12 |
|
| 13 |
The above copyright notice and this permission notice shall be included |
| 14 |
in all copies or substantial portions of the Software. |
| 15 |
|
| 16 |
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS |
| 17 |
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 |
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 |
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 |
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 21 |
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS |
| 22 |
IN THE SOFTWARE. |
| 23 |
""" |
| 24 |
|
| 25 |
from code import InteractiveInterpreter, compile_command |
| 26 |
import traceback |
| 27 |
from io import StringIO |
| 28 |
from contextlib import redirect_stdout, redirect_stderr |
| 29 |
import socketserver |
| 30 |
import json |
| 31 |
import textwrap |
| 32 |
from collections import defaultdict |
| 33 |
import re |
| 34 |
import os |
| 35 |
import sys |
| 36 |
|
| 37 |
class PyLTTex: |
| 38 |
def __init__(self): |
| 39 |
self._log_buffer = [] |
| 40 |
|
| 41 |
def log(self, *objects, sep=' ', end='\n'): |
| 42 |
try: |
| 43 |
objects = [str(v) for v in objects] |
| 44 |
except Exception as exc: |
| 45 |
raise RuntimeError( |
| 46 |
'The object to log could not be transformed to a string.', |
| 47 |
) from exc |
| 48 |
self._log_buffer.append(sep.join(objects)) |
| 49 |
self._log_buffer.append(end) |
| 50 |
|
| 51 |
def _log_message(self): |
| 52 |
msg = ''.join(self._log_buffer) |
| 53 |
self._log_buffer = [] |
| 54 |
return msg |
| 55 |
|
| 56 |
class Interpreter(InteractiveInterpreter): |
| 57 |
def __init__(self): |
| 58 |
self.tex = PyLTTex() |
| 59 |
super().__init__({'tex': self.tex}) |
| 60 |
|
| 61 |
def execute_repl(self, code, ignore_errors): |
| 62 |
self.success = True |
| 63 |
output = '' |
| 64 |
incomplete = False |
| 65 |
for line in re.split('\r?\n', code): |
| 66 |
output += ('... ' if incomplete else '>>> ') + line + '\n' |
| 67 |
if incomplete: |
| 68 |
buffer += '\n' + line |
| 69 |
else: |
| 70 |
buffer = line |
| 71 |
with StringIO() as out, redirect_stdout(out), redirect_stderr(out): |
| 72 |
try: |
| 73 |
code_obj = compile_command(buffer) |
| 74 |
if code_obj is not None: |
| 75 |
incomplete = False |
| 76 |
self.runcode(code_obj) |
| 77 |
else: |
| 78 |
incomplete = True |
| 79 |
except: |
| 80 |
incomplete = False |
| 81 |
traceback.print_exc(limit=0) |
| 82 |
self.success = False |
| 83 |
output += out.getvalue() |
| 84 |
if not ignore_errors and not self.success: |
| 85 |
return False, output, self.tex._log_message() |
| 86 |
return self.success, output, self.tex._log_message() |
| 87 |
|
| 88 |
def execute(self, code): |
| 89 |
with StringIO() as out, redirect_stdout(out), redirect_stderr(out): |
| 90 |
self.success = True |
| 91 |
try: |
| 92 |
code_obj = compile_command(code, symbol='exec') |
| 93 |
if code_obj is None: |
| 94 |
print('Incomplete Python code:\n' + code) |
| 95 |
self.success = False |
| 96 |
else: |
| 97 |
self.runcode(code_obj) |
| 98 |
except: |
| 99 |
traceback.print_exc() |
| 100 |
self.success = False |
| 101 |
return self.success, out.getvalue(), self.tex._log_message() |
| 102 |
|
| 103 |
def showtraceback(self): |
| 104 |
super().showtraceback() |
| 105 |
self.success = False |
| 106 |
|
| 107 |
class Handler(socketserver.StreamRequestHandler): |
| 108 |
def handle(self): |
| 109 |
interpreters = defaultdict(Interpreter) |
| 110 |
while True: |
| 111 |
data = self.rfile.readline().decode('utf-8') |
| 112 |
if len(data) == 0: # socket closed, LuaTeX process finished |
| 113 |
return |
| 114 |
if data.strip() == 'shutdown': |
| 115 |
return |
| 116 |
|
| 117 |
data = json.loads(data) |
| 118 |
interpreter = interpreters[data['session']] |
| 119 |
code = textwrap.dedent(data['code']) |
| 120 |
if data['repl_mode']: |
| 121 |
success, output, log_msg = interpreter.execute_repl( |
| 122 |
code, |
| 123 |
data['ignore_errors'] |
| 124 |
) |
| 125 |
else: |
| 126 |
success, output, log_msg = interpreter.execute(code) |
| 127 |
response = { |
| 128 |
'success': success, |
| 129 |
'output': output, |
| 130 |
'log_msg': log_msg |
| 131 |
} |
| 132 |
self.wfile.write((json.dumps(response) + '\n').encode('utf-8')) |
| 133 |
|
| 134 |
if __name__ == '__main__': |
| 135 |
try: |
| 136 |
sys.path.insert(0, os.path.normpath(sys.argv[1])) |
| 137 |
except: |
| 138 |
pass |
| 139 |
|
| 140 |
with socketserver.TCPServer(('localhost', 0), Handler) as server: |
| 141 |
print(server.server_address[1], end='\n', flush=True) # publish port |
| 142 |
server.handle_request() |