Debian Codegraph @

src/libtmux/_internal/control_mode.py

raw symbols SCIP
1 """Control-mode client context manager for tmux testing.
2
3 Provides a context manager that spawns a ``tmux -C attach-session``
4 subprocess, creating a real tmux client that satisfies commands
5 requiring an attached client (e.g. ``display-popup``, ``detach-client``).
6 """
7
8 from __future__ import annotations
9
10 import os
11 import subprocess
12 import typing as t
13
14 from libtmux.test.retry import retry_until
15
16 if t.TYPE_CHECKING:
17 import types
18
19 from libtmux.server import Server
20 from libtmux.session import Session
21
22
23 class ControlMode:
24 """Context manager that spawns a tmux control-mode client.
25
26 Creates a real client attached to the session, visible in
27 ``Server.list_clients()``. The client communicates via the tmux
28 control protocol on stdout.
29
30 While active, ``Server.list_clients()`` will include this client.
31
32 Parameters
33 ----------
34 server : Server
35 The tmux server instance.
36 session : Session
37 The session to attach to.
38
39 Examples
40 --------
41 >>> with ControlMode(server=server, session=session) as ctl:
42 ... clients = server.list_clients()
43 ... assert len(clients) > 0
44 ... assert ctl.client_name != ''
45 """
46
47 server: Server
48 session: Session
49 client_name: str
50 stdout: t.IO[str]
51
52 _proc: subprocess.Popen[str]
53 _write_fd: int
54
55 def __init__(self, server: Server, session: Session) -> None:
56 self.server = server
57 self.session = session
58
59 def __enter__(self) -> ControlMode:
60 """Spawn control-mode client and wait for registration."""
61 read_fd, self._write_fd = os.pipe()
62
63 tmux_bin = self.server.tmux_bin or "tmux"
64
65 if self.server.socket_name is not None:
66 socket_args = ["-L", str(self.server.socket_name)]
67 elif self.server.socket_path is not None:
68 socket_args = ["-S", str(self.server.socket_path)]
69 else:
70 socket_args = []
71
72 cmd = [
73 tmux_bin,
74 *socket_args,
75 "-C",
76 "attach-session",
77 "-t",
78 str(self.session.session_id),
79 ]
80
81 try:
82 try:
83 self._proc = subprocess.Popen(
84 cmd,
85 stdin=read_fd,
86 stdout=subprocess.PIPE,
87 stderr=subprocess.PIPE,
88 text=True,
89 encoding="utf-8",
90 )
91 finally:
92 # subprocess owns read_fd now
93 os.close(read_fd)
94 except BaseException:
95 # __exit__ will not run if __enter__ fails
96 os.close(self._write_fd)
97 raise
98
99 self.stdout = self._proc.stdout # type: ignore[assignment]
100 client_pid = str(self._proc.pid)
101
102 def client_registered() -> bool:
103 result = self.server.cmd(
104 "list-clients",
105 "-F",
106 "#{client_pid}\t#{client_name}",
107 )
108 for line in result.stdout:
109 pid, _, client_name = line.partition("\t")
110 if pid == client_pid and client_name:
111 self.client_name = client_name.strip()
112 return True
113 return False
114
115 try:
116 retry_until(client_registered, 3, raises=True)
117 except Exception:
118 os.close(self._write_fd)
119 self._proc.terminate()
120 try:
121 self._proc.wait(timeout=5)
122 except subprocess.TimeoutExpired:
123 self._proc.kill()
124 self._proc.wait()
125 raise
126
127 return self
128
129 def __exit__(
130 self,
131 exc_type: type[BaseException] | None,
132 exc_val: BaseException | None,
133 exc_tb: types.TracebackType | None,
134 ) -> None:
135 """Terminate control-mode client."""
136 # Close write end — causes the control-mode client to exit (EOF on stdin)
137 os.close(self._write_fd)
138
139 self._proc.terminate()
140 try:
141 self._proc.wait(timeout=5)
142 except subprocess.TimeoutExpired:
143 self._proc.kill()
144 self._proc.wait()