Debian Codegraph @

src/libtmux/common.py

raw symbols SCIP
1 """Helper methods and mixins for libtmux.
2
3 libtmux.common
4 ~~~~~~~~~~~~~~
5
6 """
7
8 from __future__ import annotations
9
10 import functools
11 import logging
12 import re
13 import shlex
14 import shutil
15 import subprocess
16 import sys
17 import typing as t
18
19 from . import exc
20 from ._compat import LooseVersion
21
22 if t.TYPE_CHECKING:
23 from collections.abc import Callable
24
25 logger = logging.getLogger(__name__)
26
27
28 #: Minimum version of tmux required to run libtmux
29 TMUX_MIN_VERSION = "3.2a"
30
31 #: Most recent version of tmux supported
32 TMUX_MAX_VERSION = "3.7"
33
34 SessionDict = dict[str, t.Any]
35 WindowDict = dict[str, t.Any]
36 WindowOptionDict = dict[str, t.Any]
37 PaneDict = dict[str, t.Any]
38
39
40 class CmdProtocol(t.Protocol):
41 """Command protocol for tmux command."""
42
43 def __call__(self, cmd: str, *args: t.Any, **kwargs: t.Any) -> tmux_cmd:
44 """Wrap tmux_cmd."""
45 ...
46
47
48 class CmdMixin:
49 """Command mixin for tmux command."""
50
51 cmd: CmdProtocol
52
53
54 class EnvironmentMixin:
55 """Mixin for manager session and server level environment variables in tmux."""
56
57 _add_option = None
58
59 cmd: Callable[[t.Any, t.Any], tmux_cmd]
60
61 def __init__(self, add_option: str | None = None) -> None:
62 self._add_option = add_option
63
64 def set_environment(
65 self,
66 name: str,
67 value: str,
68 *,
69 expand_format: bool | None = None,
70 hidden: bool | None = None,
71 ) -> None:
72 """Set environment ``$ tmux set-environment <name> <value>``.
73
74 Parameters
75 ----------
76 name : str
77 The environment variable name, e.g. 'PATH'.
78 value : str
79 Environment value.
80 expand_format : bool, optional
81 Expand tmux format strings in the value (``-F`` flag).
82
83 .. versionadded:: 0.56
84 hidden : bool, optional
85 Mark the variable as hidden (``-h`` flag).
86
87 .. versionadded:: 0.56
88
89 Raises
90 ------
91 ValueError
92 If tmux returns an error.
93 """
94 args = ["set-environment"]
95 if self._add_option:
96 args += [self._add_option]
97
98 if expand_format:
99 args += ["-F"]
100
101 if hidden:
102 args += ["-h"]
103
104 args += [name, value]
105
106 cmd = self.cmd(*args)
107
108 if cmd.stderr:
109 (
110 cmd.stderr[0]
111 if isinstance(cmd.stderr, list) and len(cmd.stderr) == 1
112 else cmd.stderr
113 )
114 msg = f"tmux set-environment stderr: {cmd.stderr}"
115 raise ValueError(msg)
116
117 def unset_environment(self, name: str) -> None:
118 """Unset environment variable ``$ tmux set-environment -u <name>``.
119
120 Parameters
121 ----------
122 name : str
123 The environment variable name, e.g. 'PATH'.
124
125 Raises
126 ------
127 ValueError
128 If tmux returns an error.
129 """
130 args = ["set-environment"]
131 if self._add_option:
132 args += [self._add_option]
133 args += ["-u", name]
134
135 cmd = self.cmd(*args)
136
137 if cmd.stderr:
138 (
139 cmd.stderr[0]
140 if isinstance(cmd.stderr, list) and len(cmd.stderr) == 1
141 else cmd.stderr
142 )
143 msg = f"tmux set-environment stderr: {cmd.stderr}"
144 raise ValueError(msg)
145
146 def remove_environment(self, name: str) -> None:
147 """Remove environment variable ``$ tmux set-environment -r <name>``.
148
149 Parameters
150 ----------
151 name : str
152 The environment variable name, e.g. 'PATH'.
153
154 Raises
155 ------
156 ValueError
157 If tmux returns an error.
158 """
159 args = ["set-environment"]
160 if self._add_option:
161 args += [self._add_option]
162 args += ["-r", name]
163
164 cmd = self.cmd(*args)
165
166 if cmd.stderr:
167 (
168 cmd.stderr[0]
169 if isinstance(cmd.stderr, list) and len(cmd.stderr) == 1
170 else cmd.stderr
171 )
172 msg = f"tmux set-environment stderr: {cmd.stderr}"
173 raise ValueError(msg)
174
175 def show_environment(self) -> dict[str, bool | str]:
176 """Show environment ``$ tmux show-environment -t [session]``.
177
178 Return dict of environment variables for the session.
179
180 .. versionchanged:: 0.13
181
182 Removed per-item lookups. Use :meth:`libtmux.common.EnvironmentMixin.getenv`.
183
184 Returns
185 -------
186 dict
187 environmental variables in dict, if no name, or str if name
188 entered.
189 """
190 tmux_args = ["show-environment"]
191 if self._add_option:
192 tmux_args += [self._add_option]
193 cmd = self.cmd(*tmux_args)
194 output = cmd.stdout
195 opts = [tuple(item.split("=", 1)) for item in output]
196 opts_dict: dict[str, str | bool] = {}
197 for _t in opts:
198 if len(_t) == 2:
199 opts_dict[_t[0]] = _t[1]
200 elif len(_t) == 1:
201 opts_dict[_t[0]] = True
202 else:
203 raise exc.VariableUnpackingError(variable=_t)
204
205 return opts_dict
206
207 def getenv(self, name: str) -> str | bool | None:
208 """Show environment variable ``$ tmux show-environment -t [session] <name>``.
209
210 Return the value of a specific variable if the name is specified.
211
212 .. versionadded:: 0.13
213
214 Parameters
215 ----------
216 name : str
217 the environment variable name. such as 'PATH'.
218
219 Returns
220 -------
221 str
222 Value of environment variable
223 """
224 tmux_args: tuple[str | int, ...] = ()
225
226 tmux_args += ("show-environment",)
227 if self._add_option:
228 tmux_args += (self._add_option,)
229 tmux_args += (name,)
230 cmd = self.cmd(*tmux_args)
231 output = cmd.stdout
232 opts = [tuple(item.split("=", 1)) for item in output]
233 opts_dict: dict[str, str | bool] = {}
234 for _t in opts:
235 if len(_t) == 2:
236 opts_dict[_t[0]] = _t[1]
237 elif len(_t) == 1:
238 opts_dict[_t[0]] = True
239 else:
240 raise exc.VariableUnpackingError(variable=_t)
241
242 return opts_dict.get(name)
243
244
245 def raise_if_stderr(proc: tmux_cmd, subcommand: str) -> None:
246 """Raise :exc:`LibTmuxException` tagged with the tmux subcommand on stderr.
247
248 Centralizes the ``if proc.stderr: raise exc.LibTmuxException(proc.stderr)``
249 pattern scattered across the wrappers. Tags the exception with the
250 originating tmux subcommand so downstream consumers (e.g. libtmux-mcp's
251 ``handle_tool_errors``) keep the "which tmux command failed" context.
252
253 Parameters
254 ----------
255 proc : :class:`tmux_cmd`
256 Result of a :meth:`Server.cmd` / :meth:`Session.cmd` / etc. call.
257 subcommand : str
258 The tmux subcommand the wrapper invoked, e.g. ``"last-window"``,
259 ``"swap-pane"``. Surfaces in ``str(exc)`` as a ``"<subcommand>: …"``
260 prefix.
261
262 Raises
263 ------
264 :exc:`LibTmuxException`
265 When ``proc.stderr`` is non-empty.
266
267 Examples
268 --------
269 >>> from libtmux.common import raise_if_stderr
270 >>> from libtmux import exc
271 >>> proc = session.cmd("display-message", "-p", "#{session_id}")
272 >>> raise_if_stderr(proc, "display-message") # no stderr → no raise
273
274 .. versionadded:: 0.57
275 """
276 if proc.stderr:
277 raise exc.LibTmuxException(
278 "\n".join(proc.stderr),
279 subcommand=subcommand,
280 )
281
282
283 class tmux_cmd:
284 """Run any :term:`tmux(1)` command through :py:mod:`subprocess`.
285
286 Examples
287 --------
288 Create a new session, check for error:
289
290 >>> proc = tmux_cmd(f'-L{server.socket_name}', 'new-session', '-d', '-P', '-F#S')
291 >>> if proc.stderr:
292 ... raise exc.LibTmuxException(
293 ... 'Command: %s returned error: %s' % (proc.cmd, proc.stderr)
294 ... )
295 ...
296
297 >>> print(f'tmux command returned {" ".join(proc.stdout)}')
298 tmux command returned 2
299
300 Equivalent to:
301
302 .. code-block:: console
303
304 $ tmux new-session -s my session
305
306 Notes
307 -----
308 .. versionchanged:: 0.8
309 Renamed from ``tmux`` to ``tmux_cmd``.
310 """
311
312 def __init__(self, *args: t.Any, tmux_bin: str | None = None) -> None:
313 resolved = tmux_bin or shutil.which("tmux")
314 if not resolved:
315 raise exc.TmuxCommandNotFound
316
317 cmd = [resolved]
318 cmd += args # add the command arguments to cmd
319 cmd = [str(c) for c in cmd]
320
321 self.cmd = cmd
322
323 if logger.isEnabledFor(logging.DEBUG):
324 cmd_str = shlex.join(cmd)
325 logger.debug(
326 "tmux command dispatched",
327 extra={"tmux_cmd": cmd_str},
328 )
329
330 try:
331 self.process = subprocess.Popen(
332 cmd,
333 stdout=subprocess.PIPE,
334 stderr=subprocess.PIPE,
335 text=True,
336 encoding="utf-8",
337 errors="backslashreplace",
338 )
339 stdout, stderr = self.process.communicate()
340 returncode = self.process.returncode
341 except FileNotFoundError:
342 raise exc.TmuxCommandNotFound from None
343 except Exception:
344 logger.error( # noqa: TRY400
345 "tmux subprocess failed",
346 extra={
347 "tmux_cmd": shlex.join(cmd),
348 },
349 )
350 raise
351
352 self.returncode = returncode
353
354 stdout_split = stdout.split("\n")
355 # remove trailing newlines from stdout
356 while stdout_split and stdout_split[-1] == "":
357 stdout_split.pop()
358
359 stderr_split = stderr.split("\n")
360 self.stderr = list(filter(None, stderr_split)) # filter empty values
361
362 if "has-session" in cmd and len(self.stderr) and not stdout_split:
363 self.stdout = [self.stderr[0]]
364 else:
365 self.stdout = stdout_split
366
367 if logger.isEnabledFor(logging.DEBUG):
368 logger.debug(
369 "tmux command completed",
370 extra={
371 "tmux_cmd": shlex.join(cmd),
372 "tmux_exit_code": self.returncode,
373 "tmux_stdout": self.stdout[:100],
374 "tmux_stderr": self.stderr[:100],
375 "tmux_stdout_len": len(self.stdout),
376 "tmux_stderr_len": len(self.stderr),
377 },
378 )
379
380
381 class _TmuxVersionUnavailable(Exception):
382 """Internal signal: this tmux predates the ``-V`` flag (pre-1.7)."""
383
384
385 def _no_version_flag_fallback() -> str:
386 """Return a synthetic version string when tmux lacks ``-V``.
387
388 OpenBSD ships a ``-V``-less base tmux, so assume the maximum supported
389 version; any other platform is genuinely too old.
390 """
391 if sys.platform.startswith("openbsd"): # openbsd has no tmux -V
392 return f"{TMUX_MAX_VERSION}-openbsd"
393 msg = (
394 f"libtmux supports tmux {TMUX_MIN_VERSION} and greater. This system"
395 " does not meet the minimum tmux version requirement."
396 )
397 raise exc.LibTmuxException(msg)
398
399
400 def _query_version(tmux_bin: str | None = None) -> str:
401 """Return the raw ``tmux -V`` version token, letter suffix intact.
402
403 Runs ``tmux -V`` and extracts the version token (e.g. ``"3.7a"``,
404 ``"master"``, ``"next-3.8"``). Not memoized -- :func:`get_version` and
405 :func:`get_version_str` each cache their own result on top of this query.
406
407 Parameters
408 ----------
409 tmux_bin : str, optional
410 Path to tmux binary. If *None*, uses the system tmux.
411
412 Returns
413 -------
414 str
415 Raw version token from ``tmux -V``.
416
417 Raises
418 ------
419 _TmuxVersionUnavailable
420 tmux predates the ``-V`` flag; callers apply
421 :func:`_no_version_flag_fallback`.
422 :exc:`~libtmux.exc.VersionTooLow`
423 tmux reported another error on ``-V``.
424 """
425 proc = tmux_cmd("-V", tmux_bin=tmux_bin)
426 if proc.stderr:
427 if proc.stderr[0] == "tmux: unknown option -- V":
428 raise _TmuxVersionUnavailable
429 raise exc.VersionTooLow(proc.stderr)
430
431 return proc.stdout[0].split("tmux ")[1]
432
433
434 @functools.cache
435 def get_version_str(tmux_bin: str | None = None) -> str:
436 """Return the tmux version string verbatim, preserving letter suffixes.
437
438 :func:`get_version` normalizes point releases for numeric comparison
439 (``"3.7a"`` becomes ``LooseVersion("3.7")``). This helper keeps the raw
440 suffix, so callers can distinguish patch releases whose behavior differs
441 -- for example the tmux 3.7 break-pane crash, reverted in 3.7a.
442
443 Parameters
444 ----------
445 tmux_bin : str, optional
446 Path to tmux binary. If *None*, uses the system tmux.
447
448 Returns
449 -------
450 str
451 Raw tmux version, e.g. ``"3.7a"``. Git builds return ``"master"``;
452 OpenBSD base tmux returns ``"<max>-openbsd"``.
453
454 Examples
455 --------
456 >>> isinstance(get_version_str(), str)
457 True
458
459 Notes
460 -----
461 Memoized via :func:`functools.cache`, keyed on *tmux_bin*, independently of
462 :func:`get_version`. Call ``get_version_str.cache_clear()`` after swapping
463 the tmux binary.
464 """
465 try:
466 return _query_version(tmux_bin=tmux_bin)
467 except _TmuxVersionUnavailable:
468 return _no_version_flag_fallback()
469
470
471 @functools.cache
472 def get_version(tmux_bin: str | None = None) -> LooseVersion:
473 """Return tmux version.
474
475 If tmux is built from git master, the version returned will be the latest
476 version appended with -master, e.g. ``2.4-master``.
477
478 If using OpenBSD's base system tmux, the version will have ``-openbsd``
479 appended to the latest version, e.g. ``2.4-openbsd``.
480
481 Parameters
482 ----------
483 tmux_bin : str, optional
484 Path to tmux binary. If *None*, uses the system tmux from
485 :func:`shutil.which`.
486
487 Returns
488 -------
489 :class:`distutils.version.LooseVersion`
490 tmux version according to *tmux_bin* if provided, otherwise the
491 system tmux from :func:`shutil.which`
492
493 Notes
494 -----
495 Memoized via :func:`functools.cache`, keyed on the *tmux_bin* argument
496 (``None`` is a distinct key from any explicit path), independently of
497 :func:`get_version_str`. The cache is sticky across ``PATH`` changes and
498 on-disk binary swaps when *tmux_bin* is ``None`` or the same path string --
499 call ``get_version.cache_clear()`` to invalidate. Tests that monkey-patch
500 :class:`tmux_cmd` should call ``cache_clear()`` before asserting
501 parsed-version behavior.
502 """
503 try:
504 version = _query_version(tmux_bin=tmux_bin)
505 except _TmuxVersionUnavailable:
506 # OpenBSD base tmux lacks ``-V``; skip letter-stripping on the synthetic.
507 return LooseVersion(_no_version_flag_fallback())
508
509 # Allow latest tmux HEAD
510 if version == "master":
511 return LooseVersion(f"{TMUX_MAX_VERSION}-master")
512
513 version = re.sub(r"[a-z-]", "", version)
514
515 return LooseVersion(version)
516
517
518 def has_version(version: str, tmux_bin: str | None = None) -> bool:
519 """Return True if tmux version installed.
520
521 Parameters
522 ----------
523 version : str
524 version number, e.g. '3.2a'
525 tmux_bin : str, optional
526 Path to tmux binary. If *None*, uses the system tmux.
527
528 Returns
529 -------
530 bool
531 True if version matches
532 """
533 return get_version(tmux_bin=tmux_bin) == LooseVersion(version)
534
535
536 def has_gt_version(min_version: str, tmux_bin: str | None = None) -> bool:
537 """Return True if tmux version greater than minimum.
538
539 Parameters
540 ----------
541 min_version : str
542 tmux version, e.g. '3.2a'
543 tmux_bin : str, optional
544 Path to tmux binary. If *None*, uses the system tmux.
545
546 Returns
547 -------
548 bool
549 True if version above min_version
550 """
551 return get_version(tmux_bin=tmux_bin) > LooseVersion(min_version)
552
553
554 def has_gte_version(min_version: str, tmux_bin: str | None = None) -> bool:
555 """Return True if tmux version greater or equal to minimum.
556
557 Parameters
558 ----------
559 min_version : str
560 tmux version, e.g. '3.2a'
561 tmux_bin : str, optional
562 Path to tmux binary. If *None*, uses the system tmux.
563
564 Returns
565 -------
566 bool
567 True if version above or equal to min_version
568 """
569 return get_version(tmux_bin=tmux_bin) >= LooseVersion(min_version)
570
571
572 def has_lte_version(max_version: str, tmux_bin: str | None = None) -> bool:
573 """Return True if tmux version less or equal to minimum.
574
575 Parameters
576 ----------
577 max_version : str
578 tmux version, e.g. '3.2a'
579 tmux_bin : str, optional
580 Path to tmux binary. If *None*, uses the system tmux.
581
582 Returns
583 -------
584 bool
585 True if version below or equal to max_version
586 """
587 return get_version(tmux_bin=tmux_bin) <= LooseVersion(max_version)
588
589
590 def has_lt_version(max_version: str, tmux_bin: str | None = None) -> bool:
591 """Return True if tmux version less than minimum.
592
593 Parameters
594 ----------
595 max_version : str
596 tmux version, e.g. '3.2a'
597 tmux_bin : str, optional
598 Path to tmux binary. If *None*, uses the system tmux.
599
600 Returns
601 -------
602 bool
603 True if version below max_version
604 """
605 return get_version(tmux_bin=tmux_bin) < LooseVersion(max_version)
606
607
608 def has_minimum_version(raises: bool = True, tmux_bin: str | None = None) -> bool:
609 """Return True if tmux meets version requirement. Version >= 3.2a.
610
611 Parameters
612 ----------
613 raises : bool
614 raise exception if below minimum version requirement
615 tmux_bin : str, optional
616 Path to tmux binary. If *None*, uses the system tmux.
617
618 Returns
619 -------
620 bool
621 True if tmux meets minimum required version.
622
623 Raises
624 ------
625 libtmux.exc.VersionTooLow
626 tmux version below minimum required for libtmux
627
628 Notes
629 -----
630 .. versionchanged:: 0.49.0
631 Minimum version bumped to 3.2a. For older tmux, use libtmux v0.48.x.
632
633 .. versionchanged:: 0.7.0
634 No longer returns version, returns True or False
635
636 .. versionchanged:: 0.1.7
637 Versions will now remove trailing letters per
638 `Issue 55 <https://github.com/tmux-python/tmuxp/issues/55>`_.
639 """
640 current_version = get_version(tmux_bin=tmux_bin)
641 if current_version < LooseVersion(TMUX_MIN_VERSION):
642 if raises:
643 msg = (
644 f"libtmux only supports tmux {TMUX_MIN_VERSION} and greater. This "
645 f"system has {current_version} installed. Upgrade your "
646 "tmux to use libtmux, or use libtmux v0.48.x for older tmux versions."
647 )
648 raise exc.VersionTooLow(msg)
649 return False
650 return True
651
652
653 def session_check_name(session_name: str | None) -> None:
654 """Raise exception session name invalid, modeled after tmux function.
655
656 tmux(1) session names may not be empty, or include periods or colons.
657 These delimiters are reserved for noting session, window and pane.
658
659 Parameters
660 ----------
661 session_name : str
662 Name of session.
663
664 Raises
665 ------
666 :exc:`exc.BadSessionName`
667 Invalid session name.
668 """
669 if session_name is None or len(session_name) == 0:
670 raise exc.BadSessionName(reason="empty", session_name=session_name)
671 if "." in session_name:
672 raise exc.BadSessionName(reason="contains periods", session_name=session_name)
673 if ":" in session_name:
674 raise exc.BadSessionName(reason="contains colons", session_name=session_name)
675
676
677 def get_libtmux_version() -> LooseVersion:
678 """Return libtmux version is a PEP386 compliant format.
679
680 Returns
681 -------
682 distutils.version.LooseVersion
683 libtmux version
684 """
685 from libtmux.__about__ import __version__
686
687 return LooseVersion(__version__)