tmcode 0.2.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.
- termcode/__init__.py +3 -0
- termcode/app.py +2236 -0
- termcode/buffers.py +168 -0
- termcode/cli.py +69 -0
- termcode/commands.py +234 -0
- termcode/completions.py +205 -0
- termcode/findbar.py +258 -0
- termcode/formatting.py +365 -0
- termcode/highlighting.py +61 -0
- termcode/modals.py +431 -0
- termcode/runner.py +725 -0
- termcode/search.py +105 -0
- termcode/styles.tcss +796 -0
- termcode/theme.py +99 -0
- termcode/workspace.py +271 -0
- tmcode-0.2.0.dist-info/METADATA +128 -0
- tmcode-0.2.0.dist-info/RECORD +21 -0
- tmcode-0.2.0.dist-info/WHEEL +5 -0
- tmcode-0.2.0.dist-info/entry_points.txt +3 -0
- tmcode-0.2.0.dist-info/licenses/LICENSE +21 -0
- tmcode-0.2.0.dist-info/top_level.txt +1 -0
termcode/runner.py
ADDED
|
@@ -0,0 +1,725 @@
|
|
|
1
|
+
"""Cross-OS language detection, compilation, and interactive execution engine."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import codecs
|
|
7
|
+
from collections.abc import Callable, Mapping
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from enum import Enum
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import shutil
|
|
13
|
+
import signal
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
import time
|
|
18
|
+
|
|
19
|
+
try:
|
|
20
|
+
import pty
|
|
21
|
+
import termios
|
|
22
|
+
except ImportError: # Windows
|
|
23
|
+
pty = None # type: ignore[assignment]
|
|
24
|
+
termios = None # type: ignore[assignment]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Language(str, Enum):
|
|
28
|
+
PYTHON = "python"
|
|
29
|
+
C = "c"
|
|
30
|
+
CPP = "cpp"
|
|
31
|
+
JAVASCRIPT = "javascript"
|
|
32
|
+
TYPESCRIPT = "typescript"
|
|
33
|
+
BASH = "bash"
|
|
34
|
+
GO = "go"
|
|
35
|
+
RUST = "rust"
|
|
36
|
+
JAVA = "java"
|
|
37
|
+
RUBY = "ruby"
|
|
38
|
+
PHP = "php"
|
|
39
|
+
PERL = "perl"
|
|
40
|
+
LUA = "lua"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class RunPlan:
|
|
45
|
+
language: Language
|
|
46
|
+
source: Path
|
|
47
|
+
compile_cmd: list[str] | None
|
|
48
|
+
run_cmd: list[str]
|
|
49
|
+
cwd: Path
|
|
50
|
+
display_cmd: str
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@dataclass(frozen=True)
|
|
54
|
+
class RunResult:
|
|
55
|
+
exit_code: int
|
|
56
|
+
duration_seconds: float
|
|
57
|
+
cancelled: bool
|
|
58
|
+
compile_failed: bool
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class RunnerError(Exception):
|
|
62
|
+
"""Raised when a file cannot be compiled or executed."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
_RUNNABLE_EXTENSIONS: dict[str, Language] = {
|
|
66
|
+
".py": Language.PYTHON,
|
|
67
|
+
".c": Language.C,
|
|
68
|
+
".cpp": Language.CPP,
|
|
69
|
+
".cc": Language.CPP,
|
|
70
|
+
".cxx": Language.CPP,
|
|
71
|
+
".js": Language.JAVASCRIPT,
|
|
72
|
+
".mjs": Language.JAVASCRIPT,
|
|
73
|
+
".cjs": Language.JAVASCRIPT,
|
|
74
|
+
".ts": Language.TYPESCRIPT,
|
|
75
|
+
".sh": Language.BASH,
|
|
76
|
+
".bash": Language.BASH,
|
|
77
|
+
".go": Language.GO,
|
|
78
|
+
".rs": Language.RUST,
|
|
79
|
+
".java": Language.JAVA,
|
|
80
|
+
".rb": Language.RUBY,
|
|
81
|
+
".php": Language.PHP,
|
|
82
|
+
".pl": Language.PERL,
|
|
83
|
+
".lua": Language.LUA,
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
_EDITOR_LANGUAGES: dict[str, str] = {
|
|
87
|
+
".py": "python",
|
|
88
|
+
".c": "c",
|
|
89
|
+
".h": "c",
|
|
90
|
+
".cpp": "cpp",
|
|
91
|
+
".cc": "cpp",
|
|
92
|
+
".cxx": "cpp",
|
|
93
|
+
".hpp": "cpp",
|
|
94
|
+
".hh": "cpp",
|
|
95
|
+
".js": "javascript",
|
|
96
|
+
".jsx": "javascript",
|
|
97
|
+
".mjs": "javascript",
|
|
98
|
+
".cjs": "javascript",
|
|
99
|
+
".ts": "javascript",
|
|
100
|
+
".tsx": "javascript",
|
|
101
|
+
".html": "html",
|
|
102
|
+
".htm": "html",
|
|
103
|
+
".css": "css",
|
|
104
|
+
".json": "json",
|
|
105
|
+
".java": "java",
|
|
106
|
+
".go": "go",
|
|
107
|
+
".rs": "rust",
|
|
108
|
+
".sh": "bash",
|
|
109
|
+
".bash": "bash",
|
|
110
|
+
".zsh": "bash",
|
|
111
|
+
".sql": "sql",
|
|
112
|
+
".md": "markdown",
|
|
113
|
+
".markdown": "markdown",
|
|
114
|
+
".toml": "toml",
|
|
115
|
+
".yaml": "yaml",
|
|
116
|
+
".yml": "yaml",
|
|
117
|
+
".xml": "xml",
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
_LANGUAGE_LABELS: dict[str, str] = {
|
|
121
|
+
".py": "Python",
|
|
122
|
+
".c": "C",
|
|
123
|
+
".h": "C",
|
|
124
|
+
".cpp": "C++",
|
|
125
|
+
".cc": "C++",
|
|
126
|
+
".cxx": "C++",
|
|
127
|
+
".hpp": "C++",
|
|
128
|
+
".hh": "C++",
|
|
129
|
+
".js": "JavaScript",
|
|
130
|
+
".jsx": "JavaScript",
|
|
131
|
+
".mjs": "JavaScript",
|
|
132
|
+
".cjs": "JavaScript",
|
|
133
|
+
".ts": "TypeScript",
|
|
134
|
+
".tsx": "TypeScript",
|
|
135
|
+
".html": "HTML",
|
|
136
|
+
".htm": "HTML",
|
|
137
|
+
".css": "CSS",
|
|
138
|
+
".json": "JSON",
|
|
139
|
+
".java": "Java",
|
|
140
|
+
".go": "Go",
|
|
141
|
+
".rs": "Rust",
|
|
142
|
+
".sh": "Bash",
|
|
143
|
+
".bash": "Bash",
|
|
144
|
+
".zsh": "Shell",
|
|
145
|
+
".sql": "SQL",
|
|
146
|
+
".md": "Markdown",
|
|
147
|
+
".toml": "TOML",
|
|
148
|
+
".yaml": "YAML",
|
|
149
|
+
".yml": "YAML",
|
|
150
|
+
".xml": "XML",
|
|
151
|
+
".rb": "Ruby",
|
|
152
|
+
".php": "PHP",
|
|
153
|
+
".pl": "Perl",
|
|
154
|
+
".lua": "Lua",
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def detect_language(path: Path) -> Language | None:
|
|
159
|
+
"""Return the runnable Language for path, or None if unsupported."""
|
|
160
|
+
return _RUNNABLE_EXTENSIONS.get(path.suffix.lower())
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def editor_language_for_path(path: Path | None) -> str | None:
|
|
164
|
+
"""Return the syntax-highlighting language identifier for path."""
|
|
165
|
+
if path is None:
|
|
166
|
+
return None
|
|
167
|
+
return _EDITOR_LANGUAGES.get(path.suffix.lower())
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def language_label_for_path(path: Path | None) -> str:
|
|
171
|
+
"""Return a short human-readable language badge for the status bar."""
|
|
172
|
+
if path is None:
|
|
173
|
+
return "Untitled"
|
|
174
|
+
return _LANGUAGE_LABELS.get(path.suffix.lower(), "Text")
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _venv_python(venv_dir: Path, platform: str) -> Path:
|
|
178
|
+
if platform == "win32":
|
|
179
|
+
return venv_dir / "Scripts" / "python.exe"
|
|
180
|
+
return venv_dir / "bin" / "python"
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _same_dir(a: Path, b: Path) -> bool:
|
|
184
|
+
try:
|
|
185
|
+
return a.resolve() == b.resolve()
|
|
186
|
+
except OSError:
|
|
187
|
+
return str(a) == str(b)
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def resolve_python_executable(
|
|
191
|
+
workspace_root: Path,
|
|
192
|
+
*,
|
|
193
|
+
platform: str | None = None,
|
|
194
|
+
env: Mapping[str, str] | None = None,
|
|
195
|
+
own_venv: Path | None = None,
|
|
196
|
+
which: Callable[[str], str | None] = shutil.which,
|
|
197
|
+
) -> str | None:
|
|
198
|
+
"""Resolve the best Python interpreter for running user code across OSes."""
|
|
199
|
+
plat = platform or sys.platform
|
|
200
|
+
environment = env if env is not None else os.environ
|
|
201
|
+
internal_venv = own_venv if own_venv is not None else Path(sys.prefix)
|
|
202
|
+
|
|
203
|
+
# 1. Workspace-local .venv or venv
|
|
204
|
+
for name in (".venv", "venv"):
|
|
205
|
+
candidate = _venv_python(workspace_root / name, plat)
|
|
206
|
+
if candidate.is_file():
|
|
207
|
+
return str(candidate)
|
|
208
|
+
|
|
209
|
+
# 2. Active VIRTUAL_ENV (ignoring TermCode's own internal venv)
|
|
210
|
+
active_venv = environment.get("VIRTUAL_ENV")
|
|
211
|
+
if active_venv:
|
|
212
|
+
venv_path = Path(active_venv)
|
|
213
|
+
if not _same_dir(venv_path, internal_venv):
|
|
214
|
+
candidate = _venv_python(venv_path, plat)
|
|
215
|
+
if candidate.is_file():
|
|
216
|
+
return str(candidate)
|
|
217
|
+
|
|
218
|
+
# 3. System Python on PATH
|
|
219
|
+
candidates = ("python", "python3") if plat == "win32" else ("python3", "python")
|
|
220
|
+
for exe in candidates:
|
|
221
|
+
found = which(exe)
|
|
222
|
+
if found:
|
|
223
|
+
return found
|
|
224
|
+
|
|
225
|
+
return None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def build_run_plan(
|
|
229
|
+
source: Path,
|
|
230
|
+
workspace_root: Path,
|
|
231
|
+
temp_dir: Path,
|
|
232
|
+
*,
|
|
233
|
+
platform: str | None = None,
|
|
234
|
+
env: Mapping[str, str] | None = None,
|
|
235
|
+
which: Callable[[str], str | None] = shutil.which,
|
|
236
|
+
) -> RunPlan:
|
|
237
|
+
"""Build compile and execute commands for a Python, C, or C++ file."""
|
|
238
|
+
plat = platform or sys.platform
|
|
239
|
+
lang = detect_language(source)
|
|
240
|
+
if lang is None:
|
|
241
|
+
ext = source.suffix or "(no extension)"
|
|
242
|
+
supported = ", ".join(sorted(_RUNNABLE_EXTENSIONS))
|
|
243
|
+
raise RunnerError(
|
|
244
|
+
f"Unsupported file type for running: {ext}. Supported: {supported}"
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
cwd = source.parent
|
|
248
|
+
if lang is Language.PYTHON:
|
|
249
|
+
python_exe = resolve_python_executable(
|
|
250
|
+
workspace_root, platform=plat, env=env, which=which
|
|
251
|
+
)
|
|
252
|
+
if not python_exe:
|
|
253
|
+
raise RunnerError("Could not find a Python interpreter (python3/python) on PATH.")
|
|
254
|
+
return RunPlan(
|
|
255
|
+
language=lang,
|
|
256
|
+
source=source,
|
|
257
|
+
compile_cmd=None,
|
|
258
|
+
run_cmd=[python_exe, str(source)],
|
|
259
|
+
cwd=cwd,
|
|
260
|
+
display_cmd=f"{Path(python_exe).name} {source.name}",
|
|
261
|
+
)
|
|
262
|
+
|
|
263
|
+
binary_name = "a.exe" if plat == "win32" else "a.out"
|
|
264
|
+
output_bin = temp_dir / binary_name
|
|
265
|
+
|
|
266
|
+
if lang is Language.C:
|
|
267
|
+
compiler = which("gcc")
|
|
268
|
+
if not compiler:
|
|
269
|
+
raise RunnerError(
|
|
270
|
+
"Could not find 'gcc' compiler on PATH. Install GCC (or MinGW on Windows)."
|
|
271
|
+
)
|
|
272
|
+
return RunPlan(
|
|
273
|
+
language=lang,
|
|
274
|
+
source=source,
|
|
275
|
+
compile_cmd=[compiler, "-Wall", "-Wextra", str(source), "-o", str(output_bin)],
|
|
276
|
+
run_cmd=[str(output_bin)],
|
|
277
|
+
cwd=cwd,
|
|
278
|
+
display_cmd=f"gcc -Wall -Wextra {source.name} && ./{binary_name}",
|
|
279
|
+
)
|
|
280
|
+
|
|
281
|
+
if lang is Language.CPP:
|
|
282
|
+
compiler = which("g++")
|
|
283
|
+
if not compiler:
|
|
284
|
+
raise RunnerError(
|
|
285
|
+
"Could not find 'g++' compiler on PATH. Install G++ (or MinGW on Windows)."
|
|
286
|
+
)
|
|
287
|
+
return RunPlan(
|
|
288
|
+
language=lang,
|
|
289
|
+
source=source,
|
|
290
|
+
compile_cmd=[
|
|
291
|
+
compiler,
|
|
292
|
+
"-std=c++17",
|
|
293
|
+
"-Wall",
|
|
294
|
+
"-Wextra",
|
|
295
|
+
str(source),
|
|
296
|
+
"-o",
|
|
297
|
+
str(output_bin),
|
|
298
|
+
],
|
|
299
|
+
run_cmd=[str(output_bin)],
|
|
300
|
+
cwd=cwd,
|
|
301
|
+
display_cmd=f"g++ -std=c++17 -Wall -Wextra {source.name} && ./{binary_name}",
|
|
302
|
+
)
|
|
303
|
+
|
|
304
|
+
if lang is Language.RUST:
|
|
305
|
+
compiler = which("rustc")
|
|
306
|
+
if not compiler:
|
|
307
|
+
raise RunnerError("Could not find 'rustc' compiler on PATH. Install Rust (rustup).")
|
|
308
|
+
return RunPlan(
|
|
309
|
+
language=lang,
|
|
310
|
+
source=source,
|
|
311
|
+
compile_cmd=[compiler, str(source), "-o", str(output_bin)],
|
|
312
|
+
run_cmd=[str(output_bin)],
|
|
313
|
+
cwd=cwd,
|
|
314
|
+
display_cmd=f"rustc {source.name} && ./{binary_name}",
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
if lang is Language.GO:
|
|
318
|
+
go_exe = which("go")
|
|
319
|
+
if not go_exe:
|
|
320
|
+
raise RunnerError("Could not find 'go' on PATH. Install Go to run .go files.")
|
|
321
|
+
return RunPlan(
|
|
322
|
+
language=lang,
|
|
323
|
+
source=source,
|
|
324
|
+
compile_cmd=None,
|
|
325
|
+
run_cmd=[go_exe, "run", str(source)],
|
|
326
|
+
cwd=cwd,
|
|
327
|
+
display_cmd=f"go run {source.name}",
|
|
328
|
+
)
|
|
329
|
+
|
|
330
|
+
if lang is Language.TYPESCRIPT:
|
|
331
|
+
for tool in ("tsx", "ts-node", "node"):
|
|
332
|
+
exe = which(tool)
|
|
333
|
+
if exe:
|
|
334
|
+
return RunPlan(
|
|
335
|
+
language=lang,
|
|
336
|
+
source=source,
|
|
337
|
+
compile_cmd=None,
|
|
338
|
+
run_cmd=[exe, str(source)],
|
|
339
|
+
cwd=cwd,
|
|
340
|
+
display_cmd=f"{tool} {source.name}",
|
|
341
|
+
)
|
|
342
|
+
raise RunnerError("Could not find 'tsx', 'ts-node', or 'node' on PATH for TypeScript.")
|
|
343
|
+
|
|
344
|
+
if lang is Language.BASH:
|
|
345
|
+
for tool in ("bash", "sh"):
|
|
346
|
+
exe = which(tool)
|
|
347
|
+
if exe:
|
|
348
|
+
return RunPlan(
|
|
349
|
+
language=lang,
|
|
350
|
+
source=source,
|
|
351
|
+
compile_cmd=None,
|
|
352
|
+
run_cmd=[exe, str(source)],
|
|
353
|
+
cwd=cwd,
|
|
354
|
+
display_cmd=f"{tool} {source.name}",
|
|
355
|
+
)
|
|
356
|
+
raise RunnerError("Could not find 'bash' or 'sh' on PATH.")
|
|
357
|
+
|
|
358
|
+
simple_interpreters: dict[Language, tuple[str, str]] = {
|
|
359
|
+
Language.JAVASCRIPT: ("node", "Node.js"),
|
|
360
|
+
Language.JAVA: ("java", "Java (JDK 11+)"),
|
|
361
|
+
Language.RUBY: ("ruby", "Ruby"),
|
|
362
|
+
Language.PHP: ("php", "PHP"),
|
|
363
|
+
Language.PERL: ("perl", "Perl"),
|
|
364
|
+
Language.LUA: ("lua", "Lua"),
|
|
365
|
+
}
|
|
366
|
+
exe_name, friendly = simple_interpreters[lang]
|
|
367
|
+
exe = which(exe_name)
|
|
368
|
+
if not exe:
|
|
369
|
+
raise RunnerError(f"Could not find '{exe_name}' on PATH. Install {friendly} to run {source.suffix} files.")
|
|
370
|
+
return RunPlan(
|
|
371
|
+
language=lang,
|
|
372
|
+
source=source,
|
|
373
|
+
compile_cmd=None,
|
|
374
|
+
run_cmd=[exe, str(source)],
|
|
375
|
+
cwd=cwd,
|
|
376
|
+
display_cmd=f"{exe_name} {source.name}",
|
|
377
|
+
)
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
class AsyncRunner:
|
|
381
|
+
"""Manages asynchronous compilation and interactive execution of a single program."""
|
|
382
|
+
|
|
383
|
+
def __init__(self) -> None:
|
|
384
|
+
self._proc: asyncio.subprocess.Process | None = None
|
|
385
|
+
self._master_fd: int | None = None
|
|
386
|
+
self._cancelled: bool = False
|
|
387
|
+
self._running: bool = False
|
|
388
|
+
|
|
389
|
+
@property
|
|
390
|
+
def is_running(self) -> bool:
|
|
391
|
+
return self._running
|
|
392
|
+
|
|
393
|
+
async def run(
|
|
394
|
+
self,
|
|
395
|
+
source: Path,
|
|
396
|
+
workspace_root: Path,
|
|
397
|
+
on_output: Callable[[str], None],
|
|
398
|
+
) -> RunResult:
|
|
399
|
+
"""Compile (if needed) and execute source, streaming output to on_output."""
|
|
400
|
+
if self._running:
|
|
401
|
+
raise RunnerError("A program is already running. Stop it first (F7 / /stop).")
|
|
402
|
+
|
|
403
|
+
self._running = True
|
|
404
|
+
self._cancelled = False
|
|
405
|
+
start = time.monotonic()
|
|
406
|
+
|
|
407
|
+
try:
|
|
408
|
+
with tempfile.TemporaryDirectory(prefix="termcode_") as tmp:
|
|
409
|
+
plan = build_run_plan(source, workspace_root, Path(tmp))
|
|
410
|
+
|
|
411
|
+
# Step 1: Compile (C / C++)
|
|
412
|
+
if plan.compile_cmd is not None:
|
|
413
|
+
compile_rc = await self._run_compile(plan.compile_cmd, plan.cwd, on_output)
|
|
414
|
+
if self._cancelled:
|
|
415
|
+
return RunResult(
|
|
416
|
+
exit_code=compile_rc,
|
|
417
|
+
duration_seconds=time.monotonic() - start,
|
|
418
|
+
cancelled=True,
|
|
419
|
+
compile_failed=False,
|
|
420
|
+
)
|
|
421
|
+
if compile_rc != 0:
|
|
422
|
+
return RunResult(
|
|
423
|
+
exit_code=compile_rc,
|
|
424
|
+
duration_seconds=time.monotonic() - start,
|
|
425
|
+
cancelled=False,
|
|
426
|
+
compile_failed=True,
|
|
427
|
+
)
|
|
428
|
+
|
|
429
|
+
# Step 2: Execute program (POSIX PTY or Windows pipes)
|
|
430
|
+
run_env = os.environ.copy()
|
|
431
|
+
run_env["PYTHONUNBUFFERED"] = "1"
|
|
432
|
+
if sys.platform != "win32" and pty is not None and termios is not None:
|
|
433
|
+
rc = await self._run_posix_pty(plan.run_cmd, plan.cwd, run_env, on_output)
|
|
434
|
+
else:
|
|
435
|
+
rc = await self._run_pipes(plan.run_cmd, plan.cwd, run_env, on_output)
|
|
436
|
+
|
|
437
|
+
return RunResult(
|
|
438
|
+
exit_code=rc,
|
|
439
|
+
duration_seconds=time.monotonic() - start,
|
|
440
|
+
cancelled=self._cancelled,
|
|
441
|
+
compile_failed=False,
|
|
442
|
+
)
|
|
443
|
+
except asyncio.CancelledError:
|
|
444
|
+
self._cancelled = True
|
|
445
|
+
await self.stop()
|
|
446
|
+
raise
|
|
447
|
+
finally:
|
|
448
|
+
self._proc = None
|
|
449
|
+
self._master_fd = None
|
|
450
|
+
self._running = False
|
|
451
|
+
|
|
452
|
+
async def _run_compile(
|
|
453
|
+
self,
|
|
454
|
+
cmd: list[str],
|
|
455
|
+
cwd: Path,
|
|
456
|
+
on_output: Callable[[str], None],
|
|
457
|
+
) -> int:
|
|
458
|
+
kwargs: dict[str, object] = {
|
|
459
|
+
"cwd": str(cwd),
|
|
460
|
+
"stdout": asyncio.subprocess.PIPE,
|
|
461
|
+
"stderr": asyncio.subprocess.STDOUT,
|
|
462
|
+
}
|
|
463
|
+
if sys.platform == "win32":
|
|
464
|
+
kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
|
|
465
|
+
else:
|
|
466
|
+
kwargs["start_new_session"] = True
|
|
467
|
+
|
|
468
|
+
proc = await asyncio.create_subprocess_exec(*cmd, **kwargs) # type: ignore[arg-type]
|
|
469
|
+
self._proc = proc
|
|
470
|
+
stdout, _ = await proc.communicate()
|
|
471
|
+
if stdout:
|
|
472
|
+
text = stdout.decode("utf-8", errors="replace").replace("\r\n", "\n")
|
|
473
|
+
on_output(text)
|
|
474
|
+
self._proc = None
|
|
475
|
+
return proc.returncode if proc.returncode is not None else -1
|
|
476
|
+
|
|
477
|
+
async def _run_posix_pty(
|
|
478
|
+
self,
|
|
479
|
+
cmd: list[str],
|
|
480
|
+
cwd: Path,
|
|
481
|
+
env: dict[str, str],
|
|
482
|
+
on_output: Callable[[str], None],
|
|
483
|
+
) -> int:
|
|
484
|
+
assert pty is not None and termios is not None
|
|
485
|
+
master_fd, slave_fd = pty.openpty()
|
|
486
|
+
loop = asyncio.get_running_loop()
|
|
487
|
+
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
|
|
488
|
+
eof_event = asyncio.Event()
|
|
489
|
+
|
|
490
|
+
try:
|
|
491
|
+
# Disable local PTY echo so TermCode echoes user-submitted stdin once cleanly.
|
|
492
|
+
attrs = termios.tcgetattr(slave_fd)
|
|
493
|
+
attrs[3] &= ~termios.ECHO
|
|
494
|
+
termios.tcsetattr(slave_fd, termios.TCSANOW, attrs)
|
|
495
|
+
except OSError:
|
|
496
|
+
pass
|
|
497
|
+
|
|
498
|
+
os.set_blocking(master_fd, False)
|
|
499
|
+
self._master_fd = master_fd
|
|
500
|
+
|
|
501
|
+
try:
|
|
502
|
+
try:
|
|
503
|
+
proc = await asyncio.create_subprocess_exec(
|
|
504
|
+
*cmd,
|
|
505
|
+
cwd=str(cwd),
|
|
506
|
+
env=env,
|
|
507
|
+
stdin=slave_fd,
|
|
508
|
+
stdout=slave_fd,
|
|
509
|
+
stderr=slave_fd,
|
|
510
|
+
close_fds=True,
|
|
511
|
+
start_new_session=True,
|
|
512
|
+
)
|
|
513
|
+
finally:
|
|
514
|
+
os.close(slave_fd)
|
|
515
|
+
|
|
516
|
+
self._proc = proc
|
|
517
|
+
|
|
518
|
+
def _read_available() -> None:
|
|
519
|
+
while True:
|
|
520
|
+
try:
|
|
521
|
+
chunk = os.read(master_fd, 4096)
|
|
522
|
+
except BlockingIOError:
|
|
523
|
+
return
|
|
524
|
+
except OSError:
|
|
525
|
+
eof_event.set()
|
|
526
|
+
try:
|
|
527
|
+
loop.remove_reader(master_fd)
|
|
528
|
+
except Exception:
|
|
529
|
+
pass
|
|
530
|
+
return
|
|
531
|
+
if not chunk:
|
|
532
|
+
eof_event.set()
|
|
533
|
+
try:
|
|
534
|
+
loop.remove_reader(master_fd)
|
|
535
|
+
except Exception:
|
|
536
|
+
pass
|
|
537
|
+
return
|
|
538
|
+
decoded = decoder.decode(chunk).replace("\r\n", "\n")
|
|
539
|
+
if decoded:
|
|
540
|
+
on_output(decoded)
|
|
541
|
+
|
|
542
|
+
loop.add_reader(master_fd, _read_available)
|
|
543
|
+
rc = await proc.wait()
|
|
544
|
+
|
|
545
|
+
# Drain any trailing output written right before process exit.
|
|
546
|
+
try:
|
|
547
|
+
await asyncio.wait_for(eof_event.wait(), timeout=0.25)
|
|
548
|
+
except asyncio.TimeoutError:
|
|
549
|
+
_read_available()
|
|
550
|
+
|
|
551
|
+
tail = decoder.decode(b"", final=True).replace("\r\n", "\n")
|
|
552
|
+
if tail:
|
|
553
|
+
on_output(tail)
|
|
554
|
+
return rc
|
|
555
|
+
finally:
|
|
556
|
+
try:
|
|
557
|
+
loop.remove_reader(master_fd)
|
|
558
|
+
except Exception:
|
|
559
|
+
pass
|
|
560
|
+
self._master_fd = None
|
|
561
|
+
try:
|
|
562
|
+
os.close(master_fd)
|
|
563
|
+
except OSError:
|
|
564
|
+
pass
|
|
565
|
+
|
|
566
|
+
async def _run_pipes(
|
|
567
|
+
self,
|
|
568
|
+
cmd: list[str],
|
|
569
|
+
cwd: Path,
|
|
570
|
+
env: dict[str, str],
|
|
571
|
+
on_output: Callable[[str], None],
|
|
572
|
+
) -> int:
|
|
573
|
+
kwargs: dict[str, object] = {
|
|
574
|
+
"cwd": str(cwd),
|
|
575
|
+
"env": env,
|
|
576
|
+
"stdin": asyncio.subprocess.PIPE,
|
|
577
|
+
"stdout": asyncio.subprocess.PIPE,
|
|
578
|
+
"stderr": asyncio.subprocess.STDOUT,
|
|
579
|
+
}
|
|
580
|
+
if sys.platform == "win32":
|
|
581
|
+
kwargs["creationflags"] = getattr(subprocess, "CREATE_NEW_PROCESS_GROUP", 0)
|
|
582
|
+
else:
|
|
583
|
+
kwargs["start_new_session"] = True
|
|
584
|
+
|
|
585
|
+
proc = await asyncio.create_subprocess_exec(*cmd, **kwargs) # type: ignore[arg-type]
|
|
586
|
+
self._proc = proc
|
|
587
|
+
decoder = codecs.getincrementaldecoder("utf-8")(errors="replace")
|
|
588
|
+
|
|
589
|
+
assert proc.stdout is not None
|
|
590
|
+
while True:
|
|
591
|
+
chunk = await proc.stdout.read(4096)
|
|
592
|
+
if not chunk:
|
|
593
|
+
break
|
|
594
|
+
decoded = decoder.decode(chunk).replace("\r\n", "\n")
|
|
595
|
+
if decoded:
|
|
596
|
+
on_output(decoded)
|
|
597
|
+
|
|
598
|
+
tail = decoder.decode(b"", final=True).replace("\r\n", "\n")
|
|
599
|
+
if tail:
|
|
600
|
+
on_output(tail)
|
|
601
|
+
return await proc.wait()
|
|
602
|
+
|
|
603
|
+
async def send_input(self, line: str) -> None:
|
|
604
|
+
"""Send one line of input (with newline) to the running program's stdin."""
|
|
605
|
+
if not self._running:
|
|
606
|
+
return
|
|
607
|
+
payload = (line + "\n").encode("utf-8")
|
|
608
|
+
if self._master_fd is not None:
|
|
609
|
+
try:
|
|
610
|
+
os.write(self._master_fd, payload)
|
|
611
|
+
except OSError:
|
|
612
|
+
pass
|
|
613
|
+
return
|
|
614
|
+
if self._proc is not None and self._proc.stdin is not None:
|
|
615
|
+
try:
|
|
616
|
+
self._proc.stdin.write(payload)
|
|
617
|
+
await self._proc.stdin.drain()
|
|
618
|
+
except OSError:
|
|
619
|
+
pass
|
|
620
|
+
|
|
621
|
+
async def stop(self) -> None:
|
|
622
|
+
"""Terminate the currently running process cleanly across OSes."""
|
|
623
|
+
if not self._running:
|
|
624
|
+
return
|
|
625
|
+
self._cancelled = True
|
|
626
|
+
proc = self._proc
|
|
627
|
+
if proc is None or proc.returncode is not None:
|
|
628
|
+
return
|
|
629
|
+
|
|
630
|
+
if sys.platform == "win32":
|
|
631
|
+
try:
|
|
632
|
+
proc.terminate()
|
|
633
|
+
except ProcessLookupError:
|
|
634
|
+
return
|
|
635
|
+
try:
|
|
636
|
+
await asyncio.wait_for(proc.wait(), timeout=1.0)
|
|
637
|
+
except asyncio.TimeoutError:
|
|
638
|
+
try:
|
|
639
|
+
subprocess.run(
|
|
640
|
+
["taskkill", "/T", "/F", "/PID", str(proc.pid)],
|
|
641
|
+
stdout=subprocess.DEVNULL,
|
|
642
|
+
stderr=subprocess.DEVNULL,
|
|
643
|
+
check=False,
|
|
644
|
+
)
|
|
645
|
+
except OSError:
|
|
646
|
+
proc.kill()
|
|
647
|
+
else:
|
|
648
|
+
try:
|
|
649
|
+
os.killpg(proc.pid, signal.SIGTERM)
|
|
650
|
+
except ProcessLookupError:
|
|
651
|
+
return
|
|
652
|
+
except OSError:
|
|
653
|
+
try:
|
|
654
|
+
proc.terminate()
|
|
655
|
+
except ProcessLookupError:
|
|
656
|
+
return
|
|
657
|
+
try:
|
|
658
|
+
await asyncio.wait_for(proc.wait(), timeout=1.0)
|
|
659
|
+
except asyncio.TimeoutError:
|
|
660
|
+
try:
|
|
661
|
+
os.killpg(proc.pid, signal.SIGKILL)
|
|
662
|
+
except OSError:
|
|
663
|
+
try:
|
|
664
|
+
proc.kill()
|
|
665
|
+
except ProcessLookupError:
|
|
666
|
+
pass
|
|
667
|
+
|
|
668
|
+
|
|
669
|
+
def user_shell_command(env: Mapping[str, str] | None = None) -> list[str]:
|
|
670
|
+
"""The user's interactive shell: $SHELL on Unix, %COMSPEC% on Windows."""
|
|
671
|
+
environ = os.environ if env is None else env
|
|
672
|
+
if sys.platform == "win32":
|
|
673
|
+
return [environ.get("COMSPEC") or "cmd.exe"]
|
|
674
|
+
shell = environ.get("SHELL")
|
|
675
|
+
if shell:
|
|
676
|
+
return [shell]
|
|
677
|
+
return [shutil.which("bash") or "/bin/sh"]
|
|
678
|
+
|
|
679
|
+
|
|
680
|
+
def wait_ignoring_ctrl_c(proc: subprocess.Popen[bytes]) -> tuple[int, bool]:
|
|
681
|
+
"""Wait for a child that shares our terminal; returns (exit_code, saw_ctrl_c).
|
|
682
|
+
|
|
683
|
+
Ctrl+C reaches both TermCode and the child. TermCode must survive it, so
|
|
684
|
+
the KeyboardInterrupt is swallowed and the child decides whether to exit.
|
|
685
|
+
"""
|
|
686
|
+
interrupted = False
|
|
687
|
+
while True:
|
|
688
|
+
try:
|
|
689
|
+
return proc.wait(), interrupted
|
|
690
|
+
except KeyboardInterrupt:
|
|
691
|
+
interrupted = True
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
def run_in_foreground(source: Path, workspace_root: Path) -> RunResult:
|
|
695
|
+
"""Compile (if needed) and run source with the real terminal (blocking).
|
|
696
|
+
|
|
697
|
+
Used by Shift+F5 while the TUI is suspended, so the program gets a true
|
|
698
|
+
TTY: colors, \\r progress bars, curses and single-key input all work.
|
|
699
|
+
Ctrl+C stops the program and is reported as cancelled.
|
|
700
|
+
"""
|
|
701
|
+
start = time.monotonic()
|
|
702
|
+
with tempfile.TemporaryDirectory(prefix="termcode_") as tmp:
|
|
703
|
+
plan = build_run_plan(source, workspace_root, Path(tmp))
|
|
704
|
+
|
|
705
|
+
def _wait(proc: subprocess.Popen[bytes]) -> tuple[int, bool]:
|
|
706
|
+
rc, interrupted = wait_ignoring_ctrl_c(proc)
|
|
707
|
+
return rc, interrupted
|
|
708
|
+
|
|
709
|
+
if plan.compile_cmd is not None:
|
|
710
|
+
compile_rc, cancelled = _wait(subprocess.Popen(plan.compile_cmd, cwd=plan.cwd))
|
|
711
|
+
if cancelled or compile_rc != 0:
|
|
712
|
+
return RunResult(
|
|
713
|
+
exit_code=compile_rc,
|
|
714
|
+
duration_seconds=time.monotonic() - start,
|
|
715
|
+
cancelled=cancelled,
|
|
716
|
+
compile_failed=not cancelled,
|
|
717
|
+
)
|
|
718
|
+
|
|
719
|
+
rc, cancelled = _wait(subprocess.Popen(plan.run_cmd, cwd=plan.cwd))
|
|
720
|
+
return RunResult(
|
|
721
|
+
exit_code=rc,
|
|
722
|
+
duration_seconds=time.monotonic() - start,
|
|
723
|
+
cancelled=cancelled,
|
|
724
|
+
compile_failed=False,
|
|
725
|
+
)
|