From 0b7a11ec2692be97d90e9567f036466d081ee77e Mon Sep 17 00:00:00 2001 From: rockandska Date: Sun, 28 Aug 2022 20:52:56 +0200 Subject: [PATCH 1/4] fix(tmux_cmd): use shutil.which and only PATH to discover tmux --- libtmux/common.py | 85 ++------------------------------------------ libtmux/conftest.py | 4 +-- tests/test_common.py | 17 ++++----- 3 files changed, 11 insertions(+), 95 deletions(-) diff --git a/libtmux/common.py b/libtmux/common.py index 3c4337caa..12a4caeee 100644 --- a/libtmux/common.py +++ b/libtmux/common.py @@ -8,6 +8,7 @@ import logging import os import re +import shutil import subprocess import sys import typing as t @@ -203,14 +204,6 @@ class tmux_cmd: """ :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 -------- @@ -239,14 +232,7 @@ class tmux_cmd: """ def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: - 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), - ) + tmux_bin = shutil.which("tmux") if not tmux_bin: raise (exc.TmuxCommandNotFound) @@ -461,73 +447,6 @@ def get_by_id(self, id: str) -> Optional[O]: 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. diff --git a/libtmux/conftest.py b/libtmux/conftest.py index 324fd2c6a..8f82f69c6 100644 --- a/libtmux/conftest.py +++ b/libtmux/conftest.py @@ -1,6 +1,7 @@ import logging import os import typing as t +import shutil import pytest @@ -9,7 +10,6 @@ from _pytest.monkeypatch import MonkeyPatch from libtmux import exc -from libtmux.common import which from libtmux.server import Server from libtmux.test import TEST_SESSION_PREFIX, get_test_session_name, namer @@ -109,7 +109,7 @@ def add_doctest_fixtures( request: SubRequest, doctest_namespace: t.Dict[str, t.Any], ) -> None: - if isinstance(request._pyfuncitem, DoctestItem) and which("tmux"): + if isinstance(request._pyfuncitem, DoctestItem) and shutil.which("tmux"): doctest_namespace["server"] = request.getfixturevalue("server") session: "Session" = request.getfixturevalue("session") doctest_namespace["session"] = session diff --git a/tests/test_common.py b/tests/test_common.py index f3d4920ea..34e3335b7 100644 --- a/tests/test_common.py +++ b/tests/test_common.py @@ -2,6 +2,7 @@ import re import sys +import os import typing as t from distutils.version import LooseVersion from typing import Optional @@ -23,8 +24,7 @@ has_minimum_version, has_version, session_check_name, - tmux_cmd, - which, + tmux_cmd ) from libtmux.exc import BadSessionName, LibTmuxException, TmuxCommandNotFound from libtmux.session import Session @@ -174,16 +174,13 @@ def test_has_lte_version() -> None: assert not has_lte_version("1.7b") -def test_which_no_bin_found() -> None: - assert which("top") - assert which("top", default_paths=[]) - assert not which("top", default_paths=[], append_env_path=False) - assert not which("top", default_paths=["/"], append_env_path=False) - - def test_tmux_cmd_raises_on_not_found() -> None: + previous_path = os.environ["PATH"] + os.environ["PATH"] = "" with pytest.raises(TmuxCommandNotFound): - tmux_cmd("-V", tmux_search_paths=[], append_env_path=False) + tmux_cmd("-V") + + os.environ["PATH"] = previous_path tmux_cmd("-V") From 9b0f340f5506708aa45a0faec47555dbf5a46191 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 28 Aug 2022 14:27:17 -0500 Subject: [PATCH 2/4] test(test_tmux_cmd_raises_on_not_found): Use monkeypatch --- tests/test_common.py | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/tests/test_common.py b/tests/test_common.py index 34e3335b7..14c5c39a5 100644 --- a/tests/test_common.py +++ b/tests/test_common.py @@ -2,7 +2,6 @@ import re import sys -import os import typing as t from distutils.version import LooseVersion from typing import Optional @@ -24,7 +23,7 @@ has_minimum_version, has_version, session_check_name, - tmux_cmd + tmux_cmd, ) from libtmux.exc import BadSessionName, LibTmuxException, TmuxCommandNotFound from libtmux.session import Session @@ -174,16 +173,11 @@ def test_has_lte_version() -> None: assert not has_lte_version("1.7b") -def test_tmux_cmd_raises_on_not_found() -> None: - previous_path = os.environ["PATH"] - os.environ["PATH"] = "" +def test_tmux_cmd_raises_on_not_found(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("PATH", "") with pytest.raises(TmuxCommandNotFound): tmux_cmd("-V") - os.environ["PATH"] = previous_path - - tmux_cmd("-V") - def test_tmux_cmd_unicode(session: Session) -> None: session.cmd("new-window", "-t", 3, "-n", "юникод", "-F", "Ελληνικά") From c9da2e41b4f56a8f484d81b914d103bf02673147 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 28 Aug 2022 14:32:44 -0500 Subject: [PATCH 3/4] docs(CHANGES): Note deprecation of which() --- CHANGES | 2 ++ 1 file changed, 2 insertions(+) diff --git a/CHANGES b/CHANGES index b8f51b2c2..8cb7b271c 100644 --- a/CHANGES +++ b/CHANGES @@ -14,6 +14,8 @@ $ pip install --user --upgrade --pre libtmux ### Breaking changes +- Remove `common.which()` in favor of {func}`shutil.which`, Credit: + @rocksandska, via #407 - Fixes #402: {func}`common.tmux_cmd` will only strip _trailing_ empty lines. Before this change, all empty lines were filtered out. This will lead to a more accurate behavior when using {meth}`Pane.capture_pane`. Credit: @rockandska, via #405. From 7643b43e555390fd51255193d6e28ac00c952db9 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sun, 28 Aug 2022 15:23:28 -0500 Subject: [PATCH 4/4] doc(get_version): Note which() update --- libtmux/common.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libtmux/common.py b/libtmux/common.py index 12a4caeee..b3db8344b 100644 --- a/libtmux/common.py +++ b/libtmux/common.py @@ -460,7 +460,7 @@ def get_version() -> LooseVersion: Returns ------- :class:`distutils.version.LooseVersion` - tmux version according to :func:`libtmux.common.which`'s tmux + tmux version according to :func:`shtuil.which`'s tmux """ proc = tmux_cmd("-V") if proc.stderr: