Skip to content

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

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 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 @@ -19,6 +19,25 @@ $ pipx install --suffix=@next 'tmuxp' --pip-args '\--pre' --force

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

### Development

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

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
```

## tmuxp 1.44.0 (2024-03-24)

### Breaking changes
Expand Down
10 changes: 5 additions & 5 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ def home_path_default(monkeypatch: pytest.MonkeyPatch, user_path: pathlib.Path)
monkeypatch.setenv("HOME", str(user_path))


@pytest.fixture
@pytest.fixture()
def tmuxp_configdir(user_path: pathlib.Path) -> pathlib.Path:
"""Ensure and return tmuxp config directory."""
xdg_config_dir = user_path / ".config"
Expand All @@ -58,7 +58,7 @@ def tmuxp_configdir(user_path: pathlib.Path) -> pathlib.Path:
return tmuxp_configdir


@pytest.fixture
@pytest.fixture()
def tmuxp_configdir_default(
monkeypatch: pytest.MonkeyPatch,
tmuxp_configdir: pathlib.Path,
Expand All @@ -68,7 +68,7 @@ def tmuxp_configdir_default(
assert get_workspace_dir() == str(tmuxp_configdir)


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


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


@pytest.fixture(scope="function")
@pytest.fixture()
def socket_name(request: pytest.FixtureRequest) -> str:
"""Random socket name for tmuxp."""
return "tmuxp_test%s" % next(namer)
Expand Down
25 changes: 15 additions & 10 deletions docs/_ext/aafig.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
:license: BOLA, see LICENSE for details
"""

import locale
import logging
import posixpath
import typing as t
Expand Down Expand Up @@ -91,7 +92,7 @@ def run(self) -> t.List[nodes.Node]:
if v is None:
v = True
# convert percentage to float
if k == "scale" or k == "aspect":
if k in {"scale", "aspect"}:
v = float(v) / 100.0
aafig_options[k] = v
del self.options[k]
Expand All @@ -108,7 +109,7 @@ def render_aafig_images(app: "Sphinx", doctree: nodes.Node) -> None:
format_map = app.builder.config.aafig_format
merge_dict(format_map, DEFAULT_FORMATS)
if aafigure is None:
logger.warn(
logger.warning(
"aafigure module not installed, ASCII art images "
"will be rendered as literal text",
)
Expand All @@ -124,7 +125,7 @@ def render_aafig_images(app: "Sphinx", doctree: nodes.Node) -> None:
if _format in format_map:
options["format"] = format_map[_format]
else:
logger.warn(
logger.warning(
'unsupported builder format "%s", please '
"add a custom entry in aafig_format config "
"option for this builder" % _format,
Expand All @@ -135,9 +136,9 @@ def render_aafig_images(app: "Sphinx", doctree: nodes.Node) -> None:
img.replace_self(nodes.literal_block(text, text))
continue
try:
fname, outfn, _id, extra = render_aafigure(app, text, options)
fname, _outfn, _id, extra = render_aafigure(app, text, options)
except AafigError as exc:
logger.warn("aafigure error: " + str(exc))
logger.warning("aafigure error: " + str(exc))
img.replace_self(nodes.literal_block(text, text))
continue
img["uri"] = fname
Expand All @@ -162,7 +163,7 @@ def render_aafigure(
) -> t.Tuple[str, str, t.Optional[str], t.Optional[str]]:
"""Render an ASCII art figure into the requested format output file."""
if aafigure is None:
raise AafigureNotInstalled()
raise AafigureNotInstalled

fname = get_basename(text, options)
fname = "{}.{}".format(get_basename(text, options), options["format"])
Expand All @@ -174,7 +175,7 @@ def render_aafigure(
else:
# Non-HTML
if app.builder.format != "latex":
logger.warn(
logger.warning(
"aafig: the builder format %s is not officially "
"supported, aafigure images could not work. "
"Please report problems and working builder to "
Expand All @@ -191,10 +192,12 @@ def render_aafigure(
f = None
try:
try:
with open(metadata_fname) as f:
with open(
metadata_fname, encoding=locale.getpreferredencoding(False)
) as f:
extra = f.read()
except Exception as e:
raise AafigError() from e
raise AafigError from e
finally:
if f is not None:
f.close()
Expand All @@ -213,7 +216,9 @@ def render_aafigure(
extra = None
if options["format"].lower() == "svg":
extra = visitor.get_size_attrs()
with open(metadata_fname, "w") as f:
with open(
metadata_fname, "w", encoding=locale.getpreferredencoding(False)
) as f:
f.write(extra)

return relfn, outfn, None, extra
Expand Down
17 changes: 8 additions & 9 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,15 +202,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
16 changes: 7 additions & 9 deletions src/tmuxp/_internal/config_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,10 @@ def _load(fmt: "FormatLiteral", content: str) -> t.Dict[str, t.Any]:
Loader=yaml.SafeLoader,
),
)
elif fmt == "json":
if fmt == "json":
return t.cast(t.Dict[str, t.Any], json.loads(content))
else:
msg = f"{fmt} not supported in configuration"
raise NotImplementedError(msg)
msg = f"{fmt} not supported in configuration"
raise NotImplementedError(msg)

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

if path.suffix in [".yaml", ".yml"]:
if path.suffix in {".yaml", ".yml"}:
fmt: "FormatLiteral" = "yaml"
elif path.suffix == ".json":
fmt = "json"
Expand Down Expand Up @@ -182,14 +181,13 @@ def _dump(
default_flow_style=False,
Dumper=yaml.SafeDumper,
)
elif fmt == "json":
if fmt == "json":
return json.dumps(
content,
indent=2,
)
else:
msg = f"{fmt} not supported in config"
raise NotImplementedError(msg)
msg = f"{fmt} not supported in config"
raise NotImplementedError(msg)

def dump(self, fmt: "FormatLiteral", indent: int = 2, **kwargs: t.Any) -> str:
r"""Dump via ConfigReader instance.
Expand Down
11 changes: 6 additions & 5 deletions src/tmuxp/cli/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
from libtmux.common import has_minimum_version
from libtmux.exc import TmuxCommandNotFound

from .. import exc
from ..__about__ import __version__
from ..log import setup_logger
from tmuxp import exc
from tmuxp.__about__ import __version__
from tmuxp.log import setup_logger

from .convert import command_convert, create_convert_subparser
from .debug_info import command_debug_info, create_debug_info_subparser
from .edit import command_edit, create_edit_subparser
Expand Down Expand Up @@ -141,7 +142,7 @@ def cli(_args: t.Optional[t.List[str]] = None) -> None:
if args.subparser_name is None:
parser.print_help()
return
elif args.subparser_name == "load":
if args.subparser_name == "load":
command_load(
args=CLILoadNamespace(**vars(args)),
parser=parser,
Expand All @@ -156,7 +157,7 @@ def cli(_args: t.Optional[t.List[str]] = None) -> None:
if import_subparser_name is None:
parser.print_help()
return
elif import_subparser_name == "teamocil":
if import_subparser_name == "teamocil":
command_import_teamocil(
workspace_file=args.workspace_file,
parser=parser,
Expand Down
7 changes: 4 additions & 3 deletions src/tmuxp/cli/convert.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
"""CLI for ``tmuxp convert`` subcommand."""

import argparse
import locale
import os
import pathlib
import typing as t

from tmuxp import exc
from tmuxp._internal.config_reader import ConfigReader
from tmuxp.workspace.finders import find_workspace_file, get_workspace_dir

from .. import exc
from .utils import prompt_yes_no

if t.TYPE_CHECKING:
Expand Down Expand Up @@ -70,7 +71,7 @@ def command_convert(
to_filetype: "AllowedFileTypes"
if ext == ".json":
to_filetype = "yaml"
elif ext in [".yaml", ".yml"]:
elif ext in {".yaml", ".yml"}:
to_filetype = "json"
else:
raise ConvertUnknownFileType(ext)
Expand All @@ -92,6 +93,6 @@ def command_convert(
answer_yes = True

if answer_yes:
with open(newfile, "w") as buf:
with open(newfile, "w", encoding=locale.getpreferredencoding(False)) as buf:
buf.write(new_workspace)
print(f"New workspace file saved to <{newfile}>.")
3 changes: 2 additions & 1 deletion src/tmuxp/cli/debug_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
from libtmux.__about__ import __version__ as libtmux_version
from libtmux.common import get_version, tmux_cmd

from ..__about__ import __version__
from tmuxp.__about__ import __version__

from .utils import tmuxp_echo

tmuxp_path = pathlib.Path(__file__).parent.parent
Expand Down
9 changes: 5 additions & 4 deletions src/tmuxp/cli/freeze.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
"""CLI for ``tmuxp freeze`` subcommand."""

import argparse
import locale
import os
import pathlib
import sys
import typing as t

from libtmux.server import Server

from tmuxp import exc, util
from tmuxp._internal.config_reader import ConfigReader
from tmuxp.exc import TmuxpException
from tmuxp.workspace import freezer
from tmuxp.workspace.finders import get_workspace_dir

from .. import exc, util
from ..workspace import freezer
from .utils import prompt, prompt_choices, prompt_yes_no

if t.TYPE_CHECKING:
Expand Down Expand Up @@ -112,7 +113,7 @@ def command_freeze(
session = util.get_session(server)

if not session:
raise exc.SessionNotFound()
raise exc.SessionNotFound
except TmuxpException as e:
print(e)
return
Expand Down Expand Up @@ -206,7 +207,7 @@ def extract_workspace_format(
destdir = os.path.dirname(dest)
if not os.path.isdir(destdir):
os.makedirs(destdir)
with open(dest, "w") as buf:
with open(dest, "w", encoding=locale.getpreferredencoding(False)) as buf:
buf.write(workspace)

if not args.quiet:
Expand Down
5 changes: 3 additions & 2 deletions src/tmuxp/cli/import_config.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
"""CLI for ``tmuxp shell`` subcommand."""

import argparse
import locale
import os
import pathlib
import sys
import typing as t

from tmuxp._internal.config_reader import ConfigReader
from tmuxp.workspace import importers
from tmuxp.workspace.finders import find_workspace_file

from ..workspace import importers
from .utils import prompt, prompt_choices, prompt_yes_no, tmuxp_echo


Expand Down Expand Up @@ -172,7 +173,7 @@ def import_config(
if prompt_yes_no("Save to %s?" % dest_path):
dest = dest_path

with open(dest, "w") as buf:
with open(dest, "w", encoding=locale.getpreferredencoding(False)) as buf:
buf.write(new_config)

tmuxp_echo("Saved to %s." % dest)
Expand Down
Loading