From 357b6190680b3e6f4efbc96bbd6449b17c0c17dd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rg=20Thalheim?= Date: Mon, 2 Sep 2024 16:29:50 +0200 Subject: [PATCH] add SIM lint --- pkgs/clan-app/tests/command.py | 5 ++--- pkgs/clan-cli/clan_cli/__init__.py | 5 ++--- pkgs/clan-cli/clan_cli/clan_uri.py | 7 ++----- pkgs/clan-cli/clan_cli/completions.py | 20 +++++-------------- pkgs/clan-cli/clan_cli/config/__init__.py | 2 +- pkgs/clan-cli/clan_cli/facts/check.py | 9 ++------- pkgs/clan-cli/clan_cli/history/list.py | 2 +- pkgs/clan-cli/clan_cli/inventory/__init__.py | 5 ++--- pkgs/clan-cli/clan_cli/machines/create.py | 2 +- pkgs/clan-cli/clan_cli/machines/install.py | 5 +---- pkgs/clan-cli/clan_cli/qemu/qmp.py | 5 +---- pkgs/clan-cli/clan_cli/secrets/sops.py | 6 ++---- pkgs/clan-cli/clan_cli/ssh/__init__.py | 5 +---- pkgs/clan-cli/clan_cli/vars/check.py | 4 +--- pkgs/clan-cli/tests/command.py | 5 ++--- .../tests/test_api_dataclass_compat.py | 4 +--- pkgs/clan-cli/tests/test_git.py | 5 ++--- pkgs/clan-cli/tests/test_history_cli.py | 2 +- pkgs/clan-cli/tests/test_modules.py | 4 ++-- pkgs/clan-cli/tests/test_secrets_cli.py | 9 ++++++--- .../clan_vm_manager/components/vmobj.py | 2 +- pkgs/clan-vm-manager/tests/command.py | 5 ++--- .../moonlight/join.py | 5 +---- .../moonlight/state.py | 5 ++--- pyproject.toml | 16 ++++++++++++++- 25 files changed, 59 insertions(+), 85 deletions(-) diff --git a/pkgs/clan-app/tests/command.py b/pkgs/clan-app/tests/command.py index ba8d67e1c..1dfee4e14 100644 --- a/pkgs/clan-app/tests/command.py +++ b/pkgs/clan-app/tests/command.py @@ -1,3 +1,4 @@ +import contextlib import os import signal import subprocess @@ -46,10 +47,8 @@ class Command: # We just kill all processes as quickly as possible because we don't # care about corrupted state and want to make tests fasts. for p in reversed(self.processes): - try: + with contextlib.suppress(OSError): os.killpg(os.getpgid(p.pid), signal.SIGKILL) - except OSError: - pass @pytest.fixture diff --git a/pkgs/clan-cli/clan_cli/__init__.py b/pkgs/clan-cli/clan_cli/__init__.py index 7ab89cce6..1e01225c4 100644 --- a/pkgs/clan-cli/clan_cli/__init__.py +++ b/pkgs/clan-cli/clan_cli/__init__.py @@ -1,4 +1,5 @@ import argparse +import contextlib import logging import sys from pathlib import Path @@ -35,10 +36,8 @@ from .ssh import cli as ssh_cli log = logging.getLogger(__name__) argcomplete: ModuleType | None = None -try: +with contextlib.suppress(ImportError): import argcomplete # type: ignore[no-redef] -except ImportError: - pass def flake_path(arg: str) -> FlakeId: diff --git a/pkgs/clan-cli/clan_cli/clan_uri.py b/pkgs/clan-cli/clan_cli/clan_uri.py index 8c809e702..a7cf0f358 100644 --- a/pkgs/clan-cli/clan_cli/clan_uri.py +++ b/pkgs/clan-cli/clan_cli/clan_uri.py @@ -47,11 +47,8 @@ class FlakeId: """ x = urllib.parse.urlparse(str(self.loc)) - if x.scheme == "" or "file" in x.scheme: - # See above *file* or empty are the only local schemas - return True - - return False + # See above *file* or empty are the only local schemas + return x.scheme == "" or "file" in x.scheme def is_remote(self) -> bool: return not self.is_local() diff --git a/pkgs/clan-cli/clan_cli/completions.py b/pkgs/clan-cli/clan_cli/completions.py index b0442515c..c5658f1e2 100644 --- a/pkgs/clan-cli/clan_cli/completions.py +++ b/pkgs/clan-cli/clan_cli/completions.py @@ -1,4 +1,5 @@ import argparse +import contextlib import json import subprocess import threading @@ -17,10 +18,8 @@ We target a maximum of 1second on our average machine. argcomplete: ModuleType | None = None -try: +with contextlib.suppress(ImportError): import argcomplete # type: ignore[no-redef] -except ImportError: - pass # The default completion timeout for commands @@ -211,10 +210,7 @@ def complete_secrets( from .clan_uri import FlakeId from .secrets.secrets import ListSecretsOptions, list_secrets - if (clan_dir_result := clan_dir(None)) is not None: - flake = clan_dir_result - else: - flake = "." + flake = clan_dir_result if (clan_dir_result := clan_dir(None)) is not None else "." options = ListSecretsOptions( flake=FlakeId(flake), @@ -237,10 +233,7 @@ def complete_users( from .secrets.users import list_users - if (clan_dir_result := clan_dir(None)) is not None: - flake = clan_dir_result - else: - flake = "." + flake = clan_dir_result if (clan_dir_result := clan_dir(None)) is not None else "." users = list_users(Path(flake)) @@ -258,10 +251,7 @@ def complete_groups( from .secrets.groups import list_groups - if (clan_dir_result := clan_dir(None)) is not None: - flake = clan_dir_result - else: - flake = "." + flake = clan_dir_result if (clan_dir_result := clan_dir(None)) is not None else "." groups_list = list_groups(Path(flake)) groups = [group.name for group in groups_list] diff --git a/pkgs/clan-cli/clan_cli/config/__init__.py b/pkgs/clan-cli/clan_cli/config/__init__.py index bce0a320b..13489425e 100644 --- a/pkgs/clan-cli/clan_cli/config/__init__.py +++ b/pkgs/clan-cli/clan_cli/config/__init__.py @@ -227,7 +227,7 @@ def find_option( regex = rf"({first}|)" for elem in option_path[1:]: regex += rf"\.({elem}|)" - for opt in options.keys(): + for opt in options: if re.match(regex, opt): return opt, value diff --git a/pkgs/clan-cli/clan_cli/facts/check.py b/pkgs/clan-cli/clan_cli/facts/check.py index 7916e2acd..892e234f8 100644 --- a/pkgs/clan-cli/clan_cli/facts/check.py +++ b/pkgs/clan-cli/clan_cli/facts/check.py @@ -16,10 +16,7 @@ def check_secrets(machine: Machine, service: None | str = None) -> bool: missing_secret_facts = [] missing_public_facts = [] - if service: - services = [service] - else: - services = list(machine.facts_data.keys()) + services = [service] if service else list(machine.facts_data.keys()) for service in services: for secret_fact in machine.facts_data[service]["secret"]: if isinstance(secret_fact, str): @@ -41,9 +38,7 @@ def check_secrets(machine: Machine, service: None | str = None) -> bool: log.debug(f"missing_secret_facts: {missing_secret_facts}") log.debug(f"missing_public_facts: {missing_public_facts}") - if missing_secret_facts or missing_public_facts: - return False - return True + return not (missing_secret_facts or missing_public_facts) def check_command(args: argparse.Namespace) -> None: diff --git a/pkgs/clan-cli/clan_cli/history/list.py b/pkgs/clan-cli/clan_cli/history/list.py index 9b46f5ffc..778a6c311 100644 --- a/pkgs/clan-cli/clan_cli/history/list.py +++ b/pkgs/clan-cli/clan_cli/history/list.py @@ -9,7 +9,7 @@ def list_history_command(args: argparse.Namespace) -> None: res: dict[str, list[HistoryEntry]] = {} for history_entry in list_history(): url = str(history_entry.flake.flake_url) - if res.get(url, None) is None: + if res.get(url) is None: res[url] = [] res[url].append(history_entry) diff --git a/pkgs/clan-cli/clan_cli/inventory/__init__.py b/pkgs/clan-cli/clan_cli/inventory/__init__.py index 7cdca7026..d093980d2 100644 --- a/pkgs/clan-cli/clan_cli/inventory/__init__.py +++ b/pkgs/clan-cli/clan_cli/inventory/__init__.py @@ -12,6 +12,7 @@ Operate on the returned inventory to make changes - save_inventory: To persist changes. """ +import contextlib import json from pathlib import Path @@ -163,10 +164,8 @@ def init_inventory(directory: str, init: Inventory | None = None) -> None: inventory = None # Try reading the current flake if init is None: - try: + with contextlib.suppress(ClanCmdError): inventory = load_inventory_eval(directory) - except ClanCmdError: - pass if init is not None: inventory = init diff --git a/pkgs/clan-cli/clan_cli/machines/create.py b/pkgs/clan-cli/clan_cli/machines/create.py index 0a4128c9e..a5319c7fe 100644 --- a/pkgs/clan-cli/clan_cli/machines/create.py +++ b/pkgs/clan-cli/clan_cli/machines/create.py @@ -27,7 +27,7 @@ def create_machine(flake: FlakeId, machine: Machine) -> None: full_inventory = load_inventory_eval(flake.path) - if machine.name in full_inventory.machines.keys(): + if machine.name in full_inventory.machines: msg = f"Machine with the name {machine.name} already exists" raise ClanError(msg) diff --git a/pkgs/clan-cli/clan_cli/machines/install.py b/pkgs/clan-cli/clan_cli/machines/install.py index 8a8bd8509..e2580835e 100644 --- a/pkgs/clan-cli/clan_cli/machines/install.py +++ b/pkgs/clan-cli/clan_cli/machines/install.py @@ -166,10 +166,7 @@ def find_reachable_host_from_deploy_json(deploy_json: dict[str, str]) -> str: host = None for addr in deploy_json["addrs"]: if is_reachable(addr): - if is_ipv6(addr): - host = f"[{addr}]" - else: - host = addr + host = f"[{addr}]" if is_ipv6(addr) else addr break if not host: msg = f""" diff --git a/pkgs/clan-cli/clan_cli/qemu/qmp.py b/pkgs/clan-cli/clan_cli/qemu/qmp.py index 69bb86ae4..699e87593 100644 --- a/pkgs/clan-cli/clan_cli/qemu/qmp.py +++ b/pkgs/clan-cli/clan_cli/qemu/qmp.py @@ -80,10 +80,7 @@ class QEMUMonitorProtocol: self.__sock.listen(1) def __get_sock(self) -> socket.socket: - if isinstance(self.__address, tuple): - family = socket.AF_INET - else: - family = socket.AF_UNIX + family = socket.AF_INET if isinstance(self.__address, tuple) else socket.AF_UNIX return socket.socket(family, socket.SOCK_STREAM) def __negotiate_capabilities(self) -> dict[str, Any]: diff --git a/pkgs/clan-cli/clan_cli/secrets/sops.py b/pkgs/clan-cli/clan_cli/secrets/sops.py index db535cd07..5650b91bd 100644 --- a/pkgs/clan-cli/clan_cli/secrets/sops.py +++ b/pkgs/clan-cli/clan_cli/secrets/sops.py @@ -4,7 +4,7 @@ import os import shutil import subprocess from collections.abc import Iterator -from contextlib import contextmanager +from contextlib import contextmanager, suppress from pathlib import Path from tempfile import NamedTemporaryFile from typing import IO @@ -196,10 +196,8 @@ def encrypt_file( with open(meta_path, "w") as f_meta: json.dump(meta, f_meta, indent=2) finally: - try: + with suppress(OSError): os.remove(f.name) - except OSError: - pass def decrypt_file(secret_path: Path) -> str: diff --git a/pkgs/clan-cli/clan_cli/ssh/__init__.py b/pkgs/clan-cli/clan_cli/ssh/__init__.py index a52f234b7..133af6415 100644 --- a/pkgs/clan-cli/clan_cli/ssh/__init__.py +++ b/pkgs/clan-cli/clan_cli/ssh/__init__.py @@ -476,10 +476,7 @@ class Host: verbose_ssh: bool = False, tty: bool = False, ) -> list[str]: - if self.user is not None: - ssh_target = f"{self.user}@{self.host}" - else: - ssh_target = self.host + ssh_target = f"{self.user}@{self.host}" if self.user is not None else self.host ssh_opts = ["-A"] if self.forward_agent else [] diff --git a/pkgs/clan-cli/clan_cli/vars/check.py b/pkgs/clan-cli/clan_cli/vars/check.py index 9f364113b..ecffd9302 100644 --- a/pkgs/clan-cli/clan_cli/vars/check.py +++ b/pkgs/clan-cli/clan_cli/vars/check.py @@ -37,9 +37,7 @@ def check_vars(machine: Machine, generator_name: None | str = None) -> bool: log.debug(f"missing_secret_vars: {missing_secret_vars}") log.debug(f"missing_public_vars: {missing_public_vars}") - if missing_secret_vars or missing_public_vars: - return False - return True + return not (missing_secret_vars or missing_public_vars) def check_command(args: argparse.Namespace) -> None: diff --git a/pkgs/clan-cli/tests/command.py b/pkgs/clan-cli/tests/command.py index ba8d67e1c..1dfee4e14 100644 --- a/pkgs/clan-cli/tests/command.py +++ b/pkgs/clan-cli/tests/command.py @@ -1,3 +1,4 @@ +import contextlib import os import signal import subprocess @@ -46,10 +47,8 @@ class Command: # We just kill all processes as quickly as possible because we don't # care about corrupted state and want to make tests fasts. for p in reversed(self.processes): - try: + with contextlib.suppress(OSError): os.killpg(os.getpgid(p.pid), signal.SIGKILL) - except OSError: - pass @pytest.fixture diff --git a/pkgs/clan-cli/tests/test_api_dataclass_compat.py b/pkgs/clan-cli/tests/test_api_dataclass_compat.py index 55f511089..c99939662 100644 --- a/pkgs/clan-cli/tests/test_api_dataclass_compat.py +++ b/pkgs/clan-cli/tests/test_api_dataclass_compat.py @@ -48,9 +48,7 @@ def find_dataclasses_in_directory( if ( isinstance(deco, ast.Name) and deco.id == "dataclass" - ): - dataclass_files.append((file_path, node.name)) - elif ( + ) or ( isinstance(deco, ast.Call) and isinstance(deco.func, ast.Name) and deco.func.id == "dataclass" diff --git a/pkgs/clan-cli/tests/test_git.py b/pkgs/clan-cli/tests/test_git.py index 52d5a2a1a..33266292f 100644 --- a/pkgs/clan-cli/tests/test_git.py +++ b/pkgs/clan-cli/tests/test_git.py @@ -27,10 +27,9 @@ def test_commit_file(git_repo: Path) -> None: def test_commit_file_outside_git_raises_error(git_repo: Path) -> None: # create a file outside the git (a temporary file) - with tempfile.NamedTemporaryFile() as tmp: + with tempfile.NamedTemporaryFile() as tmp, pytest.raises(ClanError): # this should not fail but skip the commit - with pytest.raises(ClanError): - git.commit_file(Path(tmp.name), git_repo, "test commit") + git.commit_file(Path(tmp.name), git_repo, "test commit") def test_commit_file_not_existing_raises_error(git_repo: Path) -> None: diff --git a/pkgs/clan-cli/tests/test_history_cli.py b/pkgs/clan-cli/tests/test_history_cli.py index 662e99349..badc023df 100644 --- a/pkgs/clan-cli/tests/test_history_cli.py +++ b/pkgs/clan-cli/tests/test_history_cli.py @@ -25,7 +25,7 @@ def test_history_add( history_file = user_history_file() assert history_file.exists() - history = [HistoryEntry(**entry) for entry in json.loads(open(history_file).read())] + history = [HistoryEntry(**entry) for entry in json.loads(history_file.read_text())] assert str(history[0].flake.flake_url) == str(test_flake_with_core.path) diff --git a/pkgs/clan-cli/tests/test_modules.py b/pkgs/clan-cli/tests/test_modules.py index 0fa9a2110..e46db3a4c 100644 --- a/pkgs/clan-cli/tests/test_modules.py +++ b/pkgs/clan-cli/tests/test_modules.py @@ -33,8 +33,8 @@ def test_list_modules(test_flake_with_core: FlakeForTest) -> None: assert len(modules_info.items()) > 1 # Random test for those two modules - assert "borgbackup" in modules_info.keys() - assert "syncthing" in modules_info.keys() + assert "borgbackup" in modules_info + assert "syncthing" in modules_info @pytest.mark.impure diff --git a/pkgs/clan-cli/tests/test_secrets_cli.py b/pkgs/clan-cli/tests/test_secrets_cli.py index debc26eae..bb36af2f9 100644 --- a/pkgs/clan-cli/tests/test_secrets_cli.py +++ b/pkgs/clan-cli/tests/test_secrets_cli.py @@ -492,10 +492,13 @@ def test_secrets( "user2", ] ) - with pytest.raises(ClanError), use_key(age_keys[2].privkey, monkeypatch): + with ( + pytest.raises(ClanError), + use_key(age_keys[2].privkey, monkeypatch), + capture_output as output, + ): # user2 is not in the group anymore - with capture_output as output: - cli.run(["secrets", "get", "--flake", str(test_flake.path), "key"]) + cli.run(["secrets", "get", "--flake", str(test_flake.path), "key"]) print(output.out) cli.run( diff --git a/pkgs/clan-vm-manager/clan_vm_manager/components/vmobj.py b/pkgs/clan-vm-manager/clan_vm_manager/components/vmobj.py index c0a49343a..ac1e3d1c0 100644 --- a/pkgs/clan-vm-manager/clan_vm_manager/components/vmobj.py +++ b/pkgs/clan-vm-manager/clan_vm_manager/components/vmobj.py @@ -279,7 +279,7 @@ class VMObject(GObject.Object): if not self._log_file: try: - self._log_file = open(proc.out_file) + self._log_file = open(proc.out_file) # noqa: SIM115 except Exception as ex: log.exception(ex) self._log_file = None diff --git a/pkgs/clan-vm-manager/tests/command.py b/pkgs/clan-vm-manager/tests/command.py index ba8d67e1c..1dfee4e14 100644 --- a/pkgs/clan-vm-manager/tests/command.py +++ b/pkgs/clan-vm-manager/tests/command.py @@ -1,3 +1,4 @@ +import contextlib import os import signal import subprocess @@ -46,10 +47,8 @@ class Command: # We just kill all processes as quickly as possible because we don't # care about corrupted state and want to make tests fasts. for p in reversed(self.processes): - try: + with contextlib.suppress(OSError): os.killpg(os.getpgid(p.pid), signal.SIGKILL) - except OSError: - pass @pytest.fixture diff --git a/pkgs/moonlight-sunshine-accept/moonlight_sunshine_accept/moonlight/join.py b/pkgs/moonlight-sunshine-accept/moonlight_sunshine_accept/moonlight/join.py index 4d6802c3c..0ac104338 100644 --- a/pkgs/moonlight-sunshine-accept/moonlight_sunshine_accept/moonlight/join.py +++ b/pkgs/moonlight-sunshine-accept/moonlight_sunshine_accept/moonlight/join.py @@ -15,10 +15,7 @@ def send_join_request(host: str, port: int, cert: str) -> bool: response = send_join_request_api(host, port) if response: return response - if send_join_request_native(host, port, cert): - return True - - return False + return bool(send_join_request_native(host, port, cert)) # This is the preferred join method, but sunshines pin mechanism diff --git a/pkgs/moonlight-sunshine-accept/moonlight_sunshine_accept/moonlight/state.py b/pkgs/moonlight-sunshine-accept/moonlight_sunshine_accept/moonlight/state.py index 2a98fd91a..11a8ee3d3 100644 --- a/pkgs/moonlight-sunshine-accept/moonlight_sunshine_accept/moonlight/state.py +++ b/pkgs/moonlight-sunshine-accept/moonlight_sunshine_accept/moonlight/state.py @@ -1,3 +1,4 @@ +import contextlib import os import random import string @@ -72,10 +73,8 @@ def write_state(data: ConfigParser) -> bool: def add_sunshine_host_to_parser( config: ConfigParser, hostname: str, manual_host: str, certificate: str, uuid: str ) -> bool: - try: + with contextlib.suppress(DuplicateSectionError): config.add_section("hosts") - except DuplicateSectionError: - pass # amount of hosts try: diff --git a/pyproject.toml b/pyproject.toml index 4ea0e0668..7dd764334 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -33,6 +33,7 @@ lint.select = [ "RET", "RSE", "RUF", + "SIM", "SLF", "SLOT", "T10", @@ -40,4 +41,17 @@ lint.select = [ "U", "YTT", ] -lint.ignore = ["E501", "E402", "E731", "ANN101", "ANN401", "A003", "RET504", "PT001", "PT023"] +lint.ignore = [ + "A003", + "ANN101", + "ANN401", + "E402", + "E501", + "E731", + "PT001", + "PT023", + "RET504", + "SIM102", + "SIM108", + "SIM112", +]