Skip to content

Docstring updates, bolster linting #514

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

Merged
merged 16 commits into from
Feb 6, 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
23 changes: 23 additions & 0 deletions CHANGES
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,29 @@ $ pip install --user --upgrade --pre libtmux

<!-- Maintainers and contributors: Insert change notes for the next release above -->

### Documentation

- Various docstring fixes and tweaks (#514)

### Development

- Strengthen linting (#514)

- Add flake8-commas (COM)

- https://docs.astral.sh/ruff/rules/#flake8-commas-com
- https://pypi.org/project/flake8-commas/

- Add flake8-builtins (A)

- https://docs.astral.sh/ruff/rules/#flake8-builtins-a
- https://pypi.org/project/flake8-builtins/

- Add flake8-errmsg (EM)

- https://docs.astral.sh/ruff/rules/#flake8-errmsg-em
- https://pypi.org/project/flake8-errmsg/

### CI

- Move CodeQL from advanced configuration file to GitHub's default
Expand Down
4 changes: 2 additions & 2 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
master_doc = "index"

project = about["__title__"]
copyright = about["__copyright__"]
project_copyright = about["__copyright__"]

version = "%s" % (".".join(about["__version__"].split("."))[:2])
release = "%s" % (about["__version__"])
Expand Down Expand Up @@ -98,7 +98,7 @@
"sidebar/navigation.html",
"sidebar/projects.html",
"sidebar/scroll-end.html",
]
],
}

