juart-cli 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.
- juart/__init__.py +3 -0
- juart/__main__.py +3 -0
- juart/_log_worker.py +52 -0
- juart/backends/__init__.py +1 -0
- juart/backends/_quartus_worker.py +254 -0
- juart/backends/base.py +37 -0
- juart/backends/quartus.py +561 -0
- juart/cli.py +102 -0
- juart/commands.py +127 -0
- juart/logging.py +314 -0
- juart/session.py +822 -0
- juart/shell.py +96 -0
- juart/terminal.py +369 -0
- juart_cli-0.1.0.dist-info/METADATA +183 -0
- juart_cli-0.1.0.dist-info/RECORD +17 -0
- juart_cli-0.1.0.dist-info/WHEEL +4 -0
- juart_cli-0.1.0.dist-info/entry_points.txt +2 -0
juart/shell.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"""Shell selection and child lifetime; the terminal owns cooked-mode handoff."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import os
|
|
5
|
+
import shutil
|
|
6
|
+
import signal
|
|
7
|
+
import subprocess
|
|
8
|
+
from contextlib import contextmanager
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class ShellError(ValueError):
|
|
13
|
+
"""The requested shell cannot be invoked safely with a known convention."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def resolve_shell(explicit: str | None = None) -> str:
|
|
17
|
+
selected = explicit or os.environ.get("COMSPEC" if os.name == "nt" else "SHELL")
|
|
18
|
+
if not selected:
|
|
19
|
+
raise ShellError("Select a shell with --shell or set COMSPEC/SHELL.")
|
|
20
|
+
executable = shutil.which(selected)
|
|
21
|
+
if not executable:
|
|
22
|
+
raise ShellError(f"Shell executable not found: {selected}")
|
|
23
|
+
shell_argv(executable, "")
|
|
24
|
+
return executable
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def shell_argv(executable: str, command: str | None) -> list[str]:
|
|
28
|
+
# PureWindowsPath is not used: normalize both separator styles for testability.
|
|
29
|
+
name = Path(executable.replace("\\", "/")).name.lower().removesuffix(".exe")
|
|
30
|
+
if name == "cmd":
|
|
31
|
+
flags = ["/d", "/s", "/c"]
|
|
32
|
+
elif name in {"powershell", "pwsh"}:
|
|
33
|
+
flags = ["-NoLogo", "-NoProfile", "-Command"]
|
|
34
|
+
elif name in {"sh", "bash", "zsh", "dash", "ksh", "fish"}:
|
|
35
|
+
flags = ["-c"]
|
|
36
|
+
else:
|
|
37
|
+
raise ShellError(f"Unsupported shell convention: {executable}")
|
|
38
|
+
return [executable] if command is None else [executable, *flags, command]
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@contextmanager
|
|
42
|
+
def child_console_signals():
|
|
43
|
+
# Windows broadcasts CTRL_C_EVENT to CLI and child. A caught handler keeps
|
|
44
|
+
# asyncio.Runner from cancelling the CLI; the child retains its own handler.
|
|
45
|
+
# POSIX SIGINT is routed by the terminal's context-aware Keys.SIGINT binding.
|
|
46
|
+
previous = None
|
|
47
|
+
if os.name == "nt":
|
|
48
|
+
previous = signal.signal(signal.SIGINT, lambda signum, frame: None)
|
|
49
|
+
try:
|
|
50
|
+
yield
|
|
51
|
+
finally:
|
|
52
|
+
if previous is not None:
|
|
53
|
+
signal.signal(signal.SIGINT, previous)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
async def _wait_shell(process: asyncio.subprocess.Process | subprocess.Popen) -> int:
|
|
57
|
+
if not isinstance(process, subprocess.Popen):
|
|
58
|
+
return await process.wait()
|
|
59
|
+
# Polling keeps cancellation bounded without leaving an executor thread
|
|
60
|
+
# blocked in Popen.wait() if the child cannot be reaped.
|
|
61
|
+
while (returncode := process.poll()) is None:
|
|
62
|
+
await asyncio.sleep(0.05)
|
|
63
|
+
return returncode
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
async def run_shell(command: str | None, executable: str) -> int:
|
|
67
|
+
"""Run explicit user text with inherited terminal streams, then reap the child."""
|
|
68
|
+
args = shell_argv(executable, command)
|
|
69
|
+
with child_console_signals():
|
|
70
|
+
try:
|
|
71
|
+
if os.name == "nt" and args[1:4] == ["/d", "/s", "/c"]:
|
|
72
|
+
# CMD does not decode CRT backslash-escaped quotes. Popen accepts
|
|
73
|
+
# a raw Windows command line; /s removes only our outer quotes.
|
|
74
|
+
prefix = subprocess.list2cmdline(args[:-1])
|
|
75
|
+
process = subprocess.Popen(f'{prefix} "{command}"', executable=executable)
|
|
76
|
+
else:
|
|
77
|
+
process = await asyncio.create_subprocess_exec(*args)
|
|
78
|
+
except OSError as exc:
|
|
79
|
+
raise ShellError(f"Cannot start shell: {exc}") from exc
|
|
80
|
+
try:
|
|
81
|
+
return await _wait_shell(process)
|
|
82
|
+
except (asyncio.CancelledError, KeyboardInterrupt):
|
|
83
|
+
if process.returncode is None:
|
|
84
|
+
try:
|
|
85
|
+
process.terminate()
|
|
86
|
+
except ProcessLookupError:
|
|
87
|
+
pass
|
|
88
|
+
try:
|
|
89
|
+
await asyncio.wait_for(_wait_shell(process), timeout=2.0)
|
|
90
|
+
except TimeoutError:
|
|
91
|
+
try:
|
|
92
|
+
process.kill()
|
|
93
|
+
except ProcessLookupError:
|
|
94
|
+
pass
|
|
95
|
+
await asyncio.wait_for(_wait_shell(process), timeout=2.0)
|
|
96
|
+
raise
|
juart/terminal.py
ADDED
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
"""Scrolling prompt_toolkit front end; transport and editor state live in Session."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
from typing import TYPE_CHECKING
|
|
7
|
+
|
|
8
|
+
from prompt_toolkit import Application
|
|
9
|
+
from prompt_toolkit.application import in_terminal
|
|
10
|
+
from prompt_toolkit.formatted_text import FormattedText
|
|
11
|
+
from prompt_toolkit.input import Input
|
|
12
|
+
from prompt_toolkit.key_binding import KeyBindings
|
|
13
|
+
from prompt_toolkit.keys import Keys
|
|
14
|
+
from prompt_toolkit.layout import HSplit, Layout, Window
|
|
15
|
+
from prompt_toolkit.layout.controls import FormattedTextControl
|
|
16
|
+
from prompt_toolkit.output import Output
|
|
17
|
+
from prompt_toolkit.shortcuts import print_formatted_text
|
|
18
|
+
from prompt_toolkit.utils import get_cwidth
|
|
19
|
+
|
|
20
|
+
from juart.shell import resolve_shell, run_shell
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from juart.commands import CommandResult
|
|
24
|
+
from juart.session import Session
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def render_rx(data: bytes, view: str = "text") -> str:
|
|
28
|
+
"""Render bytes without allowing device-controlled terminal escape sequences."""
|
|
29
|
+
if view == "hex":
|
|
30
|
+
return " ".join(f"{byte:02X}" for byte in data)
|
|
31
|
+
return "".join(
|
|
32
|
+
chr(byte) if byte in (9, 10, 13) or 32 <= byte <= 126 else f"\\x{byte:02X}" for byte in data
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _safe_text(text: str, *, column: int = 0) -> str:
|
|
37
|
+
"""Keep diagnostic/editor text on one line, including unknown error strings."""
|
|
38
|
+
parts = []
|
|
39
|
+
for char in text:
|
|
40
|
+
if char == "\t":
|
|
41
|
+
rendered = " " * (8 - column % 8)
|
|
42
|
+
elif char.isprintable():
|
|
43
|
+
rendered = char
|
|
44
|
+
else:
|
|
45
|
+
code = ord(char)
|
|
46
|
+
rendered = f"\\x{code:02X}" if code <= 255 else f"\\u{code:04X}"
|
|
47
|
+
parts.append(rendered)
|
|
48
|
+
column += get_cwidth(rendered)
|
|
49
|
+
return "".join(parts)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class _Terminal:
|
|
53
|
+
"""One app instance and its ordered input/output workers."""
|
|
54
|
+
|
|
55
|
+
def __init__(
|
|
56
|
+
self,
|
|
57
|
+
session: Session,
|
|
58
|
+
*,
|
|
59
|
+
shell: str | None,
|
|
60
|
+
input: Input | None,
|
|
61
|
+
output: Output | None,
|
|
62
|
+
auto_connect: bool,
|
|
63
|
+
) -> None:
|
|
64
|
+
self.session = session
|
|
65
|
+
self.shell = shell
|
|
66
|
+
self.output = output
|
|
67
|
+
self.auto_connect = auto_connect
|
|
68
|
+
self.input_queue: asyncio.Queue[tuple[str, str]] = asyncio.Queue()
|
|
69
|
+
self.output_queue: asyncio.Queue[tuple[str, str]] = asyncio.Queue()
|
|
70
|
+
self.pending_output: tuple[str, str] | None = None
|
|
71
|
+
self.output_lock = asyncio.Lock()
|
|
72
|
+
self.tasks: list[asyncio.Task] = []
|
|
73
|
+
self.shell_executable: str | None = None
|
|
74
|
+
self.return_code = 0
|
|
75
|
+
self.status_control = FormattedTextControl(self.status)
|
|
76
|
+
self.editor_control = FormattedTextControl(self.editor, focusable=True, show_cursor=True)
|
|
77
|
+
self.app: Application[int] = Application(
|
|
78
|
+
layout=Layout(
|
|
79
|
+
HSplit(
|
|
80
|
+
[
|
|
81
|
+
Window(self.status_control, height=1, wrap_lines=False),
|
|
82
|
+
Window(self.editor_control, wrap_lines=True, dont_extend_height=True),
|
|
83
|
+
]
|
|
84
|
+
),
|
|
85
|
+
focused_element=self.editor_control,
|
|
86
|
+
),
|
|
87
|
+
key_bindings=self.bindings(),
|
|
88
|
+
full_screen=False,
|
|
89
|
+
mouse_support=False,
|
|
90
|
+
input=input,
|
|
91
|
+
output=output,
|
|
92
|
+
)
|
|
93
|
+
# A lone Esc must cancel promptly rather than waiting for another key.
|
|
94
|
+
self.app.ttimeoutlen = 0.05
|
|
95
|
+
|
|
96
|
+
def status(self) -> str:
|
|
97
|
+
session = self.session
|
|
98
|
+
logger = getattr(session, "logger", None)
|
|
99
|
+
logging = "on" if logger is not None and logger.active else "off"
|
|
100
|
+
pending = len(session.buffer.encode("ascii", errors="replace"))
|
|
101
|
+
sending = ""
|
|
102
|
+
if session.sending:
|
|
103
|
+
accepted = getattr(session, "send_accepted", 0)
|
|
104
|
+
requested = getattr(session, "send_requested", 0)
|
|
105
|
+
sending = f" [sending {accepted}/{requested}]"
|
|
106
|
+
return (
|
|
107
|
+
f"[{session.state.lower()}] [{session.mode}] [{session.context}] "
|
|
108
|
+
f"[pending {pending} bytes]{sending} [log {logging}] [view {session.view}]"
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
def editor(self) -> FormattedText:
|
|
112
|
+
session = self.session
|
|
113
|
+
if session.context == "COMMAND":
|
|
114
|
+
prefix, text, cursor = ":", session.command, session.command_cursor
|
|
115
|
+
elif session.mode == "buffer":
|
|
116
|
+
prefix, text, cursor = "TX> ", session.buffer, session.cursor
|
|
117
|
+
else:
|
|
118
|
+
prefix, text, cursor = "TX> ", "", 0
|
|
119
|
+
cursor = max(0, min(cursor, len(text)))
|
|
120
|
+
before = _safe_text(text[:cursor], column=len(prefix))
|
|
121
|
+
after = _safe_text(text[cursor:], column=len(prefix) + get_cwidth(before))
|
|
122
|
+
return FormattedText(
|
|
123
|
+
[
|
|
124
|
+
("", prefix + before),
|
|
125
|
+
("[SetCursorPosition]", ""),
|
|
126
|
+
("", after),
|
|
127
|
+
]
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
def notify(self, text: str) -> None:
|
|
131
|
+
# FormattedText is deliberately plain text, never ANSI/HTML.
|
|
132
|
+
lines = str(text).replace("\r\n", "\n").replace("\r", "\n").split("\n")
|
|
133
|
+
self.output_queue.put_nowait(("juart", "\n".join(_safe_text(line) for line in lines)))
|
|
134
|
+
self.app.invalidate()
|
|
135
|
+
|
|
136
|
+
def on_rx(self, data: bytes) -> None:
|
|
137
|
+
if data:
|
|
138
|
+
self.output_queue.put_nowait(("RX", render_rx(data, self.session.view)))
|
|
139
|
+
self.app.invalidate()
|
|
140
|
+
|
|
141
|
+
def bindings(self) -> KeyBindings:
|
|
142
|
+
bindings = KeyBindings()
|
|
143
|
+
names = {
|
|
144
|
+
"enter": "enter",
|
|
145
|
+
# ICRNL can translate a physical Enter while output/shell handoff is cooked.
|
|
146
|
+
"c-j": "enter",
|
|
147
|
+
"escape": "escape",
|
|
148
|
+
"backspace": "backspace",
|
|
149
|
+
"delete": "delete",
|
|
150
|
+
"left": "left",
|
|
151
|
+
"right": "right",
|
|
152
|
+
"home": "home",
|
|
153
|
+
"end": "end",
|
|
154
|
+
"up": "up",
|
|
155
|
+
"down": "down",
|
|
156
|
+
"tab": "tab",
|
|
157
|
+
"c-c": "ctrl-c",
|
|
158
|
+
"c-d": "ctrl-d",
|
|
159
|
+
}
|
|
160
|
+
for key, name in names.items():
|
|
161
|
+
|
|
162
|
+
def handler(event, name=name):
|
|
163
|
+
self.input_queue.put_nowait(("key", name))
|
|
164
|
+
|
|
165
|
+
bindings.add(key)(handler)
|
|
166
|
+
|
|
167
|
+
@bindings.add(Keys.SIGINT)
|
|
168
|
+
def terminal_signal(event):
|
|
169
|
+
# POSIX foreground SIGINT reaches both CLI and child shell. During
|
|
170
|
+
# shell handoff the child handles it; otherwise use normal cleanup.
|
|
171
|
+
if self.session.context != "SHELL":
|
|
172
|
+
self.input_queue.put_nowait(("key", "ctrl-c"))
|
|
173
|
+
|
|
174
|
+
@bindings.add(Keys.BracketedPaste)
|
|
175
|
+
def paste(event):
|
|
176
|
+
self.input_queue.put_nowait(("paste", event.data))
|
|
177
|
+
|
|
178
|
+
@bindings.add(Keys.Any)
|
|
179
|
+
def literal(event):
|
|
180
|
+
# Unknown terminal/function/control sequences must not become TX bytes.
|
|
181
|
+
key = event.key_sequence[-1].key
|
|
182
|
+
if isinstance(key, str) and not isinstance(key, Keys) and len(key) == 1:
|
|
183
|
+
self.input_queue.put_nowait(("key", key))
|
|
184
|
+
|
|
185
|
+
return bindings
|
|
186
|
+
|
|
187
|
+
def print_message(self, label: str, text: str) -> None:
|
|
188
|
+
# A label on every physical line distinguishes device output from diagnostics.
|
|
189
|
+
# CR is allowed by the RX contract but cannot move over the RX label.
|
|
190
|
+
lines = text.replace("\r\n", "\n").replace("\r", "\n").split("\n")
|
|
191
|
+
print_formatted_text(
|
|
192
|
+
FormattedText([("", "\n".join(f"[{label}] {line}" for line in lines))]),
|
|
193
|
+
output=self.app.output,
|
|
194
|
+
)
|
|
195
|
+
|
|
196
|
+
async def print_output(self) -> None:
|
|
197
|
+
while True:
|
|
198
|
+
self.pending_output = await self.output_queue.get()
|
|
199
|
+
async with self.output_lock:
|
|
200
|
+
async with in_terminal():
|
|
201
|
+
self.print_message(*self.pending_output)
|
|
202
|
+
self.pending_output = None
|
|
203
|
+
for _ in range(63):
|
|
204
|
+
try:
|
|
205
|
+
message = self.output_queue.get_nowait()
|
|
206
|
+
except asyncio.QueueEmpty:
|
|
207
|
+
break
|
|
208
|
+
self.print_message(*message)
|
|
209
|
+
|
|
210
|
+
async def handle_result(self, result: CommandResult | None) -> bool:
|
|
211
|
+
if result is None:
|
|
212
|
+
return False
|
|
213
|
+
if result.exit_requested:
|
|
214
|
+
if not result.ok:
|
|
215
|
+
self.return_code = 1
|
|
216
|
+
self.app.exit(result=self.return_code)
|
|
217
|
+
return True
|
|
218
|
+
if result.shell_requested:
|
|
219
|
+
await self.invoke_shell(result.shell_command)
|
|
220
|
+
return False
|
|
221
|
+
|
|
222
|
+
async def invoke_shell(self, command: str | None) -> None:
|
|
223
|
+
session = self.session
|
|
224
|
+
# Session.execute enforces this too; retain the boundary at terminal handoff.
|
|
225
|
+
if session.state != "DISCONNECTED":
|
|
226
|
+
self.notify(f"Shell requires DISCONNECTED (currently {session.state}); use :d.")
|
|
227
|
+
return
|
|
228
|
+
saved = (session.mode, session.buffer, session.cursor)
|
|
229
|
+
session.context = "SHELL"
|
|
230
|
+
self.app.invalidate()
|
|
231
|
+
try:
|
|
232
|
+
if self.shell_executable is None:
|
|
233
|
+
self.shell_executable = resolve_shell(self.shell)
|
|
234
|
+
session.shell = self.shell_executable
|
|
235
|
+
async with self.output_lock:
|
|
236
|
+
async with in_terminal():
|
|
237
|
+
status = await run_shell(command, self.shell_executable)
|
|
238
|
+
self.notify(f"Shell exited with status {status}.")
|
|
239
|
+
except asyncio.CancelledError:
|
|
240
|
+
self.notify("Shell interrupted.")
|
|
241
|
+
raise
|
|
242
|
+
except KeyboardInterrupt:
|
|
243
|
+
self.notify("Shell interrupted (status 130).")
|
|
244
|
+
except Exception as exc:
|
|
245
|
+
self.notify(f"Shell failed: {exc}")
|
|
246
|
+
finally:
|
|
247
|
+
session.mode, session.buffer, session.cursor = saved
|
|
248
|
+
session.context = "TRANSMIT"
|
|
249
|
+
self.app.invalidate()
|
|
250
|
+
|
|
251
|
+
async def dispatch(self) -> None:
|
|
252
|
+
while True:
|
|
253
|
+
operation, value = await self.input_queue.get()
|
|
254
|
+
try:
|
|
255
|
+
if operation == "connect":
|
|
256
|
+
await self.session.connect()
|
|
257
|
+
result = None
|
|
258
|
+
elif operation == "paste":
|
|
259
|
+
result = await self.session.paste(value)
|
|
260
|
+
else:
|
|
261
|
+
result = await self.session.key(value)
|
|
262
|
+
if await self.handle_result(result):
|
|
263
|
+
return
|
|
264
|
+
except asyncio.CancelledError:
|
|
265
|
+
raise
|
|
266
|
+
except Exception as exc:
|
|
267
|
+
self.notify(f"Input operation failed: {exc}")
|
|
268
|
+
finally:
|
|
269
|
+
self.app.invalidate()
|
|
270
|
+
|
|
271
|
+
def worker_done(self, task: asyncio.Task) -> None:
|
|
272
|
+
if task.cancelled():
|
|
273
|
+
return
|
|
274
|
+
failure = task.exception()
|
|
275
|
+
if failure is not None and self.app.is_running and not self.app.is_done:
|
|
276
|
+
self.app.exit(exception=failure)
|
|
277
|
+
|
|
278
|
+
def start(self) -> None:
|
|
279
|
+
try:
|
|
280
|
+
self.shell_executable = resolve_shell(self.shell)
|
|
281
|
+
self.session.shell = self.shell_executable
|
|
282
|
+
except (OSError, ValueError) as exc:
|
|
283
|
+
self.notify(f"Shell unavailable: {exc}")
|
|
284
|
+
if self.auto_connect:
|
|
285
|
+
self.input_queue.put_nowait(("connect", ""))
|
|
286
|
+
self.tasks = [
|
|
287
|
+
asyncio.create_task(self.dispatch()),
|
|
288
|
+
asyncio.create_task(self.print_output()),
|
|
289
|
+
]
|
|
290
|
+
for task in self.tasks:
|
|
291
|
+
task.add_done_callback(self.worker_done)
|
|
292
|
+
|
|
293
|
+
async def run(self) -> int:
|
|
294
|
+
session = self.session
|
|
295
|
+
previous = (session.notify, session.on_rx, session.on_change)
|
|
296
|
+
session.notify, session.on_rx, session.on_change = (
|
|
297
|
+
self.notify,
|
|
298
|
+
self.on_rx,
|
|
299
|
+
self.app.invalidate,
|
|
300
|
+
)
|
|
301
|
+
failures: list[BaseException] = []
|
|
302
|
+
try:
|
|
303
|
+
try:
|
|
304
|
+
result = await self.app.run_async(pre_run=self.start)
|
|
305
|
+
self.return_code = max(self.return_code, result)
|
|
306
|
+
except (EOFError, KeyboardInterrupt):
|
|
307
|
+
pass
|
|
308
|
+
except BaseException as exc:
|
|
309
|
+
failures.append(exc)
|
|
310
|
+
try:
|
|
311
|
+
for task in self.tasks:
|
|
312
|
+
task.cancel()
|
|
313
|
+
for task in self.tasks:
|
|
314
|
+
while True:
|
|
315
|
+
try:
|
|
316
|
+
await asyncio.shield(task)
|
|
317
|
+
break
|
|
318
|
+
except asyncio.CancelledError as exc:
|
|
319
|
+
if task.cancelled():
|
|
320
|
+
break
|
|
321
|
+
# Cancellation of run() must not interrupt worker cleanup.
|
|
322
|
+
failures.append(exc)
|
|
323
|
+
except BaseException as exc:
|
|
324
|
+
failures.append(exc)
|
|
325
|
+
break
|
|
326
|
+
finally:
|
|
327
|
+
try:
|
|
328
|
+
await session.shutdown()
|
|
329
|
+
if session.state == "ERROR":
|
|
330
|
+
self.return_code = 1
|
|
331
|
+
except BaseException as exc:
|
|
332
|
+
self.return_code = 1
|
|
333
|
+
failures.append(exc)
|
|
334
|
+
finally:
|
|
335
|
+
try:
|
|
336
|
+
# run_async restored cooked mode; show final discard/close notices.
|
|
337
|
+
if self.pending_output is not None:
|
|
338
|
+
self.print_message(*self.pending_output)
|
|
339
|
+
self.pending_output = None
|
|
340
|
+
while not self.output_queue.empty():
|
|
341
|
+
self.print_message(*self.output_queue.get_nowait())
|
|
342
|
+
except BaseException as exc:
|
|
343
|
+
failures.append(exc)
|
|
344
|
+
except BaseException as exc:
|
|
345
|
+
failures.append(exc)
|
|
346
|
+
finally:
|
|
347
|
+
session.notify, session.on_rx, session.on_change = previous
|
|
348
|
+
if failures:
|
|
349
|
+
failure = failures[0]
|
|
350
|
+
for extra in failures[1:]:
|
|
351
|
+
if extra is not failure:
|
|
352
|
+
failure.add_note(f"Additional terminal cleanup failure: {extra!r}")
|
|
353
|
+
raise failure
|
|
354
|
+
return self.return_code
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
async def run_terminal(
|
|
358
|
+
session: Session,
|
|
359
|
+
*,
|
|
360
|
+
shell: str | None = None,
|
|
361
|
+
input: Input | None = None,
|
|
362
|
+
output: Output | None = None,
|
|
363
|
+
auto_connect: bool = True,
|
|
364
|
+
) -> int:
|
|
365
|
+
"""Run the inline CLI and always release session resources, including on EOF."""
|
|
366
|
+
terminal = _Terminal(
|
|
367
|
+
session, shell=shell, input=input, output=output, auto_connect=auto_connect
|
|
368
|
+
)
|
|
369
|
+
return await terminal.run()
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: juart-cli
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Interactive JTAG UART terminal with direct and buffered transmission
|
|
5
|
+
Requires-Python: >=3.12
|
|
6
|
+
Requires-Dist: prompt-toolkit<4,>=3.0.48
|
|
7
|
+
Description-Content-Type: text/markdown
|
|
8
|
+
|
|
9
|
+
[English](README.md) | [日本語](README.ja.md) | [한국어](README.ko.md)
|
|
10
|
+
|
|
11
|
+
# juart-cli
|
|
12
|
+
|
|
13
|
+
An interactive JTAG UART terminal for Intel/Altera Quartus FPGA setups, featuring both immediate (`direct`) and line-edited (`buffer`) transmission, exact binary HEX transmission, safe shell handoff, and opt-in JSONL session logging.
|
|
14
|
+
|
|
15
|
+
## Key Features
|
|
16
|
+
|
|
17
|
+
- **Dual Transmission Modes**
|
|
18
|
+
- `[direct]` (default): transmits each printable ASCII key immediately (`Enter` sends `0x0D`, `Tab` sends `0x09`, `Backspace` sends `0x08`, `Ctrl+D` sends `0x04`). Local TX echo is off.
|
|
19
|
+
- `[buffer]`: edit up to 4096 ASCII/Tab bytes locally before sending. Pressing `Enter` transmits **only** the edited bytes with no implicit CR/LF; empty idle `Enter` sends nothing.
|
|
20
|
+
- **Exact Binary TX & Safe RX Rendering**
|
|
21
|
+
- Send arbitrary binary payloads (1–4096 bytes) via `:hex <pairs>` without implicit line endings.
|
|
22
|
+
- Switch receive formatting between `:view text` (control bytes safely escaped as `\xNN`, blocking terminal escape injection) and `:view hex`.
|
|
23
|
+
- **Subprocess-Isolated Quartus Backend**
|
|
24
|
+
- Vendor native libraries (`jtag_client` / `jtag_atlantic`) are never loaded in the UI process.
|
|
25
|
+
- All vendor I/O runs inside an isolated worker process with bounded timeouts; stalled operations terminate and reap the worker cleanly and track accepted bytes separately from flush completion.
|
|
26
|
+
- **Safe External Tool & Shell Handoff**
|
|
27
|
+
- Release the JTAG UART cleanly with `:d` (`:disconnect`) while keeping the CLI open and preserving pending buffer input.
|
|
28
|
+
- Run external commands (such as an FPGA programmer) or an interactive shell with `:! [command]` only while disconnected, then resume with `:c` (`:connect`).
|
|
29
|
+
- **Opt-In Structured JSONL Logging**
|
|
30
|
+
- Record accepted TX bytes, raw RX bytes, lifecycle transitions, and delivery results to a brand-new JSONL file via `:log start <path>` / `:log stop`.
|
|
31
|
+
- Disk I/O is isolated in a bounded worker subprocess so filesystem errors or queue overflows never block or terminate the UART session.
|
|
32
|
+
- **Honest Delivery Accounting**
|
|
33
|
+
- Confirmed zero-byte failures retain the text buffer for explicit retry.
|
|
34
|
+
- Partial or uncertain writes clear the editor, report accepted byte counts, and print a recoverable snapshot—never silently replaying potentially duplicated commands.
|
|
35
|
+
|
|
36
|
+
## Requirements
|
|
37
|
+
|
|
38
|
+
- **Python**: 3.12 or newer (64-bit)
|
|
39
|
+
- **Package manager**: [`uv`](https://docs.astral.sh/uv/) (recommended) or standard `pip` + `venv`
|
|
40
|
+
- **Vendor stack**: Intel/Altera Quartus (or Quartus Programmer) matching the Python runtime architecture:
|
|
41
|
+
- Native Windows x64 Python + Quartus `bin64` (`jtag_client.dll`, `jtag_atlantic.dll`, `jtagconfig.exe`)
|
|
42
|
+
- Linux x64 Python + Quartus `linux64` (`libjtag_client.so`, `libjtag_atlantic.so`, `jtagconfig`)
|
|
43
|
+
- **Hardware**: Matching JTAG cable OS driver, running JTAG server, and an FPGA already configured with a JTAG UART design.
|
|
44
|
+
- `juart-cli` does **not** bundle vendor libraries, OS drivers, or bitstreams, and never programs or flashes the FPGA automatically.
|
|
45
|
+
|
|
46
|
+
## Quick Start
|
|
47
|
+
|
|
48
|
+
### Install with `uv` (recommended)
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
uv sync --dev
|
|
52
|
+
uv run juart --help
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
### Install with `pip` (without `uv`)
|
|
56
|
+
|
|
57
|
+
```powershell
|
|
58
|
+
# PowerShell (Windows)
|
|
59
|
+
python -m venv .venv
|
|
60
|
+
.venv\Scripts\python.exe -m pip install -e .
|
|
61
|
+
.venv\Scripts\juart.exe --help
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
# Linux (bash)
|
|
66
|
+
python3 -m venv .venv
|
|
67
|
+
.venv/bin/python -m pip install -e .
|
|
68
|
+
.venv/bin/juart --help
|
|
69
|
+
```
|
|
70
|
+
|
|
71
|
+
> With `pip`, run `.venv\Scripts\juart.exe` (or `python -m juart` with the venv active) instead of `uv run juart`.
|
|
72
|
+
|
|
73
|
+
### Connect to Hardware
|
|
74
|
+
|
|
75
|
+
Set your Quartus installation root and verify cable visibility before connecting:
|
|
76
|
+
|
|
77
|
+
```powershell
|
|
78
|
+
# PowerShell (Windows) — adjust path to your Quartus installation
|
|
79
|
+
$env:QUARTUS_ROOTDIR = 'C:\altera_lite\25.1std\quartus'
|
|
80
|
+
uv run juart --list-drivers
|
|
81
|
+
uv run juart --list-cables
|
|
82
|
+
|
|
83
|
+
# Launch interactive terminal (auto-connects if target is unique)
|
|
84
|
+
uv run juart --quartus-root $env:QUARTUS_ROOTDIR
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
# Cygwin (Bash / Mintty) — use the native Windows Python venv with Cygwin Bash for :!
|
|
89
|
+
export QUARTUS_ROOTDIR='C:\altera_lite\25.1std\quartus'
|
|
90
|
+
/cygdrive/c/path/to/juart-cli/.venv/Scripts/python.exe -m juart --shell "$(cygpath -w /bin/bash)"
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
# Linux (bash) — adjust path to your Quartus installation
|
|
95
|
+
export QUARTUS_ROOTDIR=/opt/intelFPGA/quartus
|
|
96
|
+
uv run juart --list-drivers
|
|
97
|
+
uv run juart --list-cables
|
|
98
|
+
|
|
99
|
+
# Launch with an explicit cable, device, and UART instance
|
|
100
|
+
uv run juart --cable "USB-Blaster [USB-0]" --device 1 --instance 0
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
You can invoke the CLI either as `juart` or via `python -m juart`. See the [User Guide & Operations Runbook](docs/user-guide.en.md) for CMD, Git Bash, Cygwin `PATH`, and WSL details.
|
|
104
|
+
|
|
105
|
+
## CLI Options
|
|
106
|
+
|
|
107
|
+
| Option | Description |
|
|
108
|
+
| --- | --- |
|
|
109
|
+
| `--version` | Print version and exit. |
|
|
110
|
+
| `--driver {quartus}` | Transport driver backend (default: `quartus`). |
|
|
111
|
+
| `--list-drivers` | Check whether Quartus x64 files are present at `--quartus-root` / `QUARTUS_ROOTDIR`. |
|
|
112
|
+
| `--list-cables` | Enumerate local JTAG cables via `jtagconfig --listhardware`. |
|
|
113
|
+
| `--cable CABLE` | Exact cable identifier reported by `--list-cables`. |
|
|
114
|
+
| `--device N` | 1-based JTAG chain device index. |
|
|
115
|
+
| `--instance N` | JTAG UART instance index (`0`–`255`). |
|
|
116
|
+
| `--quartus-root PATH` | Quartus installation directory (overrides `QUARTUS_ROOTDIR`). |
|
|
117
|
+
| `--shell PATH` | Shell executable for `:!` (`cmd`, `powershell`, `pwsh`, `sh`, `bash`, `zsh`, `dash`, `ksh`, `fish`). |
|
|
118
|
+
|
|
119
|
+
> `--list-drivers` and `--list-cables` are mutually exclusive and run non-interactively. Starting an interactive session requires a TTY.
|
|
120
|
+
|
|
121
|
+
## Interactive Commands & Keys
|
|
122
|
+
|
|
123
|
+
Press `:` in either transmission mode to enter command mode (`::` sends/inserts a literal colon).
|
|
124
|
+
|
|
125
|
+
| Command / Key | Action |
|
|
126
|
+
| --- | --- |
|
|
127
|
+
| `:direct`, `:buffer` | Switch transmission mode (clear or submit pending buffer before returning to direct). |
|
|
128
|
+
| `:c` / `:connect` | Connect to the configured JTAG UART target. |
|
|
129
|
+
| `:d` / `:disconnect` | Release JTAG UART ownership while keeping the CLI and pending buffer intact. |
|
|
130
|
+
| `:r` / `:reconnect` | Disconnect and reconnect to the target. |
|
|
131
|
+
| `:s` / `:status` | Show connection state, mode, pending byte count, view, log, shell, and last error. |
|
|
132
|
+
| `:i` / `:info` | Show driver, resolved target (`cable`, `device`, `instance`), state, and worker metadata. |
|
|
133
|
+
| `:h` / `:help` | Display the in-terminal help summary. |
|
|
134
|
+
| `:q` / `:quit`, `Ctrl+C` | Release resources, flush/stop any active log, and exit. |
|
|
135
|
+
| `:hex <pairs>` | Send 1–4096 space-separated two-digit hex bytes (requires empty buffer and idle connection). |
|
|
136
|
+
| `:view text\|hex` | Toggle RX display between sanitized ASCII text and uppercase hex bytes. |
|
|
137
|
+
| `:log start <path>` | Create a new JSONL log file exclusively (quote paths containing spaces). |
|
|
138
|
+
| `:log stop` | Flush and close the active JSONL log file. |
|
|
139
|
+
| `:! [command]` | Run a shell command or open an interactive shell (requires `DISCONNECTED` state via `:d`). |
|
|
140
|
+
| `::` | Send (`direct`) or insert (`buffer`) a literal `:`. |
|
|
141
|
+
| `Esc` | Cancel command input, or clear the pending buffer in `buffer` mode. |
|
|
142
|
+
| `Tab`, `Up` / `Down` | Command completion and session-local command history (in command mode). |
|
|
143
|
+
|
|
144
|
+
## Development & Testing
|
|
145
|
+
|
|
146
|
+
```bash
|
|
147
|
+
# Run hardware-independent unit and integration tests
|
|
148
|
+
uv run pytest
|
|
149
|
+
|
|
150
|
+
# Lint with Ruff
|
|
151
|
+
uv run ruff check .
|
|
152
|
+
|
|
153
|
+
# Build wheel and sdist packages
|
|
154
|
+
uv build
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
Hardware acceptance tests in [`tests/test_hardware.py`](tests/test_hardware.py) are skipped by default and require explicit opt-in (`JUART_RUN_HARDWARE=1`) against a board loaded with any JTAG UART byte-echo (loopback) design. `juart-cli` itself works with any FPGA design that exposes a standard Intel/Altera JTAG UART IP core.
|
|
158
|
+
|
|
159
|
+
## Releases (maintainers)
|
|
160
|
+
|
|
161
|
+
CI checks frozen dependencies, Ruff, Windows/Linux/macOS tests, and pip/uv installation of the built packages. Hosted CI never runs physical FPGA tests.
|
|
162
|
+
|
|
163
|
+
One-time setup:
|
|
164
|
+
|
|
165
|
+
1. Push the workflows to `main`. Create the GitHub environment **`pypi`** under repository Settings → Environments; configure approval protection where available.
|
|
166
|
+
2. On [PyPI Publishing](https://pypi.org/manage/account/publishing/), add a **pending publisher**: project `juart-cli`, owner `snowykr`, repository `juart-cli`, workflow filename **`publish.yml`**, environment **`pypi`**. For an existing PyPI project, configure its trusted publisher instead. No API-token secret is required.
|
|
167
|
+
|
|
168
|
+
For each release:
|
|
169
|
+
|
|
170
|
+
1. Set the same version in `pyproject.toml` and `src/juart/__init__.py`, run `uv lock`, then commit and push to `main`. Use `X.Y.Z` or a prerelease such as `X.Y.Zrc1`.
|
|
171
|
+
2. Run **Actions → Prepare release → Run workflow** on `main`. After validation, it creates a draft `v<version>` release with generated notes for that exact commit. Existing tags are not reused.
|
|
172
|
+
3. Review the draft and click **Publish release** yourself. The **Publish release** workflow validates the tag/version and main ancestry, reruns CI, publishes the tested wheel/sdist to PyPI through OIDC, then attaches those files and `SHA256SUMS` to GitHub.
|
|
173
|
+
|
|
174
|
+
Draft creation does not publish to PyPI. The manual publication is intentional: a release published by another workflow using `GITHUB_TOKEN` would not trigger the publishing workflow. PyPI packages are public even when this repository is private, and uploaded versions cannot be overwritten. On a partial upload failure, inspect which files reached PyPI before retrying; the workflow does not silently skip existing files. If only GitHub asset attachment fails, rerun that failed job rather than the successful PyPI job.
|
|
175
|
+
|
|
176
|
+
After the first successful publication, users can run `pip install juart-cli` or `uv tool install juart-cli`, then `juart`. Quartus and cable drivers remain separate prerequisites.
|
|
177
|
+
|
|
178
|
+
## Documentation
|
|
179
|
+
|
|
180
|
+
- **User Guide & Operations Runbook**
|
|
181
|
+
- [English (`docs/user-guide.en.md`)](docs/user-guide.en.md)
|
|
182
|
+
- [日本語 (`docs/user-guide.ja.md`)](docs/user-guide.ja.md)
|
|
183
|
+
- [한국어 (`docs/user-guide.ko.md`)](docs/user-guide.ko.md)
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
juart/__init__.py,sha256=cR5jBpo96VSNZEuNHVG3uCAkllS2mloGQAQxrVVwQRo,62
|
|
2
|
+
juart/__main__.py,sha256=lK4z4BBfypAN06sG9ymGRalCvYJkLNGOQCP9n-OyEJE,53
|
|
3
|
+
juart/_log_worker.py,sha256=vbYaJoyjv7Xy16mwFiw8l-aCjARn3wlCIdpJB4vZX48,1739
|
|
4
|
+
juart/cli.py,sha256=TPZFrK7b0EuqEUgdnNgusvy9xnGOqZtc7R92pPu7ny8,3867
|
|
5
|
+
juart/commands.py,sha256=oDmw_rzQlYF6LtoTQMZ0XPoeQ3V58Ta56PmiYnYc9SY,4182
|
|
6
|
+
juart/logging.py,sha256=AjV83CwroL_mcoGxZBYUTrROwFaqoFivyI0xnRfc1mA,13177
|
|
7
|
+
juart/session.py,sha256=aBEZ85JKcVblKb-5LQQYp1P5ggcEdlpyJOMG_Y9ZAsM,34336
|
|
8
|
+
juart/shell.py,sha256=nyWdm1EHAvbHQA9YI6FfHlyADXM0ohOlyrZDKv6haQI,3807
|
|
9
|
+
juart/terminal.py,sha256=clfpvP7N91wmGkPc9uqmSdGXw6S15AFJwKAC02Ix8-k,14335
|
|
10
|
+
juart/backends/__init__.py,sha256=O3ZlSTR7fSSp1EiUpjnEEG9RotweiQsw-PigLSHc4q8,42
|
|
11
|
+
juart/backends/_quartus_worker.py,sha256=ywbKCtUr8t9V3lGpf2J9J7faZAGYnZ5sLQIbQ2jePh0,10097
|
|
12
|
+
juart/backends/base.py,sha256=SXBrUudUsHEecsN4u3Yf6l7h-NvIKouE0EjsXUucsRs,1096
|
|
13
|
+
juart/backends/quartus.py,sha256=Nl6rHJIKB3YGy1kjFShghJhzPh4OyaaMZg1WUgzyBs4,22618
|
|
14
|
+
juart_cli-0.1.0.dist-info/METADATA,sha256=KAG0cVWfz0PEWCX0fTMwKk216PEOHZ6eOl6BG6NPRY8,10256
|
|
15
|
+
juart_cli-0.1.0.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
16
|
+
juart_cli-0.1.0.dist-info/entry_points.txt,sha256=MpqqEelUmXfegz5xVB1BS1n17xbE1-Bgm3qppY04bVM,41
|
|
17
|
+
juart_cli-0.1.0.dist-info/RECORD,,
|