|
| 1 | +"""Control Mode engine for libtmux.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import logging |
| 6 | +import shutil |
| 7 | +import subprocess |
| 8 | +import threading |
| 9 | +import typing as t |
| 10 | + |
| 11 | +from libtmux import exc |
| 12 | +from libtmux._internal.engines.base import Engine |
| 13 | +from libtmux.common import tmux_cmd |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | + |
| 17 | + |
| 18 | +class ControlModeEngine(Engine): |
| 19 | + """Engine that runs tmux commands via a persistent Control Mode process.""" |
| 20 | + |
| 21 | + def __init__(self) -> None: |
| 22 | + self.process: subprocess.Popen[str] | None = None |
| 23 | + self._lock = threading.Lock() |
| 24 | + self._server_args: t.Sequence[str | int] | None = None |
| 25 | + |
| 26 | + def close(self) -> None: |
| 27 | + """Terminate the tmux control mode process.""" |
| 28 | + if self.process: |
| 29 | + self.process.terminate() |
| 30 | + self.process.wait() |
| 31 | + self.process = None |
| 32 | + |
| 33 | + def __del__(self) -> None: |
| 34 | + """Cleanup the process on destruction.""" |
| 35 | + self.close() |
| 36 | + |
| 37 | + def _start_process(self, server_args: t.Sequence[str | int] | None) -> None: |
| 38 | + """Start the tmux control mode process.""" |
| 39 | + tmux_bin = shutil.which("tmux") |
| 40 | + if not tmux_bin: |
| 41 | + raise exc.TmuxCommandNotFound |
| 42 | + |
| 43 | + cmd = [tmux_bin] |
| 44 | + if server_args: |
| 45 | + cmd.extend(str(a) for a in server_args) |
| 46 | + cmd.append("-C") |
| 47 | + |
| 48 | + logger.debug(f"Starting Control Mode process: {cmd}") |
| 49 | + self.process = subprocess.Popen( |
| 50 | + cmd, |
| 51 | + stdin=subprocess.PIPE, |
| 52 | + stdout=subprocess.PIPE, |
| 53 | + stderr=subprocess.PIPE, |
| 54 | + text=True, |
| 55 | + bufsize=0, # Unbuffered |
| 56 | + errors="backslashreplace", |
| 57 | + ) |
| 58 | + self._server_args = server_args |
| 59 | + |
| 60 | + def run( |
| 61 | + self, |
| 62 | + cmd: str, |
| 63 | + cmd_args: t.Sequence[str | int] | None = None, |
| 64 | + server_args: t.Sequence[str | int] | None = None, |
| 65 | + ) -> tmux_cmd: |
| 66 | + """Run a tmux command via Control Mode.""" |
| 67 | + with self._lock: |
| 68 | + if self.process is None: |
| 69 | + self._start_process(server_args) |
| 70 | + elif server_args != self._server_args: |
| 71 | + # If server_args changed, we might need a new process. |
| 72 | + # For now, just warn or restart. Restarting is safer. |
| 73 | + logger.warning( |
| 74 | + "Server args changed, restarting Control Mode process. " |
| 75 | + f"Old: {self._server_args}, New: {server_args}" |
| 76 | + ) |
| 77 | + self.close() |
| 78 | + self._start_process(server_args) |
| 79 | + |
| 80 | + assert self.process is not None |
| 81 | + assert self.process.stdin is not None |
| 82 | + assert self.process.stdout is not None |
| 83 | + |
| 84 | + # Construct the command line |
| 85 | + # We use subprocess.list2cmdline for basic quoting, but we need to be |
| 86 | + # careful. tmux control mode accepts a single line. |
| 87 | + full_args = [cmd] |
| 88 | + if cmd_args: |
| 89 | + full_args.extend(str(a) for a in cmd_args) |
| 90 | + |
| 91 | + command_line = subprocess.list2cmdline(full_args) |
| 92 | + |
| 93 | + logger.debug(f"Sending to Control Mode: {command_line}") |
| 94 | + try: |
| 95 | + self.process.stdin.write(command_line + "\n") |
| 96 | + self.process.stdin.flush() |
| 97 | + except BrokenPipeError: |
| 98 | + # Process died? |
| 99 | + logger.exception("Control Mode process died, restarting...") |
| 100 | + self.close() |
| 101 | + self._start_process(server_args) |
| 102 | + assert self.process is not None |
| 103 | + assert self.process.stdin is not None |
| 104 | + assert self.process.stdout is not None |
| 105 | + self.process.stdin.write(command_line + "\n") |
| 106 | + self.process.stdin.flush() |
| 107 | + |
| 108 | + # Read response |
| 109 | + stdout_lines: list[str] = [] |
| 110 | + stderr_lines: list[str] = [] |
| 111 | + returncode = 0 |
| 112 | + |
| 113 | + while True: |
| 114 | + line = self.process.stdout.readline() |
| 115 | + if not line: |
| 116 | + # EOF |
| 117 | + logger.error("Unexpected EOF from Control Mode process") |
| 118 | + returncode = 1 |
| 119 | + break |
| 120 | + |
| 121 | + line = line.rstrip("\n") |
| 122 | + |
| 123 | + if line.startswith("%begin"): |
| 124 | + # Start of response |
| 125 | + continue |
| 126 | + elif line.startswith("%end"): |
| 127 | + # End of success response |
| 128 | + returncode = 0 |
| 129 | + break |
| 130 | + elif line.startswith("%error"): |
| 131 | + # End of error response |
| 132 | + returncode = 1 |
| 133 | + # Captured lines are the error message |
| 134 | + stderr_lines = stdout_lines |
| 135 | + stdout_lines = [] |
| 136 | + break |
| 137 | + elif line.startswith("%"): |
| 138 | + # Notification (ignore for now) |
| 139 | + logger.debug(f"Control Mode Notification: {line}") |
| 140 | + continue |
| 141 | + else: |
| 142 | + stdout_lines.append(line) |
| 143 | + |
| 144 | + # Tmux usually puts error message in stdout (captured above) for %error |
| 145 | + # But we moved it to stderr_lines if %error occurred. |
| 146 | + |
| 147 | + # Mimic subprocess.communicate output structure |
| 148 | + return tmux_cmd( |
| 149 | + cmd=[cmd] + (list(map(str, cmd_args)) if cmd_args else []), |
| 150 | + stdout=stdout_lines, |
| 151 | + stderr=stderr_lines, |
| 152 | + returncode=returncode, |
| 153 | + ) |
0 commit comments