-
Notifications
You must be signed in to change notification settings - Fork 109
/
Copy pathcommon.py
729 lines (561 loc) · 19.7 KB
/
common.py
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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
# flake8: NOQA W605
"""Helper methods and mixins.
libtmux.common
~~~~~~~~~~~~~~
"""
import logging
import os
import re
import subprocess
import sys
import typing as t
from collections.abc import MutableMapping
from distutils.version import LooseVersion
from . import exc
from ._compat import console_to_str, str_from_console
logger = logging.getLogger(__name__)
#: Minimum version of tmux required to run libtmux
TMUX_MIN_VERSION = "1.8"
#: Most recent version of tmux supported
TMUX_MAX_VERSION = "2.4"
SessionDict = t.Dict[str, t.Any]
WindowDict = t.Dict[str, t.Any]
PaneDict = t.Dict[str, t.Any]
class EnvironmentMixin:
"""
Mixin class for managing session and server level environment variables in
tmux.
"""
_add_option = None
def __init__(self, add_option=None):
self._add_option = add_option
def set_environment(self, name, value):
"""
Set environment ``$ tmux set-environment <name> <value>``.
Parameters
----------
name : str
the environment variable name. such as 'PATH'.
option : str
environment value.
"""
args = ["set-environment"]
if self._add_option:
args += [self._add_option]
args += [name, value]
proc = self.cmd(*args)
if proc.stderr:
if isinstance(proc.stderr, list) and len(proc.stderr) == 1:
proc.stderr = proc.stderr[0]
raise ValueError("tmux set-environment stderr: %s" % proc.stderr)
def unset_environment(self, name):
"""
Unset environment variable ``$ tmux set-environment -u <name>``.
Parameters
----------
name : str
the environment variable name. such as 'PATH'.
"""
args = ["set-environment"]
if self._add_option:
args += [self._add_option]
args += ["-u", name]
proc = self.cmd(*args)
if proc.stderr:
if isinstance(proc.stderr, list) and len(proc.stderr) == 1:
proc.stderr = proc.stderr[0]
raise ValueError("tmux set-environment stderr: %s" % proc.stderr)
def remove_environment(self, name):
"""Remove environment variable ``$ tmux set-environment -r <name>``.
Parameters
----------
name : str
the environment variable name. such as 'PATH'.
"""
args = ["set-environment"]
if self._add_option:
args += [self._add_option]
args += ["-r", name]
proc = self.cmd(*args)
if proc.stderr:
if isinstance(proc.stderr, list) and len(proc.stderr) == 1:
proc.stderr = proc.stderr[0]
raise ValueError("tmux set-environment stderr: %s" % proc.stderr)
def show_environment(self, name=None):
"""Show environment ``$ tmux show-environment -t [session] <name>``.
Return dict of environment variables for the session or the value of a
specific variable if the name is specified.
Parameters
----------
name : str
the environment variable name. such as 'PATH'.
Returns
-------
str or 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]
if name:
tmux_args += [name]
vars = self.cmd(*tmux_args).stdout
vars = [tuple(item.split("=", 1)) for item in vars]
vars_dict = {}
for t in vars:
if len(t) == 2:
vars_dict[t[0]] = t[1]
elif len(t) == 1:
vars_dict[t[0]] = True
else:
raise ValueError("unexpected variable %s", t)
if name:
return vars_dict.get(name)
return vars_dict
class TmuxCommand:
"""
:term:`tmux(1)` command via :py:mod:`subprocess`.
Parameters
----------
tmux_search_paths : list, optional
Default PATHs to search tmux for, defaults to ``default_paths`` used
in :func:`which`.
append_env_path : bool
Append environment PATHs to tmux search paths. True by default.
Examples
--------
.. code-block:: python
c = tmux_cmd('new-session', '-s%' % 'my session')
# You can actually see the command in the .cmd attribute
print(c.cmd)
proc = c.execute()
if proc.stderr:
raise exc.LibTmuxException(
'Command: %s returned error: %s' % (proc.cmd, proc.stderr)
)
print('tmux command returned %s' % proc.stdout)
Equivalent to:
.. code-block:: bash
$ tmux new-session -s my session
Notes
-----
.. versionadded:: 0.8.4
Wrap to split execution from command from instance of it
"""
def __init__(self, *args, **kwargs):
tmux_bin = which(
"tmux",
default_paths=kwargs.get(
"tmux_search_paths",
["/bin", "/sbin", "/usr/bin", "/usr/sbin", "/usr/local/bin"],
),
append_env_path=kwargs.get("append_env_path", True),
)
if not tmux_bin:
raise (exc.TmuxCommandNotFound)
cmd = [tmux_bin]
cmd += args # add the command arguments to cmd
cmd = [str_from_console(c) for c in cmd]
self.cmd = cmd
def execute(self):
cmd = self.cmd
try:
self.process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
stdout, stderr = self.process.communicate()
returncode = self.process.returncode
except Exception as e:
logger.error(f"Exception for {subprocess.list2cmdline(cmd)}: \n{e}")
self.returncode = returncode
self.stdout = console_to_str(stdout)
self.stdout = self.stdout.split("\n")
self.stdout = list(filter(None, self.stdout)) # filter empty values
self.stderr = console_to_str(stderr)
self.stderr = self.stderr.split("\n")
self.stderr = list(filter(None, self.stderr)) # filter empty values
if "has-session" in cmd and len(self.stderr):
if not self.stdout:
self.stdout = self.stderr[0]
logger.debug("self.stdout for {}: \n{}".format(" ".join(cmd), self.stdout))
return self
def tmux_cmd(*args, **kwargs):
"""Wrapper around TmuxCommand. Executes instantly.
Examples
--------
.. code-block:: python
proc = tmux_cmd('new-session', '-s%' % 'my session')
if proc.stderr:
raise exc.LibTmuxException(
'Command: %s returned error: %s' % (proc.cmd, proc.stderr)
)
print('tmux command returned %s' % proc.stdout)
Equivalent to:
.. code-block:: bash
$ tmux new-session -s my session
Notes
-----
.. versionchanged:: 0.8
Renamed from ``tmux`` to ``tmux_cmd``.
"""
return TmuxCommand(*args, **kwargs).execute()
class TmuxMappingObject(MutableMapping):
r"""Base: :py:class:`MutableMapping`.
Convenience container. Base class for :class:`Pane`, :class:`Window`,
:class:`Session` and :class:`Server`.
Instance attributes for useful information :term:`tmux(1)` uses for
Session, Window, Pane, stored :attr:`self._info`. For example, a
:class:`Window` will have a ``window_id`` and ``window_name``.
================ ================================== ==============
Object formatter_prefix value
================ ================================== ==============
:class:`Server` n/a n/a
:class:`Session` :attr:`Session.formatter_prefix` session\_
:class:`Window` :attr:`Window.formatter_prefix` window\_
:class:`Pane` :attr:`Pane.formatter_prefix` pane\_
================ ================================== ==============
"""
def __getitem__(self, key):
return self._info[key]
def __setitem__(self, key, value):
self._info[key] = value
self.dirty = True
def __delitem__(self, key):
del self._info[key]
self.dirty = True
def keys(self):
"""Return list of keys."""
return self._info.keys()
def __iter__(self):
return self._info.__iter__()
def __len__(self):
return len(self._info.keys())
def __getattr__(self, key):
try:
return self._info[self.formatter_prefix + key]
except KeyError:
raise AttributeError(f"{self.__class__} has no property {key}")
class TmuxRelationalObject:
"""Base Class for managing tmux object child entities. .. # NOQA
Manages collection of child objects (a :class:`Server` has a collection of
:class:`Session` objects, a :class:`Session` has collection of
:class:`Window`)
Children of :class:`TmuxRelationalObject` are going to have a
``self.children``, ``self.child_id_attribute``.
================ ========================= =================================
Object .children method
================ ========================= =================================
:class:`Server` :attr:`Server._sessions` :meth:`Server.list_sessions`
:class:`Session` :attr:`Session._windows` :meth:`Session.list_windows`
:class:`Window` :attr:`Window._panes` :meth:`Window.list_panes`
:class:`Pane` n/a n/a
================ ========================= =================================
================ ================================== ==============
Object child_id_attribute value
================ ================================== ==============
:class:`Server` :attr:`Server.child_id_attribute` session_id
:class:`Session` :attr:`Session.child_id_attribute` window_id
:class:`Window` :attr:`Window.child_id_attribute` pane_id
:class:`Pane` n/a n/a
================ ================================== ==============
"""
def find_where(self, attrs):
"""Return object on first match.
.. versionchanged:: 0.4
Renamed from ``.findWhere`` to ``.find_where``.
"""
try:
return self.where(attrs)[0]
except IndexError:
return None
def where(self, attrs, first=False):
"""
Return objects matching child objects properties.
Parameters
----------
attrs : dict
tmux properties to match values of
Returns
-------
list
"""
# from https://github.com/serkanyersen/underscore.py
def by(val) -> bool:
for key in attrs.keys():
try:
if attrs[key] != val[key]:
return False
except KeyError:
return False
return True
# TODO add type hint
target_children = list(filter(by, self.children))
if first:
return target_children[0]
return target_children
def get_by_id(self, id):
"""
Return object based on ``child_id_attribute``.
Parameters
----------
val : str
Returns
-------
object
Notes
-----
Based on `.get()`_ from `backbone.js`_.
.. _backbone.js: http://backbonejs.org/
.. _.get(): http://backbonejs.org/#Collection-get
"""
for child in self.children:
if child[self.child_id_attribute] == id:
return child
else:
continue
return None
def which(
exe: str,
default_paths: t.List[str] = [
"/bin",
"/sbin",
"/usr/bin",
"/usr/sbin",
"/usr/local/bin",
],
append_env_path: bool = True,
) -> t.Optional[str]:
"""
Return path of bin. Python clone of /usr/bin/which.
Parameters
----------
exe : str
Application to search PATHs for.
default_paths : list
Paths to check inside of
append_env_path : bool, optional
Append list of directories to check in from PATH environment variable.
Default True. Setting False only for testing / diagnosing.
Returns
-------
str
path of application, if found in paths.
Notes
-----
from salt.util - https://www.github.com/saltstack/salt - license apache
"""
def _is_executable_file_or_link(exe: str) -> bool:
# check for os.X_OK doesn't suffice because directory may executable
return os.access(exe, os.X_OK) and (os.path.isfile(exe) or os.path.islink(exe))
if _is_executable_file_or_link(exe):
# executable in cwd or fullpath
return exe
# Enhance POSIX path for the reliability at some environments, when
# $PATH is changing. This also keeps order, where 'first came, first
# win' for cases to find optional alternatives
if append_env_path:
search_path = (
os.environ.get("PATH") and os.environ["PATH"].split(os.pathsep) or list()
)
else:
search_path = []
for default_path in default_paths:
if default_path not in search_path:
search_path.append(default_path)
for path in search_path:
full_path = os.path.join(path, exe)
if _is_executable_file_or_link(full_path):
return full_path
logger.info(
"'{}' could not be found in the following search path: "
"'{}'".format(exe, search_path)
)
return None
def get_version() -> 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``.
Returns
-------
:class:`distutils.version.LooseVersion`
tmux version according to :func:`libtmux.common.which`'s tmux
"""
proc = tmux_cmd("-V")
if proc.stderr:
if proc.stderr[0] == "tmux: unknown option -- V":
if sys.platform.startswith("openbsd"): # openbsd has no tmux -V
return LooseVersion("%s-openbsd" % TMUX_MAX_VERSION)
raise exc.LibTmuxException(
"libtmux supports tmux %s and greater. This system"
" is running tmux 1.3 or earlier." % TMUX_MIN_VERSION
)
raise exc.VersionTooLow(proc.stderr)
version = proc.stdout[0].split("tmux ")[1]
# Allow latest tmux HEAD
if version == "master":
return LooseVersion("%s-master" % TMUX_MAX_VERSION)
version = re.sub(r"[a-z-]", "", version)
return LooseVersion(version)
def has_version(version: str) -> bool:
"""
Return affirmative if tmux version installed.
Parameters
----------
version : str
version number, e.g. '1.8'
Returns
-------
bool
True if version matches
"""
return get_version() == LooseVersion(version)
def has_gt_version(min_version: str) -> bool:
"""
Return affirmative if tmux version greater than minimum.
Parameters
----------
min_version : str
tmux version, e.g. '1.8'
Returns
-------
bool
True if version above min_version
"""
return get_version() > LooseVersion(min_version)
def has_gte_version(min_version: str) -> bool:
"""
Return True if tmux version greater or equal to minimum.
Parameters
----------
min_version : str
tmux version, e.g. '1.8'
Returns
-------
bool
True if version above or equal to min_version
"""
return get_version() >= LooseVersion(min_version)
def has_lte_version(max_version: str) -> bool:
"""
Return True if tmux version less or equal to minimum.
Parameters
----------
max_version : str
tmux version, e.g. '1.8'
Returns
-------
bool
True if version below or equal to max_version
"""
return get_version() <= LooseVersion(max_version)
def has_lt_version(max_version: str) -> bool:
"""
Return True if tmux version less than minimum.
Parameters
----------
max_version : str
tmux version, e.g. '1.8'
Returns
-------
bool
True if version below max_version
"""
return get_version() < LooseVersion(max_version)
def has_minimum_version(raises: bool = True) -> bool:
"""
Return if tmux meets version requirement. Version >1.8 or above.
Parameters
----------
raises : bool
raise exception if below minimum version requirement
Returns
-------
bool
True if tmux meets minimum required version.
Raises
------
libtmux.exc.VersionTooLow
tmux version below minimum required for libtmux
Notes
-----
.. 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`_.
.. _Issue 55: https://github.com/tmux-python/tmuxp/issues/55.
"""
if get_version() < LooseVersion(TMUX_MIN_VERSION):
if raises:
raise exc.VersionTooLow(
"libtmux only supports tmux %s and greater. This system"
" has %s installed. Upgrade your tmux to use libtmux."
% (TMUX_MIN_VERSION, get_version())
)
else:
return False
return True
def session_check_name(session_name: str):
"""
Raises 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 not session_name or len(session_name) == 0:
raise exc.BadSessionName("tmux session names may not be empty.")
elif "." in session_name:
raise exc.BadSessionName(
'tmux session name "%s" may not contain periods.', session_name
)
elif ":" in session_name:
raise exc.BadSessionName(
'tmux session name "%s" may not contain colons.', session_name
)
def handle_option_error(error: str):
"""Raises exception if error in option command found.
In tmux 3.0, show-option and show-window-otion return invalid option instead of
unknown option. See https://github.com/tmux/tmux/blob/3.0/cmd-show-options.c.
In tmux >2.4, there are 3 different types of option errors:
- unknown option
- invalid option
- ambiguous option
In tmux <2.4, unknown option was the only option.
All errors raised will have the base error of :exc:`exc.OptionError`. So to
catch any option error, use ``except exc.OptionError``.
Parameters
----------
error : str
Error response from subprocess call.
Raises
------
:exc:`exc.OptionError`, :exc:`exc.UnknownOption`, :exc:`exc.InvalidOption`,
:exc:`exc.AmbiguousOption`
"""
if "unknown option" in error:
raise exc.UnknownOption(error)
elif "invalid option" in error:
raise exc.InvalidOption(error)
elif "ambiguous option" in error:
raise exc.AmbiguousOption(error)
else:
raise exc.OptionError(error) # Raise generic option error
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__)