Skip to content

Commit 637e119

Browse files
authored
Linting: Aggressive ruff pass (ruff v0.3.4, #922)
2 parents 5a4bbb6 + 53f41e2 commit 637e119

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

50 files changed

+250
-246
lines changed

CHANGES

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,25 @@ $ pipx install --suffix=@next 'tmuxp' --pip-args '\--pre' --force
1919

2020
<!-- Maintainers, insert changes / features for the next release here -->
2121

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

2443
### Breaking changes

conftest.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ def home_path_default(monkeypatch: pytest.MonkeyPatch, user_path: pathlib.Path)
4747
monkeypatch.setenv("HOME", str(user_path))
4848

4949

50-
@pytest.fixture
50+
@pytest.fixture()
5151
def tmuxp_configdir(user_path: pathlib.Path) -> pathlib.Path:
5252
"""Ensure and return tmuxp config directory."""
5353
xdg_config_dir = user_path / ".config"
@@ -58,7 +58,7 @@ def tmuxp_configdir(user_path: pathlib.Path) -> pathlib.Path:
5858
return tmuxp_configdir
5959

6060

61-
@pytest.fixture
61+
@pytest.fixture()
6262
def tmuxp_configdir_default(
6363
monkeypatch: pytest.MonkeyPatch,
6464
tmuxp_configdir: pathlib.Path,
@@ -68,7 +68,7 @@ def tmuxp_configdir_default(
6868
assert get_workspace_dir() == str(tmuxp_configdir)
6969

7070

71-
@pytest.fixture(scope="function")
71+
@pytest.fixture()
7272
def monkeypatch_plugin_test_packages(monkeypatch: pytest.MonkeyPatch) -> None:
7373
"""Monkeypatch tmuxp plugin fixtures to python path."""
7474
paths = [
@@ -83,14 +83,14 @@ def monkeypatch_plugin_test_packages(monkeypatch: pytest.MonkeyPatch) -> None:
8383
monkeypatch.syspath_prepend(str(pathlib.Path(path).resolve()))
8484

8585

86-
@pytest.fixture(scope="function")
86+
@pytest.fixture()
8787
def session_params(session_params: t.Dict[str, t.Any]) -> t.Dict[str, t.Any]:
8888
"""Terminal-friendly tmuxp session_params for dimensions."""
8989
session_params.update({"x": 800, "y": 600})
9090
return session_params
9191

9292

93-
@pytest.fixture(scope="function")
93+
@pytest.fixture()
9494
def socket_name(request: pytest.FixtureRequest) -> str:
9595
"""Random socket name for tmuxp."""
9696
return "tmuxp_test%s" % next(namer)

docs/_ext/aafig.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
:license: BOLA, see LICENSE for details
1313
"""
1414

15+
import locale
1516
import logging
1617
import posixpath
1718
import typing as t
@@ -91,7 +92,7 @@ def run(self) -> t.List[nodes.Node]:
9192
if v is None:
9293
v = True
9394
# convert percentage to float
94-
if k == "scale" or k == "aspect":
95+
if k in {"scale", "aspect"}:
9596
v = float(v) / 100.0
9697
aafig_options[k] = v
9798
del self.options[k]
@@ -108,7 +109,7 @@ def render_aafig_images(app: "Sphinx", doctree: nodes.Node) -> None:
108109
format_map = app.builder.config.aafig_format
109110
merge_dict(format_map, DEFAULT_FORMATS)
110111
if aafigure is None:
111-
logger.warn(
112+
logger.warning(
112113
"aafigure module not installed, ASCII art images "
113114
"will be rendered as literal text",
114115
)
@@ -124,7 +125,7 @@ def render_aafig_images(app: "Sphinx", doctree: nodes.Node) -> None:
124125
if _format in format_map:
125126
options["format"] = format_map[_format]
126127
else:
127-
logger.warn(
128+
logger.warning(
128129
'unsupported builder format "%s", please '
129130
"add a custom entry in aafig_format config "
130131
"option for this builder" % _format,
@@ -135,9 +136,9 @@ def render_aafig_images(app: "Sphinx", doctree: nodes.Node) -> None:
135136
img.replace_self(nodes.literal_block(text, text))
136137
continue
137138
try:
138-
fname, outfn, _id, extra = render_aafigure(app, text, options)
139+
fname, _outfn, _id, extra = render_aafigure(app, text, options)
139140
except AafigError as exc:
140-
logger.warn("aafigure error: " + str(exc))
141+
logger.warning("aafigure error: " + str(exc))
141142
img.replace_self(nodes.literal_block(text, text))
142143
continue
143144
img["uri"] = fname
@@ -162,7 +163,7 @@ def render_aafigure(
162163
) -> t.Tuple[str, str, t.Optional[str], t.Optional[str]]:
163164
"""Render an ASCII art figure into the requested format output file."""
164165
if aafigure is None:
165-
raise AafigureNotInstalled()
166+
raise AafigureNotInstalled
166167

167168
fname = get_basename(text, options)
168169
fname = "{}.{}".format(get_basename(text, options), options["format"])
@@ -174,7 +175,7 @@ def render_aafigure(
174175
else:
175176
# Non-HTML
176177
if app.builder.format != "latex":
177-
logger.warn(
178+
logger.warning(
178179
"aafig: the builder format %s is not officially "
179180
"supported, aafigure images could not work. "
180181
"Please report problems and working builder to "
@@ -191,10 +192,12 @@ def render_aafigure(
191192
f = None
192193
try:
193194
try:
194-
with open(metadata_fname) as f:
195+
with open(
196+
metadata_fname, encoding=locale.getpreferredencoding(False)
197+
) as f:
195198
extra = f.read()
196199
except Exception as e:
197-
raise AafigError() from e
200+
raise AafigError from e
198201
finally:
199202
if f is not None:
200203
f.close()
@@ -213,7 +216,9 @@ def render_aafigure(
213216
extra = None
214217
if options["format"].lower() == "svg":
215218
extra = visitor.get_size_attrs()
216-
with open(metadata_fname, "w") as f:
219+
with open(
220+
metadata_fname, "w", encoding=locale.getpreferredencoding(False)
221+
) as f:
217222
f.write(extra)
218223

219224
return relfn, outfn, None, extra

docs/conf.py

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -202,15 +202,14 @@ def linkcode_resolve(domain: str, info: t.Dict[str, str]) -> t.Union[None, str]:
202202
fn,
203203
linespec,
204204
)
205-
else:
206-
return "{}/blob/v{}/{}/{}/{}{}".format(
207-
about["__github__"],
208-
about["__version__"],
209-
"src",
210-
about["__package_name__"],
211-
fn,
212-
linespec,
213-
)
205+
return "{}/blob/v{}/{}/{}/{}{}".format(
206+
about["__github__"],
207+
about["__version__"],
208+
"src",
209+
about["__package_name__"],
210+
fn,
211+
linespec,
212+
)
214213

215214

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

src/tmuxp/_internal/config_reader.py

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -45,11 +45,10 @@ def _load(fmt: "FormatLiteral", content: str) -> t.Dict[str, t.Any]:
4545
Loader=yaml.SafeLoader,
4646
),
4747
)
48-
elif fmt == "json":
48+
if fmt == "json":
4949
return t.cast(t.Dict[str, t.Any], json.loads(content))
50-
else:
51-
msg = f"{fmt} not supported in configuration"
52-
raise NotImplementedError(msg)
50+
msg = f"{fmt} not supported in configuration"
51+
raise NotImplementedError(msg)
5352

5453
@classmethod
5554
def load(cls, fmt: "FormatLiteral", content: str) -> "ConfigReader":
@@ -107,7 +106,7 @@ def _from_file(cls, path: pathlib.Path) -> t.Dict[str, t.Any]:
107106
assert isinstance(path, pathlib.Path)
108107
content = path.open().read()
109108

110-
if path.suffix in [".yaml", ".yml"]:
109+
if path.suffix in {".yaml", ".yml"}:
111110
fmt: "FormatLiteral" = "yaml"
112111
elif path.suffix == ".json":
113112
fmt = "json"
@@ -182,14 +181,13 @@ def _dump(
182181
default_flow_style=False,
183182
Dumper=yaml.SafeDumper,
184183
)
185-
elif fmt == "json":
184+
if fmt == "json":
186185
return json.dumps(
187186
content,
188187
indent=2,
189188
)
190-
else:
191-
msg = f"{fmt} not supported in config"
192-
raise NotImplementedError(msg)
189+
msg = f"{fmt} not supported in config"
190+
raise NotImplementedError(msg)
193191

194192
def dump(self, fmt: "FormatLiteral", indent: int = 2, **kwargs: t.Any) -> str:
195193
r"""Dump via ConfigReader instance.

src/tmuxp/cli/__init__.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,10 @@
1111
from libtmux.common import has_minimum_version
1212
from libtmux.exc import TmuxCommandNotFound
1313

14-
from .. import exc
15-
from ..__about__ import __version__
16-
from ..log import setup_logger
14+
from tmuxp import exc
15+
from tmuxp.__about__ import __version__
16+
from tmuxp.log import setup_logger
17+
1718
from .convert import command_convert, create_convert_subparser
1819
from .debug_info import command_debug_info, create_debug_info_subparser
1920
from .edit import command_edit, create_edit_subparser
@@ -141,7 +142,7 @@ def cli(_args: t.Optional[t.List[str]] = None) -> None:
141142
if args.subparser_name is None:
142143
parser.print_help()
143144
return
144-
elif args.subparser_name == "load":
145+
if args.subparser_name == "load":
145146
command_load(
146147
args=CLILoadNamespace(**vars(args)),
147148
parser=parser,
@@ -156,7 +157,7 @@ def cli(_args: t.Optional[t.List[str]] = None) -> None:
156157
if import_subparser_name is None:
157158
parser.print_help()
158159
return
159-
elif import_subparser_name == "teamocil":
160+
if import_subparser_name == "teamocil":
160161
command_import_teamocil(
161162
workspace_file=args.workspace_file,
162163
parser=parser,

src/tmuxp/cli/convert.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
"""CLI for ``tmuxp convert`` subcommand."""
22

33
import argparse
4+
import locale
45
import os
56
import pathlib
67
import typing as t
78

9+
from tmuxp import exc
810
from tmuxp._internal.config_reader import ConfigReader
911
from tmuxp.workspace.finders import find_workspace_file, get_workspace_dir
1012

11-
from .. import exc
1213
from .utils import prompt_yes_no
1314

1415
if t.TYPE_CHECKING:
@@ -70,7 +71,7 @@ def command_convert(
7071
to_filetype: "AllowedFileTypes"
7172
if ext == ".json":
7273
to_filetype = "yaml"
73-
elif ext in [".yaml", ".yml"]:
74+
elif ext in {".yaml", ".yml"}:
7475
to_filetype = "json"
7576
else:
7677
raise ConvertUnknownFileType(ext)
@@ -92,6 +93,6 @@ def command_convert(
9293
answer_yes = True
9394

9495
if answer_yes:
95-
with open(newfile, "w") as buf:
96+
with open(newfile, "w", encoding=locale.getpreferredencoding(False)) as buf:
9697
buf.write(new_workspace)
9798
print(f"New workspace file saved to <{newfile}>.")

src/tmuxp/cli/debug_info.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
from libtmux.__about__ import __version__ as libtmux_version
1313
from libtmux.common import get_version, tmux_cmd
1414

15-
from ..__about__ import __version__
15+
from tmuxp.__about__ import __version__
16+
1617
from .utils import tmuxp_echo
1718

1819
tmuxp_path = pathlib.Path(__file__).parent.parent

src/tmuxp/cli/freeze.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,20 @@
11
"""CLI for ``tmuxp freeze`` subcommand."""
22

33
import argparse
4+
import locale
45
import os
56
import pathlib
67
import sys
78
import typing as t
89

910
from libtmux.server import Server
1011

12+
from tmuxp import exc, util
1113
from tmuxp._internal.config_reader import ConfigReader
1214
from tmuxp.exc import TmuxpException
15+
from tmuxp.workspace import freezer
1316
from tmuxp.workspace.finders import get_workspace_dir
1417

15-
from .. import exc, util
16-
from ..workspace import freezer
1718
from .utils import prompt, prompt_choices, prompt_yes_no
1819

1920
if t.TYPE_CHECKING:
@@ -112,7 +113,7 @@ def command_freeze(
112113
session = util.get_session(server)
113114

114115
if not session:
115-
raise exc.SessionNotFound()
116+
raise exc.SessionNotFound
116117
except TmuxpException as e:
117118
print(e)
118119
return
@@ -206,7 +207,7 @@ def extract_workspace_format(
206207
destdir = os.path.dirname(dest)
207208
if not os.path.isdir(destdir):
208209
os.makedirs(destdir)
209-
with open(dest, "w") as buf:
210+
with open(dest, "w", encoding=locale.getpreferredencoding(False)) as buf:
210211
buf.write(workspace)
211212

212213
if not args.quiet:

src/tmuxp/cli/import_config.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,16 @@
11
"""CLI for ``tmuxp shell`` subcommand."""
22

33
import argparse
4+
import locale
45
import os
56
import pathlib
67
import sys
78
import typing as t
89

910
from tmuxp._internal.config_reader import ConfigReader
11+
from tmuxp.workspace import importers
1012
from tmuxp.workspace.finders import find_workspace_file
1113

12-
from ..workspace import importers
1314
from .utils import prompt, prompt_choices, prompt_yes_no, tmuxp_echo
1415

1516

@@ -172,7 +173,7 @@ def import_config(
172173
if prompt_yes_no("Save to %s?" % dest_path):
173174
dest = dest_path
174175

175-
with open(dest, "w") as buf:
176+
with open(dest, "w", encoding=locale.getpreferredencoding(False)) as buf:
176177
buf.write(new_config)
177178

178179
tmuxp_echo("Saved to %s." % dest)

0 commit comments

Comments
 (0)