RET504: fix

This commit is contained in:
Jörg Thalheim
2025-08-26 15:25:38 +02:00
parent fb2fe36c87
commit d5b09f18ed
27 changed files with 42 additions and 95 deletions

View File

@@ -39,8 +39,7 @@ def generate_ula_prefix(instance_name: str) -> ipaddress.IPv6Network:
prefix = f"fd{prefix_bits:08x}"
prefix_formatted = f"{prefix[:4]}:{prefix[4:8]}::/40"
network = ipaddress.IPv6Network(prefix_formatted)
return network
return ipaddress.IPv6Network(prefix_formatted)
def generate_controller_subnet(
@@ -60,9 +59,7 @@ def generate_controller_subnet(
# The controller subnet is at base_prefix:controller_id::/56
base_int = int(base_network.network_address)
controller_subnet_int = base_int | (controller_id << (128 - 56))
controller_subnet = ipaddress.IPv6Network((controller_subnet_int, 56))
return controller_subnet
return ipaddress.IPv6Network((controller_subnet_int, 56))
def generate_peer_suffix(peer_name: str) -> str:
@@ -76,8 +73,7 @@ def generate_peer_suffix(peer_name: str) -> str:
suffix_bits = h[:16]
# Format as IPv6 suffix without leading colon
suffix = f"{suffix_bits[0:4]}:{suffix_bits[4:8]}:{suffix_bits[8:12]}:{suffix_bits[12:16]}"
return suffix
return f"{suffix_bits[0:4]}:{suffix_bits[4:8]}:{suffix_bits[8:12]}:{suffix_bits[12:16]}"
def main() -> None:

View File

@@ -551,8 +551,7 @@ def options_docs_from_tree(
return output
md = render_tree(root)
return md
return render_tree(root)
if __name__ == "__main__":

View File

@@ -324,14 +324,13 @@ class Machine:
# Always run command with shell opts
command = f"set -eo pipefail; source /etc/profile; set -xu; {command}"
proc = subprocess.run(
return subprocess.run(
self.nsenter_command(command),
timeout=timeout,
check=False,
stdout=subprocess.PIPE,
text=True,
)
return proc
def nested(
self,

View File

@@ -73,8 +73,7 @@ def complete_machines(
if thread.is_alive():
return iter([])
machines_dict = dict.fromkeys(machines, "machine")
return machines_dict
return dict.fromkeys(machines, "machine")
def complete_services_for_machine(
@@ -118,8 +117,7 @@ def complete_services_for_machine(
if thread.is_alive():
return iter([])
services_dict = dict.fromkeys(services, "service")
return services_dict
return dict.fromkeys(services, "service")
def complete_backup_providers_for_machine(
@@ -162,8 +160,7 @@ def complete_backup_providers_for_machine(
if thread.is_alive():
return iter([])
providers_dict = dict.fromkeys(providers, "provider")
return providers_dict
return dict.fromkeys(providers, "provider")
def complete_state_services_for_machine(
@@ -206,8 +203,7 @@ def complete_state_services_for_machine(
if thread.is_alive():
return iter([])
providers_dict = dict.fromkeys(providers, "service")
return providers_dict
return dict.fromkeys(providers, "service")
def complete_secrets(
@@ -225,8 +221,7 @@ def complete_secrets(
secrets = list_secrets(Flake(flake).path)
secrets_dict = dict.fromkeys(secrets, "secret")
return secrets_dict
return dict.fromkeys(secrets, "secret")
def complete_users(
@@ -244,8 +239,7 @@ def complete_users(
users = list_users(Path(flake))
users_dict = dict.fromkeys(users, "user")
return users_dict
return dict.fromkeys(users, "user")
def complete_groups(
@@ -264,8 +258,7 @@ def complete_groups(
groups_list = list_groups(Path(flake))
groups = [group.name for group in groups_list]
groups_dict = dict.fromkeys(groups, "group")
return groups_dict
return dict.fromkeys(groups, "group")
def complete_templates_disko(
@@ -285,8 +278,7 @@ def complete_templates_disko(
disko_template_list = list_all_templates.builtins.get("disko")
if disko_template_list:
disko_templates = list(disko_template_list)
disko_dict = dict.fromkeys(disko_templates, "disko")
return disko_dict
return dict.fromkeys(disko_templates, "disko")
return []
@@ -307,8 +299,7 @@ def complete_templates_clan(
clan_template_list = list_all_templates.builtins.get("clan")
if clan_template_list:
clan_templates = list(clan_template_list)
clan_dict = dict.fromkeys(clan_templates, "clan")
return clan_dict
return dict.fromkeys(clan_templates, "clan")
return []
@@ -350,8 +341,7 @@ def complete_vars_for_machine(
except (OSError, PermissionError):
pass
vars_dict = dict.fromkeys(vars_list, "var")
return vars_dict
return dict.fromkeys(vars_list, "var")
def complete_target_host(
@@ -392,8 +382,7 @@ def complete_target_host(
if thread.is_alive():
return iter([])
providers_dict = dict.fromkeys(target_hosts, "target_host")
return providers_dict
return dict.fromkeys(target_hosts, "target_host")
def complete_tags(
@@ -462,8 +451,7 @@ def complete_tags(
if any(thread.is_alive() for thread in threads):
return iter([])
providers_dict = dict.fromkeys(tags, "tag")
return providers_dict
return dict.fromkeys(tags, "tag")
def add_dynamic_completer(

View File

@@ -10,7 +10,7 @@ from clan_lib.ssh.remote import Remote
@pytest.fixture
def hosts(sshd: Sshd) -> list[Remote]:
login = pwd.getpwuid(os.getuid()).pw_name
group = [
return [
Remote(
address="127.0.0.1",
port=sshd.port,
@@ -20,5 +20,3 @@ def hosts(sshd: Sshd) -> list[Remote]:
command_prefix="local_test",
),
]
return group

View File

@@ -164,13 +164,12 @@ class SecretStore(StoreBase):
msg = f"file {file_name} was not found"
raise ClanError(msg)
if outdated:
msg = (
return (
"The local state of some secret vars is inconsistent and needs to be updated.\n"
f"Run 'clan vars fix {machine}' to apply the necessary changes."
"Problems to fix:\n"
"\n".join(o[2] for o in outdated if o[2])
)
return msg
return None
def _set(

View File

@@ -279,8 +279,7 @@ API.register(get_system_file)
param = sig.parameters.get(arg_name)
if param:
param_class = param.annotation
return param_class
return param.annotation
return None

View File

@@ -105,9 +105,7 @@ def list_system_services_mdns() -> DNSInfo:
],
)
proc = run(cmd)
data = parse_avahi_output(proc.stdout)
return data
return parse_avahi_output(proc.stdout)
def mdns_command(_args: argparse.Namespace) -> None:

View File

@@ -37,9 +37,7 @@ def inspect_dataclass_fields(t: type) -> dict[TypeVar, type]:
type_params = origin.__parameters__
# Create a map from type parameters to actual type arguments
type_map = dict(zip(type_params, type_args, strict=False))
return type_map
return dict(zip(type_params, type_args, strict=False))
def apply_annotations(schema: dict[str, Any], annotations: list[Any]) -> dict[str, Any]:

View File

@@ -82,9 +82,7 @@ class PrefixFormatter(logging.Formatter):
self.hostnames += [hostname]
index = self.hostnames.index(hostname)
coloroffset = (index + self.hostname_color_offset) % len(colorcodes)
colorcode = colorcodes[coloroffset]
return colorcode
return colorcodes[coloroffset]
def get_callers(start: int = 2, end: int = 2) -> list[str]:

View File

@@ -530,10 +530,9 @@ class FlakeCacheEntry:
msg = f"Expected dict for ALL selector caching, got {type(self.value)}"
raise ClanError(msg)
if self.fetched_all:
result = all(
return all(
self.value[sel].is_cached(selectors[1:]) for sel in self.value
)
return result
return False
if (
selector.type == SelectorType.SET
@@ -724,13 +723,12 @@ class FlakeCacheEntry:
exists = json_data.get("exists", True)
fetched_all = json_data.get("fetched_all", False)
entry = FlakeCacheEntry(
return FlakeCacheEntry(
value=value,
is_list=is_list,
exists=exists,
fetched_all=fetched_all,
)
return entry
def __repr__(self) -> str:
if isinstance(self.value, dict):
@@ -1087,8 +1085,7 @@ class Flake:
else:
log.debug(f"$ clan select {shlex.quote(selector)}")
value = self._cache.select(selector)
return value
return self._cache.select(selector)
def select_machine(self, machine_name: str, selector: str) -> Any:
"""Select a nix attribute for a specific machine.

View File

@@ -47,9 +47,7 @@ def configured_log_manager(base_dir: Path) -> LogManager:
clans_config = LogGroupConfig("clans", "Clans")
machines_config = LogGroupConfig("machines", "Machines")
clans_config = clans_config.add_child(machines_config)
log_manager = log_manager.add_root_group_config(clans_config)
return log_manager
return log_manager.add_root_group_config(clans_config)
class TestLogGroupConfig:

View File

@@ -133,8 +133,7 @@ class Machine:
remote = get_machine_host(self.name, self.flake, field="buildHost")
if remote:
data = remote.data
return data
return remote.data
return None

View File

@@ -65,12 +65,11 @@ class Network:
@cached_property
def module(self) -> "NetworkTechnologyBase":
res = import_with_source(
return import_with_source(
self.module_name,
"NetworkTechnology",
NetworkTechnologyBase, # type: ignore[type-abstract]
)
return res
def is_running(self) -> bool:
return self.module.is_running()

View File

@@ -103,8 +103,7 @@ def nix_eval(flags: list[str]) -> list[str]:
def nix_metadata(flake_url: str | Path) -> dict[str, Any]:
cmd = nix_command(["flake", "metadata", "--json", f"{flake_url}"])
proc = run(cmd)
data = json.loads(proc.stdout)
return data
return json.loads(proc.stdout)
# lazy loads list of allowed and static programs

View File

@@ -151,9 +151,7 @@ class InventoryStore:
)
else:
filtered = cast("InventorySnapshot", raw_value)
sanitized = sanitize(filtered, self._allowed_path_transforms, [])
return sanitized
return sanitize(filtered, self._allowed_path_transforms, [])
def get_readonly_raw(self) -> Inventory:
attrs = "{" + ",".join(self._keys) + "}"

View File

@@ -138,8 +138,7 @@ def list_difference(all_items: list, filter_items: list) -> list:
def find_duplicates(string_list: list[str]) -> list[str]:
count = Counter(string_list)
duplicates = [item for item, freq in count.items() if freq > 1]
return duplicates
return [item for item, freq in count.items() if freq > 1]
def find_deleted_paths(

View File

@@ -10,7 +10,7 @@ from tempfile import NamedTemporaryFile
def create_sandbox_profile() -> str:
"""Create a sandbox profile that allows access to tmpdir and nix store, based on Nix's sandbox-defaults.sb."""
# Based on Nix's sandbox-defaults.sb implementation with TMPDIR parameter
profile_content = """(version 1)
return """(version 1)
(define TMPDIR (param "_TMPDIR"))
@@ -92,8 +92,6 @@ def create_sandbox_profile() -> str:
(allow process-exec (literal "/usr/bin/env"))
"""
return profile_content
@contextmanager
def sandbox_exec_cmd(generator: str, tmpdir: Path) -> Iterator[list[str]]:

View File

@@ -24,8 +24,7 @@ def list_service_instances(flake: Flake) -> InventoryInstancesType:
"""Returns all currently present service instances including their full configuration"""
inventory_store = InventoryStore(flake)
inventory = inventory_store.read()
instances = inventory.get("instances", {})
return instances
return inventory.get("instances", {})
def collect_tags(machines: InventoryMachinesType) -> set[str]:

View File

@@ -20,9 +20,7 @@ def create_secret_key_nixos_anywhere() -> SSHKeyPair:
"""
private_key_dir = user_nixos_anywhere_dir()
key_pair = generate_ssh_key(private_key_dir)
return key_pair
return generate_ssh_key(private_key_dir)
def generate_ssh_key(root_dir: Path) -> SSHKeyPair:

View File

@@ -51,7 +51,7 @@ def test_list_inventory_tags(clan_flake: Callable[..., Flake]) -> None:
inventory_store.write(inventory, message="Test add tags via API")
# Check that the tags were updated
persisted = inventory_store._get_persisted() # noqa: SLF001
persisted = inventory_store._get_persisted()
assert get_value_by_path(persisted, "machines.jon.tags", []) == new_tags
tags = list_tags(flake)

View File

@@ -135,16 +135,14 @@ def indent_next(text: str, indent_size: int = 4) -> str:
"""
indent = " " * indent_size
lines = text.split("\n")
indented_text = lines[0] + ("\n" + indent).join(lines[1:])
return indented_text
return lines[0] + ("\n" + indent).join(lines[1:])
def indent_all(text: str, indent_size: int = 4) -> str:
"""Indent all lines in a string."""
indent = " " * indent_size
lines = text.split("\n")
indented_text = indent + ("\n" + indent).join(lines)
return indented_text
return indent + ("\n" + indent).join(lines)
def get_subcommands(

View File

@@ -138,6 +138,4 @@ def spawn(
proc.start()
# Return the process
mp_proc = MPProcess(name=proc_name, proc=proc, out_file=out_file)
return mp_proc
return MPProcess(name=proc_name, proc=proc, out_file=out_file)

View File

@@ -181,8 +181,7 @@ class ClanStore:
if vm_store is None:
return None
vm = vm_store.get(str(machine.name), None)
return vm
return vm_store.get(str(machine.name), None)
def get_running_vms(self) -> list[VMObject]:
return [

View File

@@ -48,8 +48,7 @@ def list_devshells() -> list[str]:
stdout=subprocess.PIPE,
check=True,
)
names = json.loads(flake_show.stdout.decode())
return names
return json.loads(flake_show.stdout.decode())
def print_devshells() -> None:

View File

@@ -58,9 +58,7 @@ def compute_member_id(ipv6_addr: str) -> str:
node_id_bytes = addr_bytes[10:16]
node_id = int.from_bytes(node_id_bytes, byteorder="big")
member_id = format(node_id, "x").zfill(10)[-10:]
return member_id
return format(node_id, "x").zfill(10)[-10:]
# this is managed by the nixos module

View File

@@ -45,7 +45,6 @@ lint.ignore = [
"PLR2004",
"PT001",
"PT023",
"RET504",
"RUF100",
"S603",
"S607",