regwright-kernel 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- regwright_kernel/__init__.py +3 -0
- regwright_kernel/__main__.py +19 -0
- regwright_kernel/install.py +75 -0
- regwright_kernel/kernel.py +301 -0
- regwright_kernel/logo-32x32.png +0 -0
- regwright_kernel/logo-64x64.png +0 -0
- regwright_kernel/logo-svg.svg +5 -0
- regwright_kernel/serve.py +199 -0
- regwright_kernel/words.json +982 -0
- regwright_kernel-0.1.0.data/data/share/jupyter/kernels/regwright/kernel.json +15 -0
- regwright_kernel-0.1.0.data/data/share/jupyter/kernels/regwright/logo-32x32.png +0 -0
- regwright_kernel-0.1.0.data/data/share/jupyter/kernels/regwright/logo-64x64.png +0 -0
- regwright_kernel-0.1.0.data/data/share/jupyter/kernels/regwright/logo-svg.svg +5 -0
- regwright_kernel-0.1.0.dist-info/METADATA +89 -0
- regwright_kernel-0.1.0.dist-info/RECORD +17 -0
- regwright_kernel-0.1.0.dist-info/WHEEL +4 -0
- regwright_kernel-0.1.0.dist-info/licenses/LICENSE +25 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""`python -m regwright_kernel` starts the kernel; `python -m regwright_kernel install` installs its spec."""
|
|
2
|
+
|
|
3
|
+
import sys
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def main() -> None:
|
|
7
|
+
if len(sys.argv) > 1 and sys.argv[1] == "install":
|
|
8
|
+
from .install import main as install_main
|
|
9
|
+
|
|
10
|
+
sys.exit(install_main(sys.argv[2:]))
|
|
11
|
+
from ipykernel.kernelapp import IPKernelApp
|
|
12
|
+
|
|
13
|
+
from .kernel import RegwrightKernel
|
|
14
|
+
|
|
15
|
+
IPKernelApp.launch_instance(kernel_class=RegwrightKernel)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
if __name__ == "__main__":
|
|
19
|
+
main()
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
"""Install the Regwright kernelspec so Jupyter lists "Regwright (Stata syntax)"."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import sys
|
|
10
|
+
import tempfile
|
|
11
|
+
from importlib import resources
|
|
12
|
+
|
|
13
|
+
KERNEL_NAME = "regwright"
|
|
14
|
+
DISPLAY_NAME = "Regwright (Stata syntax)"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def kernel_json(python: str | None = None) -> dict:
|
|
18
|
+
return {
|
|
19
|
+
"argv": [python or sys.executable, "-m", "regwright_kernel", "-f", "{connection_file}"],
|
|
20
|
+
"display_name": DISPLAY_NAME,
|
|
21
|
+
"language": "stata",
|
|
22
|
+
"interrupt_mode": "signal",
|
|
23
|
+
"metadata": {"debugger": False},
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def write_spec(directory: str, python: str | None = None) -> None:
|
|
28
|
+
os.makedirs(directory, exist_ok=True)
|
|
29
|
+
with open(os.path.join(directory, "kernel.json"), "w", encoding="utf-8") as f:
|
|
30
|
+
json.dump(kernel_json(python), f, indent=1)
|
|
31
|
+
pkg = resources.files(__package__)
|
|
32
|
+
for name in ("logo-32x32.png", "logo-64x64.png", "logo-svg.svg"):
|
|
33
|
+
src = pkg.joinpath(name)
|
|
34
|
+
if src.is_file():
|
|
35
|
+
with resources.as_file(src) as p:
|
|
36
|
+
shutil.copy(p, os.path.join(directory, name))
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def install(user: bool = False, prefix: str | None = None, sys_prefix: bool = False, name: str = KERNEL_NAME) -> str:
|
|
40
|
+
from jupyter_client.kernelspec import KernelSpecManager
|
|
41
|
+
|
|
42
|
+
if sys_prefix:
|
|
43
|
+
prefix = sys.prefix
|
|
44
|
+
if not user and prefix is None and not _can_write_system():
|
|
45
|
+
user = True
|
|
46
|
+
with tempfile.TemporaryDirectory() as td:
|
|
47
|
+
write_spec(td)
|
|
48
|
+
return KernelSpecManager().install_kernel_spec(td, name, user=user, prefix=prefix)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _can_write_system() -> bool:
|
|
52
|
+
from jupyter_core.paths import SYSTEM_JUPYTER_PATH
|
|
53
|
+
|
|
54
|
+
for p in SYSTEM_JUPYTER_PATH:
|
|
55
|
+
try:
|
|
56
|
+
os.makedirs(p, exist_ok=True)
|
|
57
|
+
return os.access(p, os.W_OK)
|
|
58
|
+
except OSError:
|
|
59
|
+
continue
|
|
60
|
+
return False
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def main(argv: list[str] | None = None) -> int:
|
|
64
|
+
ap = argparse.ArgumentParser(prog="python -m regwright_kernel install", description=f"Install the {DISPLAY_NAME} kernelspec.")
|
|
65
|
+
where = ap.add_mutually_exclusive_group()
|
|
66
|
+
where.add_argument("--user", action="store_true", help="install for the current user (default when the system folder is read-only)")
|
|
67
|
+
where.add_argument("--sys-prefix", action="store_true", help="install into this Python environment (venv/conda)")
|
|
68
|
+
where.add_argument("--prefix", help="install under PREFIX/share/jupyter/kernels")
|
|
69
|
+
ap.add_argument("--name", default=KERNEL_NAME, help="kernelspec name (default: regwright)")
|
|
70
|
+
a = ap.parse_args(argv)
|
|
71
|
+
dest = install(user=a.user, prefix=a.prefix, sys_prefix=a.sys_prefix, name=a.name)
|
|
72
|
+
print(f"Installed kernelspec {a.name!r} ({DISPLAY_NAME}) in {dest}")
|
|
73
|
+
if not shutil.which("regwright") and not os.environ.get("REGWRIGHT_PATH"):
|
|
74
|
+
print("Note: the regwright CLI is not on PATH. Install it from https://regwright.com or set REGWRIGHT_PATH.")
|
|
75
|
+
return 0
|
|
@@ -0,0 +1,301 @@
|
|
|
1
|
+
"""The Regwright Jupyter kernel: Stata syntax, executed by ``regwright serve``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import shutil
|
|
9
|
+
import tempfile
|
|
10
|
+
from importlib import resources
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
from ipykernel.kernelbase import Kernel
|
|
14
|
+
|
|
15
|
+
from . import __version__
|
|
16
|
+
from .serve import GraphWatcher, ServeError, ServeSession
|
|
17
|
+
|
|
18
|
+
_WORDS = json.loads(resources.files(__package__).joinpath("words.json").read_text(encoding="utf-8"))
|
|
19
|
+
COMMANDS: list[str] = _WORDS["commands"]
|
|
20
|
+
FUNCTIONS: list[str] = _WORDS["functions"]
|
|
21
|
+
DESCRIBE: dict[str, str] = _WORDS["describe"]
|
|
22
|
+
|
|
23
|
+
# Abbreviations that map to the full command for the inspector.
|
|
24
|
+
_ABBREV = {
|
|
25
|
+
"su": "summarize", "sum": "summarize", "summ": "summarize", "reg": "regress", "tab": "tabulate",
|
|
26
|
+
"ta": "tabulate", "gen": "generate", "g": "generate", "des": "describe", "d": "describe",
|
|
27
|
+
"li": "list", "l": "list", "di": "display", "dis": "display", "cap": "capture", "qui": "quietly",
|
|
28
|
+
"bys": "bysort", "corr": "correlate", "forval": "forvalues", "forv": "forvalues", "lab": "label",
|
|
29
|
+
"ren": "rename", "est": "estimates", "tw": "twoway", "sc": "scatter", "gr": "graph",
|
|
30
|
+
"hist": "histogram", "loc": "local", "gl": "global", "mat": "matrix", "prog": "program",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
_IDENT = re.compile(r"[A-Za-z0-9_]")
|
|
34
|
+
_PREFIXES = r"(?:quietly|quietl|quiet|quie|qui|noisily|noisil|noisi|nois|noi|capture|captur|captu|capt|cap)"
|
|
35
|
+
# Text before a token that means the token is a command name.
|
|
36
|
+
_STATEMENT_START = re.compile(
|
|
37
|
+
rf"(?:^|[:{{])\s*(?:{_PREFIXES}(?:\s*:\s*|\s+))*$"
|
|
38
|
+
)
|
|
39
|
+
_RC_LINE = re.compile(r"^r\((-?\d+)\);$")
|
|
40
|
+
_RED = "\x1b[0;31m"
|
|
41
|
+
_RESET = "\x1b[0m"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _token_bounds(code: str, cursor: int) -> tuple[int, int]:
|
|
45
|
+
start = cursor
|
|
46
|
+
while start > 0 and _IDENT.match(code[start - 1]):
|
|
47
|
+
start -= 1
|
|
48
|
+
end = cursor
|
|
49
|
+
while end < len(code) and _IDENT.match(code[end]):
|
|
50
|
+
end += 1
|
|
51
|
+
return start, end
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _line_before(code: str, pos: int) -> str:
|
|
55
|
+
"""Text of the logical line before `pos` (joining `///` continuations)."""
|
|
56
|
+
nl = code.rfind("\n", 0, pos)
|
|
57
|
+
line = code[nl + 1:pos]
|
|
58
|
+
while nl > 0:
|
|
59
|
+
prev_nl = code.rfind("\n", 0, nl)
|
|
60
|
+
prev = code[prev_nl + 1:nl]
|
|
61
|
+
if re.search(r"(?:^|\s)///", prev):
|
|
62
|
+
line = re.sub(r"(?:^|\s)///.*$", " ", prev) + line
|
|
63
|
+
nl = prev_nl
|
|
64
|
+
else:
|
|
65
|
+
break
|
|
66
|
+
return line
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def is_command_position(code: str, start: int) -> bool:
|
|
70
|
+
return bool(_STATEMENT_START.search(_line_before(code, start)))
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def is_complete(code: str) -> str:
|
|
74
|
+
"""'complete' or 'incomplete' (open block, continuation, comment or compound string)."""
|
|
75
|
+
depth = 0
|
|
76
|
+
comment = 0
|
|
77
|
+
lines = code.split("\n")
|
|
78
|
+
for line in lines:
|
|
79
|
+
i = 0
|
|
80
|
+
while i < len(line):
|
|
81
|
+
two = line[i:i + 2]
|
|
82
|
+
if comment:
|
|
83
|
+
if two == "/*":
|
|
84
|
+
comment += 1
|
|
85
|
+
i += 2
|
|
86
|
+
elif two == "*/":
|
|
87
|
+
comment -= 1
|
|
88
|
+
i += 2
|
|
89
|
+
else:
|
|
90
|
+
i += 1
|
|
91
|
+
continue
|
|
92
|
+
if two == "/*":
|
|
93
|
+
comment += 1
|
|
94
|
+
i += 2
|
|
95
|
+
continue
|
|
96
|
+
if two == "//" and (i == 0 or line[i - 1].isspace()):
|
|
97
|
+
break
|
|
98
|
+
ch = line[i]
|
|
99
|
+
if ch == '"':
|
|
100
|
+
j = line.find('"', i + 1)
|
|
101
|
+
i = len(line) if j < 0 else j + 1
|
|
102
|
+
continue
|
|
103
|
+
if ch == "{":
|
|
104
|
+
depth += 1
|
|
105
|
+
elif ch == "}":
|
|
106
|
+
depth -= 1
|
|
107
|
+
i += 1
|
|
108
|
+
last = lines[-1] if lines else ""
|
|
109
|
+
if comment > 0 or depth > 0 or re.search(r"(?:^|\s)///\s*$", last):
|
|
110
|
+
return "incomplete"
|
|
111
|
+
if re.match(r"^\s*(?:program(?:\s+define)?\s+\w+|mata\s*:?)\s*(?:,.*)?$", code.split("\n")[0]) and not re.search(r"(?m)^\s*end\s*$", code):
|
|
112
|
+
return "incomplete"
|
|
113
|
+
return "complete"
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
class RegwrightKernel(Kernel):
|
|
117
|
+
implementation = "regwright_kernel"
|
|
118
|
+
implementation_version = __version__
|
|
119
|
+
language = "stata"
|
|
120
|
+
language_version = "Regwright"
|
|
121
|
+
language_info = {
|
|
122
|
+
"name": "stata",
|
|
123
|
+
"mimetype": "text/x-stata",
|
|
124
|
+
"file_extension": ".do",
|
|
125
|
+
"codemirror_mode": "stata",
|
|
126
|
+
"pygments_lexer": "stata",
|
|
127
|
+
}
|
|
128
|
+
banner = "Regwright: Stata syntax without Stata (https://regwright.com)"
|
|
129
|
+
help_links = [{"text": "Regwright", "url": "https://regwright.com"}]
|
|
130
|
+
|
|
131
|
+
def __init__(self, **kwargs):
|
|
132
|
+
super().__init__(**kwargs)
|
|
133
|
+
self._graph_dir = Path(tempfile.mkdtemp(prefix="regwright-kernel-graphs-"))
|
|
134
|
+
self._graphs = GraphWatcher(self._graph_dir)
|
|
135
|
+
self._echo = os.environ.get("REGWRIGHT_KERNEL_ECHO", "0") not in ("", "0", "false", "no")
|
|
136
|
+
self._session: ServeSession | None = None
|
|
137
|
+
self._vars: list[dict] = []
|
|
138
|
+
self._nobs = 0
|
|
139
|
+
|
|
140
|
+
# ----- session -----
|
|
141
|
+
|
|
142
|
+
def _ensure(self) -> ServeSession:
|
|
143
|
+
if self._session is None or not self._session.running:
|
|
144
|
+
self._session = ServeSession(graph_dir=str(self._graph_dir))
|
|
145
|
+
self._session.start()
|
|
146
|
+
try:
|
|
147
|
+
self._session.chdir(os.getcwd())
|
|
148
|
+
except ServeError:
|
|
149
|
+
pass
|
|
150
|
+
return self._session
|
|
151
|
+
|
|
152
|
+
def _refresh_vars(self) -> None:
|
|
153
|
+
try:
|
|
154
|
+
d = self._ensure().describe()
|
|
155
|
+
self._vars = d.get("vars") or []
|
|
156
|
+
self._nobs = d.get("nobs") or 0
|
|
157
|
+
except ServeError:
|
|
158
|
+
self._vars = []
|
|
159
|
+
|
|
160
|
+
def _stream(self, name: str, text: str) -> None:
|
|
161
|
+
if text:
|
|
162
|
+
self.send_response(self.iopub_socket, "stream", {"name": name, "text": text})
|
|
163
|
+
|
|
164
|
+
# ----- execute -----
|
|
165
|
+
|
|
166
|
+
def do_execute(self, code, silent, store_history=True, user_expressions=None, allow_stdin=False):
|
|
167
|
+
if not code.strip():
|
|
168
|
+
return self._ok()
|
|
169
|
+
try:
|
|
170
|
+
session = self._ensure()
|
|
171
|
+
self._graphs.snapshot()
|
|
172
|
+
reply = session.run(code)
|
|
173
|
+
except KeyboardInterrupt:
|
|
174
|
+
if self._session:
|
|
175
|
+
self._session.kill()
|
|
176
|
+
self._vars = []
|
|
177
|
+
return self._error(1, "--Break--", ["--Break-- (the session was restarted; data in memory was cleared)"], silent)
|
|
178
|
+
except ServeError as e:
|
|
179
|
+
return self._error(-1, str(e), [str(e)], silent, ename="RegwrightError")
|
|
180
|
+
|
|
181
|
+
rc = int(reply.get("rc", 0))
|
|
182
|
+
lines = reply.get("lines") or []
|
|
183
|
+
notes = session.take_stderr()
|
|
184
|
+
if not silent:
|
|
185
|
+
if notes.strip():
|
|
186
|
+
self._stream("stderr", notes if notes.endswith("\n") else notes + "\n")
|
|
187
|
+
# Group consecutive lines by stream so output keeps its order.
|
|
188
|
+
buf: list[str] = []
|
|
189
|
+
cur = None
|
|
190
|
+
for ln in lines:
|
|
191
|
+
kind = ln.get("kind")
|
|
192
|
+
text = ln.get("text", "")
|
|
193
|
+
if kind == "input" and not self._echo:
|
|
194
|
+
continue
|
|
195
|
+
if kind == "error" and _RC_LINE.match(text.strip()):
|
|
196
|
+
continue # shown in the error message below
|
|
197
|
+
name = "stderr" if kind == "error" else "stdout"
|
|
198
|
+
if name != cur and buf:
|
|
199
|
+
self._stream(cur, "\n".join(buf) + "\n")
|
|
200
|
+
buf = []
|
|
201
|
+
cur = name
|
|
202
|
+
buf.append(text)
|
|
203
|
+
if buf:
|
|
204
|
+
self._stream(cur, "\n".join(buf) + "\n")
|
|
205
|
+
for name, svg in self._graphs.changed():
|
|
206
|
+
self.send_response(
|
|
207
|
+
self.iopub_socket,
|
|
208
|
+
"display_data",
|
|
209
|
+
{"data": {"image/svg+xml": svg, "text/plain": f"<Regwright graph {name}>"}, "metadata": {}},
|
|
210
|
+
)
|
|
211
|
+
self._refresh_vars()
|
|
212
|
+
if rc != 0:
|
|
213
|
+
msgs = [ln.get("text", "") for ln in lines if ln.get("kind") == "error" and not _RC_LINE.match(ln.get("text", "").strip())]
|
|
214
|
+
return self._error(rc, msgs[0] if msgs else f"r({rc});", [], silent, already_streamed=True)
|
|
215
|
+
return self._ok()
|
|
216
|
+
|
|
217
|
+
def _ok(self) -> dict:
|
|
218
|
+
return {"status": "ok", "execution_count": self.execution_count, "payload": [], "user_expressions": {}}
|
|
219
|
+
|
|
220
|
+
def _error(self, rc: int, evalue: str, extra: list[str], silent: bool, ename: str | None = None,
|
|
221
|
+
already_streamed: bool = False) -> dict:
|
|
222
|
+
ename = ename or f"r({rc})"
|
|
223
|
+
tb = [f"{_RED}{line}{_RESET}" for line in extra]
|
|
224
|
+
if rc >= 0:
|
|
225
|
+
tb.append(f"{_RED}r({rc});{_RESET}")
|
|
226
|
+
content = {"ename": ename, "evalue": evalue, "traceback": tb}
|
|
227
|
+
if not silent:
|
|
228
|
+
self.send_response(self.iopub_socket, "error", content)
|
|
229
|
+
return {"status": "error", "execution_count": self.execution_count, **content}
|
|
230
|
+
|
|
231
|
+
# ----- completion and inspection -----
|
|
232
|
+
|
|
233
|
+
def do_complete(self, code, cursor_pos):
|
|
234
|
+
cursor_pos = len(code) if cursor_pos is None else cursor_pos
|
|
235
|
+
start, _ = _token_bounds(code, cursor_pos)
|
|
236
|
+
prefix = code[start:cursor_pos]
|
|
237
|
+
if not self._vars:
|
|
238
|
+
self._refresh_vars()
|
|
239
|
+
varnames = [v["name"] for v in self._vars]
|
|
240
|
+
types: list[dict] = []
|
|
241
|
+
if is_command_position(code, start):
|
|
242
|
+
pool = [(c, "keyword") for c in COMMANDS]
|
|
243
|
+
else:
|
|
244
|
+
pool = [(v, "variable") for v in varnames] + [(f, "function") for f in FUNCTIONS]
|
|
245
|
+
matches: list[str] = []
|
|
246
|
+
seen = set()
|
|
247
|
+
for name, kind in pool:
|
|
248
|
+
if name.startswith(prefix) and name not in seen:
|
|
249
|
+
seen.add(name)
|
|
250
|
+
matches.append(name)
|
|
251
|
+
types.append({"start": start, "end": cursor_pos, "text": name, "type": kind})
|
|
252
|
+
return {
|
|
253
|
+
"status": "ok",
|
|
254
|
+
"matches": matches,
|
|
255
|
+
"cursor_start": start,
|
|
256
|
+
"cursor_end": cursor_pos,
|
|
257
|
+
"metadata": {"_jupyter_types_experimental": types},
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
def do_inspect(self, code, cursor_pos, detail_level=0, omit_sections=()):
|
|
261
|
+
cursor_pos = len(code) if cursor_pos is None else cursor_pos
|
|
262
|
+
start, end = _token_bounds(code, cursor_pos)
|
|
263
|
+
word = code[start:end]
|
|
264
|
+
if not word:
|
|
265
|
+
return {"status": "ok", "found": False, "data": {}, "metadata": {}}
|
|
266
|
+
if not self._vars:
|
|
267
|
+
self._refresh_vars()
|
|
268
|
+
var = next((v for v in self._vars if v["name"] == word), None)
|
|
269
|
+
if var is not None:
|
|
270
|
+
label = var.get("label") or "(no label)"
|
|
271
|
+
plain = f"{var['name']} {var.get('type', '')} {var.get('format', '')}\n{label}"
|
|
272
|
+
md = f"**{var['name']}** · `{var.get('type', '')}` · `{var.get('format', '')}`\n\n{label}"
|
|
273
|
+
return {"status": "ok", "found": True, "data": {"text/plain": plain, "text/markdown": md}, "metadata": {}}
|
|
274
|
+
cmd = _ABBREV.get(word, word)
|
|
275
|
+
if cmd in DESCRIBE or word in COMMANDS:
|
|
276
|
+
desc = DESCRIBE.get(cmd, "Stata command")
|
|
277
|
+
name = cmd if cmd == word else f"{word} ({cmd})"
|
|
278
|
+
return {
|
|
279
|
+
"status": "ok",
|
|
280
|
+
"found": True,
|
|
281
|
+
"data": {"text/plain": f"{name}: {desc}", "text/markdown": f"**{name}**: {desc}"},
|
|
282
|
+
"metadata": {},
|
|
283
|
+
}
|
|
284
|
+
if word in FUNCTIONS:
|
|
285
|
+
return {"status": "ok", "found": True, "data": {"text/plain": f"{word}(): Stata function"}, "metadata": {}}
|
|
286
|
+
return {"status": "ok", "found": False, "data": {}, "metadata": {}}
|
|
287
|
+
|
|
288
|
+
def do_is_complete(self, code):
|
|
289
|
+
status = is_complete(code)
|
|
290
|
+
if status == "incomplete":
|
|
291
|
+
return {"status": "incomplete", "indent": " "}
|
|
292
|
+
return {"status": "complete"}
|
|
293
|
+
|
|
294
|
+
def do_shutdown(self, restart):
|
|
295
|
+
if self._session is not None:
|
|
296
|
+
self._session.stop()
|
|
297
|
+
self._session = None
|
|
298
|
+
self._vars = []
|
|
299
|
+
if not restart:
|
|
300
|
+
shutil.rmtree(self._graph_dir, ignore_errors=True)
|
|
301
|
+
return {"status": "ok", "restart": restart}
|
|
Binary file
|
|
Binary file
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
|
|
2
|
+
<rect width="128" height="128" rx="16" fill="#1b1f2a"/>
|
|
3
|
+
<text x="24" y="95" font-family="Georgia, 'Noto Serif', 'DejaVu Serif', serif" font-size="86" font-weight="700" fill="#f5f1e8">R</text>
|
|
4
|
+
<circle cx="99" cy="88" r="10" fill="#b4232c"/>
|
|
5
|
+
</svg>
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
"""A client for ``regwright serve``: one persistent engine session over JSON lines."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import subprocess
|
|
10
|
+
import threading
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class ServeError(RuntimeError):
|
|
16
|
+
"""The engine could not be started or stopped answering."""
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def find_binary() -> str:
|
|
20
|
+
"""The regwright CLI: $REGWRIGHT_PATH, else `regwright` on PATH."""
|
|
21
|
+
explicit = os.environ.get("REGWRIGHT_PATH") or os.environ.get("REGWRIGHT_BIN")
|
|
22
|
+
if explicit:
|
|
23
|
+
return explicit
|
|
24
|
+
found = shutil.which("regwright")
|
|
25
|
+
if found:
|
|
26
|
+
return found
|
|
27
|
+
raise ServeError(
|
|
28
|
+
"The regwright command-line tool was not found. Install it from https://regwright.com "
|
|
29
|
+
"or set REGWRIGHT_PATH to the binary."
|
|
30
|
+
)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ServeSession:
|
|
34
|
+
"""Owns one ``regwright serve`` child process."""
|
|
35
|
+
|
|
36
|
+
def __init__(self, binary: str | None = None, graph_dir: str | None = None, cwd: str | None = None,
|
|
37
|
+
env: dict[str, str] | None = None):
|
|
38
|
+
self.binary = binary
|
|
39
|
+
self.graph_dir = graph_dir
|
|
40
|
+
self.cwd = cwd
|
|
41
|
+
self.extra_env = env or {}
|
|
42
|
+
self.proc: subprocess.Popen[str] | None = None
|
|
43
|
+
self._next_id = 1
|
|
44
|
+
self._stderr: list[str] = []
|
|
45
|
+
self._lock = threading.Lock()
|
|
46
|
+
|
|
47
|
+
@property
|
|
48
|
+
def running(self) -> bool:
|
|
49
|
+
return self.proc is not None and self.proc.poll() is None
|
|
50
|
+
|
|
51
|
+
def start(self) -> None:
|
|
52
|
+
if self.running:
|
|
53
|
+
return
|
|
54
|
+
binary = self.binary or find_binary()
|
|
55
|
+
env = dict(os.environ)
|
|
56
|
+
env.update(self.extra_env)
|
|
57
|
+
if self.graph_dir:
|
|
58
|
+
env["REGWRIGHT_GRAPH_DIR"] = self.graph_dir
|
|
59
|
+
try:
|
|
60
|
+
self.proc = subprocess.Popen(
|
|
61
|
+
[binary, "serve"],
|
|
62
|
+
stdin=subprocess.PIPE,
|
|
63
|
+
stdout=subprocess.PIPE,
|
|
64
|
+
stderr=subprocess.PIPE,
|
|
65
|
+
cwd=self.cwd,
|
|
66
|
+
env=env,
|
|
67
|
+
text=True,
|
|
68
|
+
encoding="utf-8",
|
|
69
|
+
bufsize=1,
|
|
70
|
+
)
|
|
71
|
+
except FileNotFoundError as e:
|
|
72
|
+
raise ServeError(f"cannot start {binary!r}: not found. Install regwright or set REGWRIGHT_PATH.") from e
|
|
73
|
+
except OSError as e:
|
|
74
|
+
raise ServeError(f"cannot start {binary!r}: {e}") from e
|
|
75
|
+
t = threading.Thread(target=self._drain_stderr, args=(self.proc,), daemon=True)
|
|
76
|
+
t.start()
|
|
77
|
+
|
|
78
|
+
def _drain_stderr(self, proc: subprocess.Popen[str]) -> None:
|
|
79
|
+
assert proc.stderr is not None
|
|
80
|
+
for line in proc.stderr:
|
|
81
|
+
with self._lock:
|
|
82
|
+
self._stderr.append(line)
|
|
83
|
+
|
|
84
|
+
def take_stderr(self) -> str:
|
|
85
|
+
"""Engine notes printed on stderr since the last call (e.g. licence messages)."""
|
|
86
|
+
with self._lock:
|
|
87
|
+
s = "".join(self._stderr)
|
|
88
|
+
self._stderr.clear()
|
|
89
|
+
return s
|
|
90
|
+
|
|
91
|
+
def request(self, req: dict) -> dict:
|
|
92
|
+
self.start()
|
|
93
|
+
assert self.proc is not None and self.proc.stdin is not None and self.proc.stdout is not None
|
|
94
|
+
rid = self._next_id
|
|
95
|
+
self._next_id += 1
|
|
96
|
+
msg = dict(req)
|
|
97
|
+
msg["id"] = rid
|
|
98
|
+
try:
|
|
99
|
+
self.proc.stdin.write(json.dumps(msg) + "\n")
|
|
100
|
+
self.proc.stdin.flush()
|
|
101
|
+
except (BrokenPipeError, OSError) as e:
|
|
102
|
+
self.kill()
|
|
103
|
+
raise ServeError(f"regwright stopped: {e}") from e
|
|
104
|
+
while True:
|
|
105
|
+
line = self.proc.stdout.readline()
|
|
106
|
+
if not line:
|
|
107
|
+
code = self.proc.poll()
|
|
108
|
+
self.kill()
|
|
109
|
+
raise ServeError(f"regwright exited unexpectedly (code {code}). {self.take_stderr().strip()}".strip())
|
|
110
|
+
line = line.strip()
|
|
111
|
+
if not line:
|
|
112
|
+
continue
|
|
113
|
+
try:
|
|
114
|
+
reply = json.loads(line)
|
|
115
|
+
except json.JSONDecodeError:
|
|
116
|
+
continue
|
|
117
|
+
if reply.get("id") == rid:
|
|
118
|
+
return reply
|
|
119
|
+
if "error" in reply and reply.get("id") is None:
|
|
120
|
+
raise ServeError(str(reply["error"]))
|
|
121
|
+
|
|
122
|
+
def run(self, code: str) -> dict:
|
|
123
|
+
return self.request({"code": code})
|
|
124
|
+
|
|
125
|
+
def describe(self) -> dict:
|
|
126
|
+
return self.request({"cmd": "describe"})
|
|
127
|
+
|
|
128
|
+
def chdir(self, path: str) -> bool:
|
|
129
|
+
return self.request({"cmd": "cwd", "path": path}).get("rc") == 0
|
|
130
|
+
|
|
131
|
+
def kill(self) -> None:
|
|
132
|
+
if self.proc is not None:
|
|
133
|
+
try:
|
|
134
|
+
self.proc.kill()
|
|
135
|
+
self.proc.wait(timeout=5)
|
|
136
|
+
except Exception:
|
|
137
|
+
pass
|
|
138
|
+
self.proc = None
|
|
139
|
+
|
|
140
|
+
def stop(self, timeout: float = 3.0) -> None:
|
|
141
|
+
proc = self.proc
|
|
142
|
+
if proc is None:
|
|
143
|
+
return
|
|
144
|
+
if proc.poll() is None:
|
|
145
|
+
try:
|
|
146
|
+
assert proc.stdin is not None
|
|
147
|
+
proc.stdin.write(json.dumps({"cmd": "shutdown"}) + "\n")
|
|
148
|
+
proc.stdin.flush()
|
|
149
|
+
proc.stdin.close()
|
|
150
|
+
proc.wait(timeout=timeout)
|
|
151
|
+
except Exception:
|
|
152
|
+
pass
|
|
153
|
+
self.kill()
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
@dataclass
|
|
157
|
+
class GraphWatcher:
|
|
158
|
+
"""Finds SVGs the engine wrote to REGWRIGHT_GRAPH_DIR since the last snapshot.
|
|
159
|
+
|
|
160
|
+
Graphs are written as <name>.svg; the default name "Graph" is overwritten by every new graph,
|
|
161
|
+
so changes are detected by content hash.
|
|
162
|
+
"""
|
|
163
|
+
|
|
164
|
+
directory: Path
|
|
165
|
+
seen: dict[str, str] = field(default_factory=dict)
|
|
166
|
+
|
|
167
|
+
def __post_init__(self) -> None:
|
|
168
|
+
self.directory.mkdir(parents=True, exist_ok=True)
|
|
169
|
+
self.snapshot()
|
|
170
|
+
|
|
171
|
+
def _files(self) -> list[Path]:
|
|
172
|
+
try:
|
|
173
|
+
return [p for p in self.directory.iterdir() if p.suffix.lower() == ".svg"]
|
|
174
|
+
except OSError:
|
|
175
|
+
return []
|
|
176
|
+
|
|
177
|
+
def snapshot(self) -> None:
|
|
178
|
+
self.seen = {}
|
|
179
|
+
for p in self._files():
|
|
180
|
+
try:
|
|
181
|
+
self.seen[p.name] = hashlib.sha1(p.read_bytes()).hexdigest()
|
|
182
|
+
except OSError:
|
|
183
|
+
pass
|
|
184
|
+
|
|
185
|
+
def changed(self) -> list[tuple[str, str]]:
|
|
186
|
+
"""[(name, svg text)] written since the last snapshot, oldest first."""
|
|
187
|
+
out = []
|
|
188
|
+
for p in self._files():
|
|
189
|
+
try:
|
|
190
|
+
data = p.read_bytes()
|
|
191
|
+
mtime = p.stat().st_mtime
|
|
192
|
+
except OSError:
|
|
193
|
+
continue
|
|
194
|
+
h = hashlib.sha1(data).hexdigest()
|
|
195
|
+
if self.seen.get(p.name) != h:
|
|
196
|
+
self.seen[p.name] = h
|
|
197
|
+
out.append((mtime, p.stem, data.decode("utf-8", "replace")))
|
|
198
|
+
out.sort()
|
|
199
|
+
return [(name, svg) for _, name, svg in out]
|