Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Linting: Aggressive ruff pass (ruff v0.3.4) #539

Merged
merged 3 commits into from
Mar 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,25 @@ $ pip install --user --upgrade --pre libtmux

<!-- To maintainers and contributors: Please add notes for the forthcoming version above -->

### Development

- Aggressive automated lint fixes via `ruff` (#539)

via ruff v0.3.4, all automated lint fixes, including unsafe and previews were applied:

```sh
ruff check --select ALL . --fix --unsafe-fixes --preview --show-fixes; ruff format .
```

Branches were treated with:

```sh
git rebase \
--strategy-option=theirs \
--exec 'poetry run ruff check --select ALL . --fix --unsafe-fixes --preview --show-fixes; poetry run ruff format .; git add src tests; git commit --amend --no-edit' \
origin/master
```

## libtmux 0.35.1 (2024-03-23)

### Bug fix
Expand Down
8 changes: 2 additions & 6 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,6 @@
from libtmux.session import Session
from libtmux.window import Window

if t.TYPE_CHECKING:
from libtmux.session import Session

pytest_plugins = ["pytester"]


Expand All @@ -47,7 +44,7 @@ def add_doctest_fixtures(
doctest_namespace["request"] = request


@pytest.fixture(autouse=True, scope="function")
@pytest.fixture(autouse=True)
def set_home(
monkeypatch: pytest.MonkeyPatch,
user_path: pathlib.Path,
Expand All @@ -56,12 +53,11 @@ def set_home(
monkeypatch.setenv("HOME", str(user_path))


@pytest.fixture(autouse=True, scope="function")
@pytest.fixture(autouse=True)
def setup_fn(
clear_env: None,
) -> None:
"""Function-level test configuration fixtures for pytest."""
pass


@pytest.fixture(autouse=True, scope="session")
Expand Down
17 changes: 8 additions & 9 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -197,15 +197,14 @@ def linkcode_resolve(domain: str, info: t.Dict[str, str]) -> t.Union[None, str]:
fn,
linespec,
)
else:
return "{}/blob/v{}/{}/{}/{}{}".format(
about["__github__"],
about["__version__"],
"src",
about["__package_name__"],
fn,
linespec,
)
return "{}/blob/v{}/{}/{}/{}{}".format(
about["__github__"],
about["__version__"],
"src",
about["__package_name__"],
fn,
linespec,
)


def remove_tabs_js(app: "Sphinx", exc: Exception) -> None:
Expand Down
28 changes: 15 additions & 13 deletions src/libtmux/_internal/query_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@
This is an internal API not covered by versioning policy.
"""

import logging
import re
import traceback
import typing as t
from collections.abc import Iterable, Mapping, Sequence

logger = logging.getLogger(__name__)

if t.TYPE_CHECKING:

class LookupProtocol(t.Protocol):
Expand Down Expand Up @@ -102,7 +105,7 @@ def keygetter(

except Exception as e:
traceback.print_stack()
print(f"Above error was {e}")
logger.debug(f"The above error was {e}")
return None

return dct
Expand Down Expand Up @@ -141,8 +144,9 @@ def parse_lookup(
field_name = path.rsplit(lookup)[0]
if field_name is not None:
return keygetter(obj, field_name)
except Exception:
except Exception as e:
traceback.print_stack()
logger.debug(f"The above error was {e}")
return None


Expand Down Expand Up @@ -307,12 +311,12 @@ def lookup_iregex(


class PKRequiredException(Exception):
def __init__(self, *args: object):
def __init__(self, *args: object) -> None:
return super().__init__("items() require a pk_key exists")


class OpNotFound(ValueError):
def __init__(self, op: str, *args: object):
def __init__(self, op: str, *args: object) -> None:
return super().__init__(f"{op} not in LOOKUP_NAME_MAP")


Expand Down Expand Up @@ -473,7 +477,7 @@ def __init__(self, items: t.Optional["Iterable[T]"] = None) -> None:

def items(self) -> t.List[t.Tuple[str, T]]:
if self.pk_key is None:
raise PKRequiredException()
raise PKRequiredException
return [(getattr(item, self.pk_key), item) for item in self]

def __eq__(
Expand All @@ -493,9 +497,8 @@ def __eq__(
for key in a_keys:
if abs(a[key] - b[key]) > 1:
return False
else:
if a != b:
return False
elif a != b:
return False

return True
return False
Expand Down Expand Up @@ -534,8 +537,7 @@ def filter_lookup(obj: t.Any) -> bool:
def val_match(obj: t.Union[str, t.List[t.Any], T]) -> bool:
if isinstance(matcher, list):
return obj in matcher
else:
return bool(obj == matcher)
return bool(obj == matcher)

_filter = val_match
else:
Expand All @@ -557,9 +559,9 @@ def get(
"""
objs = self.filter(matcher=matcher, **kwargs)
if len(objs) > 1:
raise MultipleObjectsReturned()
elif len(objs) == 0:
raise MultipleObjectsReturned
if len(objs) == 0:
if default == no_arg:
raise ObjectDoesNotExist()
raise ObjectDoesNotExist
return default
return objs[0]
11 changes: 5 additions & 6 deletions src/libtmux/_vendor/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType

__all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"]
__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"]

InfiniteTypes = Union[InfinityType, NegativeInfinityType]
PrePostDevType = Union[InfiniteTypes, Tuple[str, int]]
Expand Down Expand Up @@ -78,7 +78,7 @@ class InvalidVersion(ValueError):
libtmux._vendor.version.InvalidVersion: Invalid version: 'invalid'
"""

def __init__(self, version: str, *args: object):
def __init__(self, version: str, *args: object) -> None:
return super().__init__(f"Invalid version: '{version}'")


Expand Down Expand Up @@ -362,8 +362,7 @@ def local(self) -> Optional[str]:
"""
if self._version.local:
return ".".join(str(x) for x in self._version.local)
else:
return None
return None

@property
def public(self) -> str:
Expand Down Expand Up @@ -494,9 +493,9 @@ def _parse_letter_version(
letter = "a"
elif letter == "beta":
letter = "b"
elif letter in ["c", "pre", "preview"]:
elif letter in {"c", "pre", "preview"}:
letter = "rc"
elif letter in ["rev", "r"]:
elif letter in {"rev", "r"}:
letter = "post"

return letter, int(number)
Expand Down
20 changes: 7 additions & 13 deletions src/libtmux/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,6 @@
from . import exc
from ._compat import LooseVersion, console_to_str, str_from_console

if t.TYPE_CHECKING:
pass


logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -219,7 +215,7 @@ class tmux_cmd:
def __init__(self, *args: t.Any) -> None:
tmux_bin = shutil.which("tmux")
if not tmux_bin:
raise exc.TmuxCommandNotFound()
raise exc.TmuxCommandNotFound

cmd = [tmux_bin]
cmd += args # add the command arguments to cmd
Expand Down Expand Up @@ -416,8 +412,7 @@ def has_minimum_version(raises: bool = True) -> bool:
+ "libtmux."
)
raise exc.VersionTooLow(msg)
else:
return False
return False
return True


Expand All @@ -439,9 +434,9 @@ def session_check_name(session_name: t.Optional[str]) -> None:
"""
if session_name is None or len(session_name) == 0:
raise exc.BadSessionName(reason="empty", session_name=session_name)
elif "." in session_name:
if "." in session_name:
raise exc.BadSessionName(reason="contains periods", session_name=session_name)
elif ":" in session_name:
if ":" in session_name:
raise exc.BadSessionName(reason="contains colons", session_name=session_name)


Expand Down Expand Up @@ -474,12 +469,11 @@ def handle_option_error(error: str) -> t.Type[exc.OptionError]:
"""
if "unknown option" in error:
raise exc.UnknownOption(error)
elif "invalid option" in error:
if "invalid option" in error:
raise exc.InvalidOption(error)
elif "ambiguous option" in error:
if "ambiguous option" in error:
raise exc.AmbiguousOption(error)
else:
raise exc.OptionError(error) # Raise generic option error
raise exc.OptionError(error) # Raise generic option error


def get_libtmux_version() -> LooseVersion:
Expand Down
26 changes: 12 additions & 14 deletions src/libtmux/exc.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ def __init__(
list_cmd: t.Optional[str] = None,
list_extra_args: "t.Optional[ListExtraArgs]" = None,
*args: object,
):
) -> None:
if all(arg is not None for arg in [obj_key, obj_id, list_cmd, list_extra_args]):
return super().__init__(
f"Could not find {obj_key}={obj_id} for {list_cmd} "
Expand All @@ -56,7 +56,7 @@ def __init__(
reason: str,
session_name: t.Optional[str] = None,
*args: object,
):
) -> None:
msg = f"Bad session name: {reason}"
if session_name is not None:
msg += f" (session name: {session_name})"
Expand All @@ -74,7 +74,7 @@ class UnknownOption(OptionError):
class UnknownColorOption(UnknownOption):
"""Unknown color option."""

def __init__(self, *args: object):
def __init__(self, *args: object) -> None:
return super().__init__("Server.colors must equal 88 or 256")


Expand All @@ -93,7 +93,7 @@ class WaitTimeout(LibTmuxException):
class VariableUnpackingError(LibTmuxException):
"""Error unpacking variable."""

def __init__(self, variable: t.Optional[t.Any] = None, *args: object):
def __init__(self, variable: t.Optional[t.Any] = None, *args: object) -> None:
return super().__init__(f"Unexpected variable: {variable!s}")


Expand All @@ -104,7 +104,7 @@ class PaneError(LibTmuxException):
class PaneNotFound(PaneError):
"""Pane not found."""

def __init__(self, pane_id: t.Optional[str] = None, *args: object):
def __init__(self, pane_id: t.Optional[str] = None, *args: object) -> None:
if pane_id is not None:
return super().__init__(f"Pane not found: {pane_id}")
return super().__init__("Pane not found")
Expand All @@ -117,21 +117,21 @@ class WindowError(LibTmuxException):
class MultipleActiveWindows(WindowError):
"""Multiple active windows."""

def __init__(self, count: int, *args: object):
def __init__(self, count: int, *args: object) -> None:
return super().__init__(f"Multiple active windows: {count} found")


class NoActiveWindow(WindowError):
"""No active window found."""

def __init__(self, *args: object):
def __init__(self, *args: object) -> None:
return super().__init__("No active windows found")


class NoWindowsExist(WindowError):
"""No windows exist for object."""

def __init__(self, *args: object):
def __init__(self, *args: object) -> None:
return super().__init__("No windows exist for object")


Expand All @@ -143,20 +143,18 @@ def __init__(self) -> None:


class WindowAdjustmentDirectionRequiresAdjustment(
WindowError, AdjustmentDirectionRequiresAdjustment
WindowError,
AdjustmentDirectionRequiresAdjustment,
):
"""ValueError for :meth:`libtmux.Window.resize_window`."""

pass


class PaneAdjustmentDirectionRequiresAdjustment(
WindowError, AdjustmentDirectionRequiresAdjustment
WindowError,
AdjustmentDirectionRequiresAdjustment,
):
"""ValueError for :meth:`libtmux.Pane.resize_pane`."""

pass


class RequiresDigitOrPercentage(LibTmuxException, ValueError):
"""Requires digit (int or str digit) or a percentage."""
Expand Down
6 changes: 1 addition & 5 deletions src/libtmux/neo.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,11 +226,7 @@ def fetch_objs(
]

# Filter empty values
obj_formatters_filtered = [
{k: v for k, v in formatter.items() if v} for formatter in obj_formatters
]

return obj_formatters_filtered
return [{k: v for k, v in formatter.items() if v} for formatter in obj_formatters]


def fetch_obj(
Expand Down
Loading