# linkify_issues
Expand Down
6 changes: 6 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,11 @@ select = [
"F", # pyflakes
"I", # isort
"UP", # pyupgrade
"A", # flake8-builtins
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"COM", # flake8-commas
"EM", # flake8-errmsg
"Q", # flake8-quotes
"PTH", # flake8-use-pathlib
"SIM", # flake8-simplify
Expand All @@ -132,6 +135,9 @@ select = [
"RUF", # Ruff-specific rules
"D", # pydocstyle
]
ignore = [
"COM812", # missing trailing comma, ruff format conflict
]

[tool.ruff.lint.isort]
known-first-party = [
Expand Down
4 changes: 3 additions & 1 deletion src/libtmux/_internal/query_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,9 @@ def keygetter(


def parse_lookup(
obj: "Mapping[str, t.Any]", path: str, lookup: str
obj: "Mapping[str, t.Any]",
path: str,
lookup: str,
) -> t.Optional[t.Any]:
"""Check if field lookup key, e.g. "my__path__contains" has comparator, return val.

Expand Down
18 changes: 13 additions & 5 deletions src/libtmux/_vendor/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,18 @@
],
]
CmpKey = Tuple[
int, Tuple[int, ...], PrePostDevType, PrePostDevType, PrePostDevType, LocalType
int,
Tuple[int, ...],
PrePostDevType,
PrePostDevType,
PrePostDevType,
LocalType,
]
VersionComparisonMethod = Callable[[CmpKey, CmpKey], bool]

_Version = collections.namedtuple(
"_Version", ["epoch", "release", "dev", "pre", "post", "local"]
"_Version",
["epoch", "release", "dev", "pre", "post", "local"],
)


Expand Down Expand Up @@ -220,7 +226,8 @@ def __init__(self, version: str) -> None:
release=tuple(int(i) for i in match.group("release").split(".")),
pre=_parse_letter_version(match.group("pre_l"), match.group("pre_n")),
post=_parse_letter_version(
match.group("post_l"), match.group("post_n1") or match.group("post_n2")
match.group("post_l"),
match.group("post_n1") or match.group("post_n2"),
),
dev=_parse_letter_version(match.group("dev_l"), match.group("dev_n")),
local=_parse_local_version(match.group("local")),
Expand Down Expand Up @@ -468,7 +475,8 @@ def micro(self) -> int:


def _parse_letter_version(
letter: str, number: Union[str, bytes, SupportsInt]
letter: str,
number: Union[str, bytes, SupportsInt],
) -> Optional[Tuple[str, int]]:
if letter:
# We consider there to be an implicit 0 in a pre-release if there is
Expand Down Expand Up @@ -529,7 +537,7 @@ def _cmpkey(
# re-reverse it back into the correct order and make it a tuple and use
# that for our sorting key.
_release = tuple(
reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release))))
reversed(list(itertools.dropwhile(lambda x: x == 0, reversed(release)))),
)

# We need to "trick" the sorting algorithm to put 1.0.dev0 before 1.0a0.
Expand Down
71 changes: 33 additions & 38 deletions src/libtmux/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,7 @@ def __init__(self, add_option: Optional[str] = None) -> None:
self._add_option = add_option

def set_environment(self, name: str, value: str) -> None:
"""
Set environment ``$ tmux set-environment <name> <value>``.
"""Set environment ``$ tmux set-environment <name> <value>``.

Parameters
----------
Expand All @@ -73,8 +72,7 @@ def set_environment(self, name: str, value: str) -> None:
raise ValueError("tmux set-environment stderr: %s" % cmd.stderr)

def unset_environment(self, name: str) -> None:
"""
Unset environment variable ``$ tmux set-environment -u <name>``.
"""Unset environment variable ``$ tmux set-environment -u <name>``.

Parameters
----------
Expand Down Expand Up @@ -139,17 +137,17 @@ def show_environment(self) -> Dict[str, Union[bool, str]]:
tmux_args += [self._add_option]
cmd = self.cmd(*tmux_args)
output = cmd.stdout
vars = [tuple(item.split("=", 1)) for item in output]
vars_dict: t.Dict[str, t.Union[str, bool]] = {}
for _t in vars:
opts = [tuple(item.split("=", 1)) for item in output]
opts_dict: t.Dict[str, t.Union[str, bool]] = {}
for _t in opts:
if len(_t) == 2:
vars_dict[_t[0]] = _t[1]
opts_dict[_t[0]] = _t[1]
elif len(_t) == 1:
vars_dict[_t[0]] = True
opts_dict[_t[0]] = True
else:
raise exc.VariableUnpackingError(variable=_t)

return vars_dict
return opts_dict

def getenv(self, name: str) -> Optional[t.Union[str, bool]]:
"""Show environment variable ``$ tmux show-environment -t [session] <name>``.
Expand All @@ -176,22 +174,21 @@ def getenv(self, name: str) -> Optional[t.Union[str, bool]]:
tmux_args += (name,)
cmd = self.cmd(*tmux_args)
output = cmd.stdout
vars = [tuple(item.split("=", 1)) for item in output]
vars_dict: t.Dict[str, t.Union[str, bool]] = {}
for _t in vars:
opts = [tuple(item.split("=", 1)) for item in output]
opts_dict: t.Dict[str, t.Union[str, bool]] = {}
for _t in opts:
if len(_t) == 2:
vars_dict[_t[0]] = _t[1]
opts_dict[_t[0]] = _t[1]
elif len(_t) == 1:
vars_dict[_t[0]] = True
opts_dict[_t[0]] = True
else:
raise exc.VariableUnpackingError(variable=_t)

return vars_dict.get(name)
return opts_dict.get(name)


class tmux_cmd:
"""
:term:`tmux(1)` command via :py:mod:`subprocess`.
""":term:`tmux(1)` command via :py:mod:`subprocess`.

Examples
--------
Expand Down Expand Up @@ -231,7 +228,9 @@ def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:

try:
self.process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = self.process.communicate()
returncode = self.process.returncode
Expand All @@ -258,14 +257,14 @@ def __init__(self, *args: t.Any, **kwargs: t.Any) -> None:

logger.debug(
"self.stdout for {cmd}: {stdout}".format(
cmd=" ".join(cmd), stdout=self.stdout
)
cmd=" ".join(cmd),
stdout=self.stdout,
),
)


def get_version() -> LooseVersion:
"""
Return tmux version.
"""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``.
Expand All @@ -285,7 +284,7 @@ def get_version() -> LooseVersion:
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
" is running tmux 1.3 or earlier." % TMUX_MIN_VERSION,
)
raise exc.VersionTooLow(proc.stderr)

Expand All @@ -301,8 +300,7 @@ def get_version() -> LooseVersion:


def has_version(version: str) -> bool:
"""
Return affirmative if tmux version installed.
"""Return True if tmux version installed.

Parameters
----------
Expand All @@ -318,8 +316,7 @@ def has_version(version: str) -> bool:


def has_gt_version(min_version: str) -> bool:
"""
Return affirmative if tmux version greater than minimum.
"""Return True if tmux version greater than minimum.

Parameters
----------
Expand All @@ -335,8 +332,7 @@ def has_gt_version(min_version: str) -> bool:


def has_gte_version(min_version: str) -> bool:
"""
Return True if tmux version greater or equal to minimum.
"""Return True if tmux version greater or equal to minimum.

Parameters
----------
Expand All @@ -352,8 +348,7 @@ def has_gte_version(min_version: str) -> bool:


def has_lte_version(max_version: str) -> bool:
"""
Return True if tmux version less or equal to minimum.
"""Return True if tmux version less or equal to minimum.

Parameters
----------
Expand All @@ -369,8 +364,7 @@ def has_lte_version(max_version: str) -> bool:


def has_lt_version(max_version: str) -> bool:
"""
Return True if tmux version less than minimum.
"""Return True if tmux version less than minimum.

Parameters
----------
Expand All @@ -386,8 +380,7 @@ def has_lt_version(max_version: str) -> bool:


def has_minimum_version(raises: bool = True) -> bool:
"""
Return if tmux meets version requirement. Version >1.8 or above.
"""Return True if tmux meets version requirement. Version >1.8 or above.

Parameters
----------
Expand Down Expand Up @@ -416,12 +409,14 @@ def has_minimum_version(raises: bool = True) -> bool:
"""
if get_version() < LooseVersion(TMUX_MIN_VERSION):
if raises:
raise exc.VersionTooLow(
msg = (
"libtmux only supports tmux {} and greater. This system"
" has {} installed. Upgrade your tmux to use libtmux.".format(
TMUX_MIN_VERSION, get_version()
TMUX_MIN_VERSION,
get_version(),
)
)
raise exc.VersionTooLow(msg)
else:
return False
return True
Expand Down
7 changes: 5 additions & 2 deletions src/libtmux/exc.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def __init__(
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} "
f'{list_extra_args if list_extra_args is not None else ""}'
f'{list_extra_args if list_extra_args is not None else ""}',
)
return super().__init__("Could not find object")

Expand All @@ -51,7 +51,10 @@ class BadSessionName(LibTmuxException):
"""Disallowed session name for tmux (empty, contains periods or colons)."""

def __init__(
self, reason: str, session_name: t.Optional[str] = None, *args: object
self,
reason: str,
session_name: t.Optional[str] = None,
*args: object,
):
msg = f"Bad session name: {reason}"
if session_name is not None:
Expand Down
9 changes: 7 additions & 2 deletions src/libtmux/neo.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,10 @@ def _refresh(
) -> None:
assert isinstance(obj_id, str)
obj = fetch_obj(
obj_key=obj_key, obj_id=obj_id, list_cmd=list_cmd, server=self.server
obj_key=obj_key,
obj_id=obj_id,
list_cmd=list_cmd,
server=self.server,
)
assert obj is not None
if obj is not None:
Expand Down Expand Up @@ -233,7 +236,9 @@ def fetch_obj(
) -> OutputRaw:
"""Fetch raw data from tmux command."""
obj_formatters_filtered = fetch_objs(
server=server, list_cmd=list_cmd, list_extra_args=list_extra_args
server=server,
list_cmd=list_cmd,
list_extra_args=list_extra_args,
)

obj = None
Expand Down
Loading