class PtyShell(Shell):
"""An interactive bash / zsh in a pseudo-terminal, started on the first command."""
def __init__(self, program: str, cwd: str | Path, on_output: OutputCallback | None) -> None:
super().__init__(cwd, on_output)
self.program = program
self.persistent = True
self._master: int | None = None
self._process: asyncio.subprocess.Process | None = None
self._buffer = bytearray()
self._ready: asyncio.Event | None = None
self._exit_task: asyncio.Task[None] | None = None
self._interrupted = False
@property
def running(self) -> bool:
"""Whether the shell process is up."""
return self._master is not None
async def start(self) -> None:
"""Start the shell and wait until it is set up (prompt and echo off)."""
if sys.platform == "win32":
msg = "No pseudo-terminals on Windows"
raise OSError(msg)
import fcntl
import pty
import termios
master, slave = pty.openpty()
def controlling_terminal() -> None:
os.setsid()
fcntl.ioctl(slave, termios.TIOCSCTTY, 0)
self._process = await asyncio.create_subprocess_exec(
self.program,
"-i",
stdin=slave,
stdout=slave,
stderr=slave,
cwd=self.cwd,
env={**os.environ, **SHELL_ENV},
preexec_fn=controlling_terminal,
)
os.close(slave)
os.set_blocking(master, False)
self._master = master
self._ready = asyncio.Event()
asyncio.get_running_loop().add_reader(master, self._on_readable)
init = _ZSH_INIT if Path(self.program).name == "zsh" else _BASH_INIT
self._write(f" {init}\n")
try:
await asyncio.wait_for(self._ready.wait(), INIT_TIMEOUT)
except TimeoutError:
self.close()
msg = f"{self.program} did not come up within {INIT_TIMEOUT:.0f}s"
raise OSError(msg) from None
async def run(self, command: str) -> ShellCommand:
if self.busy:
msg = "A command is still running"
raise RuntimeError(msg)
if not self.running:
await self.start()
entry = ShellCommand(command, self.cwd)
self.current = entry
self._interrupted = False
self._write(command.rstrip("\n") + "\n")
return entry
async def send_input(self, text: str) -> None:
self._write(text.rstrip("\n") + "\n")
async def interrupt(self) -> None:
"""Ctrl+C; a second interrupt of the same command ends the shell.
A command that replaced the shell or its prompt hook (``exec bash``) never
reports back; the next command then starts a new shell in the same directory.
"""
if self._interrupted and (command := self.current) is not None:
self.close()
command.append(b"\r\n[acptui: shell ended, the next command starts a new one]\r\n")
self._finish(command, -1)
return
self._interrupted = True
self._write(b"\x03")
def _write(self, data: str | bytes) -> None:
if self._master is None:
return
with contextlib.suppress(OSError):
os.write(self._master, data.encode() if isinstance(data, str) else data)
def _on_readable(self) -> None:
if self._master is None:
return
try:
data = os.read(self._master, 64 * 1024)
except BlockingIOError:
return
except OSError:
data = b""
if not data:
self._gone()
return
self._buffer.extend(data)
self._drain()
def _drain(self) -> None:
while match := _MARK.search(self._buffer):
status, cwd = int(match.group(1)), match.group(2).decode(errors="replace")
before = bytes(self._buffer[: match.start()])
del self._buffer[: match.end()]
if cwd:
self.cwd = cwd
if self._ready is not None and not self._ready.is_set():
self._ready.set() # set up: what came before (rc file noise) is dropped
continue
if (command := self.current) is not None:
if before:
command.append(before)
self._finish(command, status)
if (command := self.current) is not None and self._buffer:
# Keep a possible partial marker; everything before it is output.
keep = self._buffer.rfind(b"\x1b")
cut = keep if keep != -1 and b"\x07" not in self._buffer[keep:] else len(self._buffer)
if cut:
command.append(bytes(self._buffer[:cut]))
del self._buffer[:cut]
self._notify(command)
def _gone(self) -> None:
"""The shell exited (``exit``) or its terminal closed."""
process = self._process
self._process = None
self._teardown()
if (command := self.current) is None:
return
if process is None:
self._finish(command, -1)
return
async def finish() -> None:
# The terminal closes before the exit status is known
try:
code = await asyncio.wait_for(process.wait(), 5)
except TimeoutError:
code = -1
self._finish(command, code)
self._exit_task = asyncio.get_running_loop().create_task(finish())
def _teardown(self) -> None:
if self._master is not None:
with contextlib.suppress(Exception):
asyncio.get_running_loop().remove_reader(self._master)
with contextlib.suppress(OSError):
os.close(self._master)
self._master = None
self._buffer.clear()
def close(self) -> None:
process = self._process
self._teardown()
if sys.platform != "win32" and process is not None and process.returncode is None:
with contextlib.suppress(ProcessLookupError, PermissionError):
os.killpg(process.pid, signal.SIGHUP)
self._process = None