-
Notifications
You must be signed in to change notification settings - Fork 117
Expand file tree
/
Copy pathcommon.py
More file actions
535 lines (418 loc) · 14.7 KB
/
common.py
File metadata and controls
535 lines (418 loc) · 14.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
"""Helper methods and mixins for libtmux.
libtmux.common
~~~~~~~~~~~~~~
"""
from __future__ import annotations
import logging
import re
import shlex
import shutil
import subprocess
import sys
import typing as t
from . import exc
from ._compat import LooseVersion
if t.TYPE_CHECKING:
from collections.abc import Callable
logger = logging.getLogger(__name__)
#: Minimum version of tmux required to run libtmux
TMUX_MIN_VERSION = "3.2a"
#: Most recent version of tmux supported
TMUX_MAX_VERSION = "3.6"
SessionDict = dict[str, t.Any]
WindowDict = dict[str, t.Any]
WindowOptionDict = dict[str, t.Any]
PaneDict = dict[str, t.Any]
class CmdProtocol(t.Protocol):
"""Command protocol for tmux command."""
def __call__(self, cmd: str, *args: t.Any, **kwargs: t.Any) -> tmux_cmd:
"""Wrap tmux_cmd."""
...
class CmdMixin:
"""Command mixin for tmux command."""
cmd: CmdProtocol
class EnvironmentMixin:
"""Mixin for manager session and server level environment variables in tmux."""
_add_option = None
cmd: Callable[[t.Any, t.Any], tmux_cmd]
def __init__(self, add_option: str | None = None) -> None:
self._add_option = add_option
def set_environment(self, name: str, value: str) -> None:
"""Set environment ``$ tmux set-environment <name> <value>``.
Parameters
----------
name : str
The environment variable name, e.g. 'PATH'.
value : str
Environment value.
Raises
------
ValueError
If tmux returns an error.
"""
args = ["set-environment"]
if self._add_option:
args += [self._add_option]
args += [name, value]
cmd = self.cmd(*args)
if cmd.stderr:
(
cmd.stderr[0]
if isinstance(cmd.stderr, list) and len(cmd.stderr) == 1
else cmd.stderr
)
msg = f"tmux set-environment stderr: {cmd.stderr}"
raise ValueError(msg)
def unset_environment(self, name: str) -> None:
"""Unset environment variable ``$ tmux set-environment -u <name>``.
Parameters
----------
name : str
The environment variable name, e.g. 'PATH'.
Raises
------
ValueError
If tmux returns an error.
"""
args = ["set-environment"]
if self._add_option:
args += [self._add_option]
args += ["-u", name]
cmd = self.cmd(*args)
if cmd.stderr:
(
cmd.stderr[0]
if isinstance(cmd.stderr, list) and len(cmd.stderr) == 1
else cmd.stderr
)
msg = f"tmux set-environment stderr: {cmd.stderr}"
raise ValueError(msg)
def remove_environment(self, name: str) -> None:
"""Remove environment variable ``$ tmux set-environment -r <name>``.
Parameters
----------
name : str
The environment variable name, e.g. 'PATH'.
Raises
------
ValueError
If tmux returns an error.
"""
args = ["set-environment"]
if self._add_option:
args += [self._add_option]
args += ["-r", name]
cmd = self.cmd(*args)
if cmd.stderr:
(
cmd.stderr[0]
if isinstance(cmd.stderr, list) and len(cmd.stderr) == 1
else cmd.stderr
)
msg = f"tmux set-environment stderr: {cmd.stderr}"
raise ValueError(msg)
def show_environment(self) -> dict[str, bool | str]:
"""Show environment ``$ tmux show-environment -t [session]``.
Return dict of environment variables for the session.
.. versionchanged:: 0.13
Removed per-item lookups. Use :meth:`libtmux.common.EnvironmentMixin.getenv`.
Returns
-------
dict
environmental variables in dict, if no name, or str if name
entered.
"""
tmux_args = ["show-environment"]
if self._add_option:
tmux_args += [self._add_option]
cmd = self.cmd(*tmux_args)
output = cmd.stdout
opts = [tuple(item.split("=", 1)) for item in output]
opts_dict: dict[str, str | bool] = {}
for _t in opts:
if len(_t) == 2:
opts_dict[_t[0]] = _t[1]
elif len(_t) == 1:
opts_dict[_t[0]] = True
else:
raise exc.VariableUnpackingError(variable=_t)
return opts_dict
def getenv(self, name: str) -> str | bool | None:
"""Show environment variable ``$ tmux show-environment -t [session] <name>``.
Return the value of a specific variable if the name is specified.
.. versionadded:: 0.13
Parameters
----------
name : str
the environment variable name. such as 'PATH'.
Returns
-------
str
Value of environment variable
"""
tmux_args: tuple[str | int, ...] = ()
tmux_args += ("show-environment",)
if self._add_option:
tmux_args += (self._add_option,)
tmux_args += (name,)
cmd = self.cmd(*tmux_args)
output = cmd.stdout
opts = [tuple(item.split("=", 1)) for item in output]
opts_dict: dict[str, str | bool] = {}
for _t in opts:
if len(_t) == 2:
opts_dict[_t[0]] = _t[1]
elif len(_t) == 1:
opts_dict[_t[0]] = True
else:
raise exc.VariableUnpackingError(variable=_t)
return opts_dict.get(name)
class tmux_cmd:
"""Run any :term:`tmux(1)` command through :py:mod:`subprocess`.
Examples
--------
Create a new session, check for error:
>>> proc = tmux_cmd(f'-L{server.socket_name}', 'new-session', '-d', '-P', '-F#S')
>>> if proc.stderr:
... raise exc.LibTmuxException(
... 'Command: %s returned error: %s' % (proc.cmd, proc.stderr)
... )
...
>>> print(f'tmux command returned {" ".join(proc.stdout)}')
tmux command returned 2
Equivalent to:
.. code-block:: console
$ tmux new-session -s my session
Notes
-----
.. versionchanged:: 0.8
Renamed from ``tmux`` to ``tmux_cmd``.
"""
def __init__(self, *args: t.Any, tmux_bin: str | None = None) -> None:
resolved = tmux_bin or shutil.which("tmux")
if not resolved:
raise exc.TmuxCommandNotFound
cmd = [resolved]
cmd += args # add the command arguments to cmd
cmd = [str(c) for c in cmd]
self.cmd = cmd
if logger.isEnabledFor(logging.DEBUG):
cmd_str = shlex.join(cmd)
logger.debug(
"tmux command dispatched",
extra={"tmux_cmd": cmd_str},
)
try:
self.process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
errors="backslashreplace",
)
stdout, stderr = self.process.communicate()
returncode = self.process.returncode
except FileNotFoundError:
raise exc.TmuxCommandNotFound from None
except Exception:
logger.error( # noqa: TRY400
"tmux subprocess failed",
extra={
"tmux_cmd": shlex.join(cmd),
},
)
raise
self.returncode = returncode
stdout_split = stdout.split("\n")
# remove trailing newlines from stdout
while stdout_split and stdout_split[-1] == "":
stdout_split.pop()
stderr_split = stderr.split("\n")
self.stderr = list(filter(None, stderr_split)) # filter empty values
if "has-session" in cmd and len(self.stderr) and not stdout_split:
self.stdout = [self.stderr[0]]
else:
self.stdout = stdout_split
if logger.isEnabledFor(logging.DEBUG):
logger.debug(
"tmux command completed",
extra={
"tmux_cmd": shlex.join(cmd),
"tmux_exit_code": self.returncode,
"tmux_stdout": self.stdout[:100],
"tmux_stderr": self.stderr[:100],
"tmux_stdout_len": len(self.stdout),
"tmux_stderr_len": len(self.stderr),
},
)
def get_version(tmux_bin: str | None = None) -> LooseVersion:
"""Return tmux version.
If tmux is built from git master, the version returned will be the latest
version appended with -master, e.g. ``2.4-master``.
If using OpenBSD's base system tmux, the version will have ``-openbsd``
appended to the latest version, e.g. ``2.4-openbsd``.
Parameters
----------
tmux_bin : str, optional
Path to tmux binary. If *None*, uses the system tmux from
:func:`shutil.which`.
Returns
-------
:class:`distutils.version.LooseVersion`
tmux version according to *tmux_bin* if provided, otherwise the
system tmux from :func:`shutil.which`
"""
proc = tmux_cmd("-V", tmux_bin=tmux_bin)
if proc.stderr:
if proc.stderr[0] == "tmux: unknown option -- V":
if sys.platform.startswith("openbsd"): # openbsd has no tmux -V
return LooseVersion(f"{TMUX_MAX_VERSION}-openbsd")
msg = (
f"libtmux supports tmux {TMUX_MIN_VERSION} and greater. This system"
" does not meet the minimum tmux version requirement."
)
raise exc.LibTmuxException(
msg,
)
raise exc.VersionTooLow(proc.stderr)
version = proc.stdout[0].split("tmux ")[1]
# Allow latest tmux HEAD
if version == "master":
return LooseVersion(f"{TMUX_MAX_VERSION}-master")
version = re.sub(r"[a-z-]", "", version)
return LooseVersion(version)
def has_version(version: str, tmux_bin: str | None = None) -> bool:
"""Return True if tmux version installed.
Parameters
----------
version : str
version number, e.g. '3.2a'
tmux_bin : str, optional
Path to tmux binary. If *None*, uses the system tmux.
Returns
-------
bool
True if version matches
"""
return get_version(tmux_bin=tmux_bin) == LooseVersion(version)
def has_gt_version(min_version: str, tmux_bin: str | None = None) -> bool:
"""Return True if tmux version greater than minimum.
Parameters
----------
min_version : str
tmux version, e.g. '3.2a'
tmux_bin : str, optional
Path to tmux binary. If *None*, uses the system tmux.
Returns
-------
bool
True if version above min_version
"""
return get_version(tmux_bin=tmux_bin) > LooseVersion(min_version)
def has_gte_version(min_version: str, tmux_bin: str | None = None) -> bool:
"""Return True if tmux version greater or equal to minimum.
Parameters
----------
min_version : str
tmux version, e.g. '3.2a'
tmux_bin : str, optional
Path to tmux binary. If *None*, uses the system tmux.
Returns
-------
bool
True if version above or equal to min_version
"""
return get_version(tmux_bin=tmux_bin) >= LooseVersion(min_version)
def has_lte_version(max_version: str, tmux_bin: str | None = None) -> bool:
"""Return True if tmux version less or equal to minimum.
Parameters
----------
max_version : str
tmux version, e.g. '3.2a'
tmux_bin : str, optional
Path to tmux binary. If *None*, uses the system tmux.
Returns
-------
bool
True if version below or equal to max_version
"""
return get_version(tmux_bin=tmux_bin) <= LooseVersion(max_version)
def has_lt_version(max_version: str, tmux_bin: str | None = None) -> bool:
"""Return True if tmux version less than minimum.
Parameters
----------
max_version : str
tmux version, e.g. '3.2a'
tmux_bin : str, optional
Path to tmux binary. If *None*, uses the system tmux.
Returns
-------
bool
True if version below max_version
"""
return get_version(tmux_bin=tmux_bin) < LooseVersion(max_version)
def has_minimum_version(raises: bool = True, tmux_bin: str | None = None) -> bool:
"""Return True if tmux meets version requirement. Version >= 3.2a.
Parameters
----------
raises : bool
raise exception if below minimum version requirement
tmux_bin : str, optional
Path to tmux binary. If *None*, uses the system tmux.
Returns
-------
bool
True if tmux meets minimum required version.
Raises
------
libtmux.exc.VersionTooLow
tmux version below minimum required for libtmux
Notes
-----
.. versionchanged:: 0.49.0
Minimum version bumped to 3.2a. For older tmux, use libtmux v0.48.x.
.. versionchanged:: 0.7.0
No longer returns version, returns True or False
.. versionchanged:: 0.1.7
Versions will now remove trailing letters per
`Issue 55 <https://github.com/tmux-python/tmuxp/issues/55>`_.
"""
current_version = get_version(tmux_bin=tmux_bin)
if current_version < LooseVersion(TMUX_MIN_VERSION):
if raises:
msg = (
f"libtmux only supports tmux {TMUX_MIN_VERSION} and greater. This "
f"system has {current_version} installed. Upgrade your "
"tmux to use libtmux, or use libtmux v0.48.x for older tmux versions."
)
raise exc.VersionTooLow(msg)
return False
return True
def session_check_name(session_name: str | None) -> None:
"""Raise exception session name invalid, modeled after tmux function.
tmux(1) session names may not be empty, or include periods or colons.
These delimiters are reserved for noting session, window and pane.
Parameters
----------
session_name : str
Name of session.
Raises
------
:exc:`exc.BadSessionName`
Invalid session name.
"""
if session_name is None or len(session_name) == 0:
raise exc.BadSessionName(reason="empty", session_name=session_name)
if "." in session_name:
raise exc.BadSessionName(reason="contains periods", session_name=session_name)
if ":" in session_name:
raise exc.BadSessionName(reason="contains colons", session_name=session_name)
def get_libtmux_version() -> LooseVersion:
"""Return libtmux version is a PEP386 compliant format.
Returns
-------
distutils.version.LooseVersion
libtmux version
"""
from libtmux.__about__ import __version__
return LooseVersion(__version__)