Skip to content

Commit 1705f9f

Browse files
authored
Linting: Aggressive ruff pass (ruff v0.3.4, #539)
2 parents 3eb0599 + dcc8cb2 commit 1705f9f

22 files changed

+216
-193
lines changed

CHANGES

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,25 @@ $ pip install --user --upgrade --pre libtmux
1515

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

18+
### Development
19+
20+
- Aggressive automated lint fixes via `ruff` (#539)
21+
22+
via ruff v0.3.4, all automated lint fixes, including unsafe and previews were applied:
23+
24+
```sh
25+
ruff check --select ALL . --fix --unsafe-fixes --preview --show-fixes; ruff format .
26+
```
27+
28+
Branches were treated with:
29+
30+
```sh
31+
git rebase \
32+
--strategy-option=theirs \
33+
--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' \
34+
origin/master
35+
```
36+
1837
## libtmux 0.35.1 (2024-03-23)
1938

2039
### Bug fix

conftest.py

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -21,9 +21,6 @@
2121
from libtmux.session import Session
2222
from libtmux.window import Window
2323

24-
if t.TYPE_CHECKING:
25-
from libtmux.session import Session
26-
2724
pytest_plugins = ["pytester"]
2825

2926

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

4946

50-
@pytest.fixture(autouse=True, scope="function")
47+
@pytest.fixture(autouse=True)
5148
def set_home(
5249
monkeypatch: pytest.MonkeyPatch,
5350
user_path: pathlib.Path,
@@ -56,12 +53,11 @@ def set_home(
5653
monkeypatch.setenv("HOME", str(user_path))
5754

5855

59-
@pytest.fixture(autouse=True, scope="function")
56+
@pytest.fixture(autouse=True)
6057
def setup_fn(
6158
clear_env: None,
6259
) -> None:
6360
"""Function-level test configuration fixtures for pytest."""
64-
pass
6561

6662

6763
@pytest.fixture(autouse=True, scope="session")

docs/conf.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -197,15 +197,14 @@ def linkcode_resolve(domain: str, info: t.Dict[str, str]) -> t.Union[None, str]:
197197
fn,
198198
linespec,
199199
)
200-
else:
201-
return "{}/blob/v{}/{}/{}/{}{}".format(
202-
about["__github__"],
203-
about["__version__"],
204-
"src",
205-
about["__package_name__"],
206-
fn,
207-
linespec,
208-
)
200+
return "{}/blob/v{}/{}/{}/{}{}".format(
201+
about["__github__"],
202+
about["__version__"],
203+
"src",
204+
about["__package_name__"],
205+
fn,
206+
linespec,
207+
)
209208

210209

211210
def remove_tabs_js(app: "Sphinx", exc: Exception) -> None:

src/libtmux/_internal/query_list.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,14 @@
55
This is an internal API not covered by versioning policy.
66
"""
77

8+
import logging
89
import re
910
import traceback
1011
import typing as t
1112
from collections.abc import Iterable, Mapping, Sequence
1213

14+
logger = logging.getLogger(__name__)
15+
1316
if t.TYPE_CHECKING:
1417

1518
class LookupProtocol(t.Protocol):
@@ -102,7 +105,7 @@ def keygetter(
102105

103106
except Exception as e:
104107
traceback.print_stack()
105-
print(f"Above error was {e}")
108+
logger.debug(f"The above error was {e}")
106109
return None
107110

108111
return dct
@@ -141,8 +144,9 @@ def parse_lookup(
141144
field_name = path.rsplit(lookup)[0]
142145
if field_name is not None:
143146
return keygetter(obj, field_name)
144-
except Exception:
147+
except Exception as e:
145148
traceback.print_stack()
149+
logger.debug(f"The above error was {e}")
146150
return None
147151

148152

@@ -307,12 +311,12 @@ def lookup_iregex(
307311

308312

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

313317

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

318322

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

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

479483
def __eq__(
@@ -493,9 +497,8 @@ def __eq__(
493497
for key in a_keys:
494498
if abs(a[key] - b[key]) > 1:
495499
return False
496-
else:
497-
if a != b:
498-
return False
500+
elif a != b:
501+
return False
499502

500503
return True
501504
return False
@@ -534,8 +537,7 @@ def filter_lookup(obj: t.Any) -> bool:
534537
def val_match(obj: t.Union[str, t.List[t.Any], T]) -> bool:
535538
if isinstance(matcher, list):
536539
return obj in matcher
537-
else:
538-
return bool(obj == matcher)
540+
return bool(obj == matcher)
539541

540542
_filter = val_match
541543
else:
@@ -557,9 +559,9 @@ def get(
557559
"""
558560
objs = self.filter(matcher=matcher, **kwargs)
559561
if len(objs) > 1:
560-
raise MultipleObjectsReturned()
561-
elif len(objs) == 0:
562+
raise MultipleObjectsReturned
563+
if len(objs) == 0:
562564
if default == no_arg:
563-
raise ObjectDoesNotExist()
565+
raise ObjectDoesNotExist
564566
return default
565567
return objs[0]

src/libtmux/_vendor/version.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
from ._structures import Infinity, InfinityType, NegativeInfinity, NegativeInfinityType
1818

19-
__all__ = ["VERSION_PATTERN", "parse", "Version", "InvalidVersion"]
19+
__all__ = ["VERSION_PATTERN", "InvalidVersion", "Version", "parse"]
2020

2121
InfiniteTypes = Union[InfinityType, NegativeInfinityType]
2222
PrePostDevType = Union[InfiniteTypes, Tuple[str, int]]
@@ -78,7 +78,7 @@ class InvalidVersion(ValueError):
7878
libtmux._vendor.version.InvalidVersion: Invalid version: 'invalid'
7979
"""
8080

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

8484

@@ -362,8 +362,7 @@ def local(self) -> Optional[str]:
362362
"""
363363
if self._version.local:
364364
return ".".join(str(x) for x in self._version.local)
365-
else:
366-
return None
365+
return None
367366

368367
@property
369368
def public(self) -> str:
@@ -494,9 +493,9 @@ def _parse_letter_version(
494493
letter = "a"
495494
elif letter == "beta":
496495
letter = "b"
497-
elif letter in ["c", "pre", "preview"]:
496+
elif letter in {"c", "pre", "preview"}:
498497
letter = "rc"
499-
elif letter in ["rev", "r"]:
498+
elif letter in {"rev", "r"}:
500499
letter = "post"
501500

502501
return letter, int(number)

src/libtmux/common.py

Lines changed: 7 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,6 @@
1616
from . import exc
1717
from ._compat import LooseVersion, console_to_str, str_from_console
1818

19-
if t.TYPE_CHECKING:
20-
pass
21-
22-
2319
logger = logging.getLogger(__name__)
2420

2521

@@ -219,7 +215,7 @@ class tmux_cmd:
219215
def __init__(self, *args: t.Any) -> None:
220216
tmux_bin = shutil.which("tmux")
221217
if not tmux_bin:
222-
raise exc.TmuxCommandNotFound()
218+
raise exc.TmuxCommandNotFound
223219

224220
cmd = [tmux_bin]
225221
cmd += args # add the command arguments to cmd
@@ -416,8 +412,7 @@ def has_minimum_version(raises: bool = True) -> bool:
416412
+ "libtmux."
417413
)
418414
raise exc.VersionTooLow(msg)
419-
else:
420-
return False
415+
return False
421416
return True
422417

423418

@@ -439,9 +434,9 @@ def session_check_name(session_name: t.Optional[str]) -> None:
439434
"""
440435
if session_name is None or len(session_name) == 0:
441436
raise exc.BadSessionName(reason="empty", session_name=session_name)
442-
elif "." in session_name:
437+
if "." in session_name:
443438
raise exc.BadSessionName(reason="contains periods", session_name=session_name)
444-
elif ":" in session_name:
439+
if ":" in session_name:
445440
raise exc.BadSessionName(reason="contains colons", session_name=session_name)
446441

447442

@@ -474,12 +469,11 @@ def handle_option_error(error: str) -> t.Type[exc.OptionError]:
474469
"""
475470
if "unknown option" in error:
476471
raise exc.UnknownOption(error)
477-
elif "invalid option" in error:
472+
if "invalid option" in error:
478473
raise exc.InvalidOption(error)
479-
elif "ambiguous option" in error:
474+
if "ambiguous option" in error:
480475
raise exc.AmbiguousOption(error)
481-
else:
482-
raise exc.OptionError(error) # Raise generic option error
476+
raise exc.OptionError(error) # Raise generic option error
483477

484478

485479
def get_libtmux_version() -> LooseVersion:

src/libtmux/exc.py

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def __init__(
3535
list_cmd: t.Optional[str] = None,
3636
list_extra_args: "t.Optional[ListExtraArgs]" = None,
3737
*args: object,
38-
):
38+
) -> None:
3939
if all(arg is not None for arg in [obj_key, obj_id, list_cmd, list_extra_args]):
4040
return super().__init__(
4141
f"Could not find {obj_key}={obj_id} for {list_cmd} "
@@ -56,7 +56,7 @@ def __init__(
5656
reason: str,
5757
session_name: t.Optional[str] = None,
5858
*args: object,
59-
):
59+
) -> None:
6060
msg = f"Bad session name: {reason}"
6161
if session_name is not None:
6262
msg += f" (session name: {session_name})"
@@ -74,7 +74,7 @@ class UnknownOption(OptionError):
7474
class UnknownColorOption(UnknownOption):
7575
"""Unknown color option."""
7676

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

8080

@@ -93,7 +93,7 @@ class WaitTimeout(LibTmuxException):
9393
class VariableUnpackingError(LibTmuxException):
9494
"""Error unpacking variable."""
9595

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

9999

@@ -104,7 +104,7 @@ class PaneError(LibTmuxException):
104104
class PaneNotFound(PaneError):
105105
"""Pane not found."""
106106

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

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

123123

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

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

130130

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

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

137137

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

144144

145145
class WindowAdjustmentDirectionRequiresAdjustment(
146-
WindowError, AdjustmentDirectionRequiresAdjustment
146+
WindowError,
147+
AdjustmentDirectionRequiresAdjustment,
147148
):
148149
"""ValueError for :meth:`libtmux.Window.resize_window`."""
149150

150-
pass
151-
152151

153152
class PaneAdjustmentDirectionRequiresAdjustment(
154-
WindowError, AdjustmentDirectionRequiresAdjustment
153+
WindowError,
154+
AdjustmentDirectionRequiresAdjustment,
155155
):
156156
"""ValueError for :meth:`libtmux.Pane.resize_pane`."""
157157

158-
pass
159-
160158

161159
class RequiresDigitOrPercentage(LibTmuxException, ValueError):
162160
"""Requires digit (int or str digit) or a percentage."""

src/libtmux/neo.py

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -226,11 +226,7 @@ def fetch_objs(
226226
]
227227

228228
# Filter empty values
229-
obj_formatters_filtered = [
230-
{k: v for k, v in formatter.items() if v} for formatter in obj_formatters
231-
]
232-
233-
return obj_formatters_filtered
229+
return [{k: v for k, v in formatter.items() if v} for formatter in obj_formatters]
234230

235231

236232
def fetch_obj(

0 commit comments

Comments
 (0)