Files
computer-playbook/tasks/utils/migrate_meta_layout/indices.py
T
kevinveenbirkenbachandClaude Opus 4.7 7dc6d6e491 chore(ruff): enable TC + N rules
TC (flake8-type-checking): typing-only imports moved into
``if TYPE_CHECKING:`` blocks across 8 source files via auto-fix
(117 hits). Reduces runtime import surface and rules out circular
imports for type-only deps. Project-wide ``from __future__ import
annotations`` (FA, already enabled) keeps annotations as strings,
so the moved imports never need to load at runtime.

N (pep8-naming): 32 hits handled.

Renames (semantic + lint):
- ``isSmallerThenMaximumBackupSize`` -> ``is_larger_than_maximum_backup_size``
  (snake_case + fixes both the typo "Then -> Than" and the
  semantic mismatch: the function returns ``current > maximum``)
- ``isDirectoryDeletable`` / ``deleteVersion`` /
  ``getAmountOfIteration`` / ``deleteIteration`` -> snake_case
- 8 test functions with ALL-CAPS env-var fragments
  (``test_..._DOMAIN_PRIMARY_...`` etc.) -> snake_case
- Mock alias ``VH`` -> ``vh`` in test_host_vars.py

Exception class renames (``N818`` Error suffix):
- ``TimeLimitExceededException`` -> ``TimeLimitExceededError``
- ``AttemptException`` -> ``AttemptError``
- ``PathNotFound`` -> ``PathNotFoundError`` (propagated across
  4 callers under tests/integration/lookups/config/)
- ``_ExitJson`` / ``_FailJson`` -> ``*_Error``

Refactor:
- ``METADATA = {...}`` local constant in two functions of
  ``plugins/filter/invokable_paths.py`` lifted to module-level
  ``_METADATA_KEYS``.
- ``from typing import TYPE_CHECKING`` in
  ``tasks/utils/migrate_meta_layout/__main__.py`` moved above
  the ``sys.path.insert`` hack to satisfy E402 (collateral from
  the TC auto-fix that landed it after the path mutation).

Per-file ignores in pyproject.toml for the legitimate cases the
rule cannot accept:
- ``pull-specific-host.py`` -> ``N999`` (Ansible-invoked role-level
  script, hyphenated filename pinned by the surrounding stack).
- 4 matrix-deploy files -> ``N806`` for the ``include_R`` /
  ``raw_include_R`` round-index notation; the uppercase ``R``
  here mirrors the formula in the docstring rather than naming
  a constant.
- ``plugins/filter/value_generator.py`` -> ``N806`` for the
  lazy-loaded class binding ``ValueGenerator =
  _value_generator_cls()``, which retains the imported class
  identifier per PEP 8.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 18:57:07 +02:00

113 lines
4.0 KiB
Python

from __future__ import annotations
from functools import cache
from typing import TYPE_CHECKING, Any
from utils.roles.entity_name import get_entity_name
from . import yaml_io
if TYPE_CHECKING:
from pathlib import Path
def build_network_index(networks_file: Path) -> dict[str, dict[str, Any]]:
networks = yaml_io.load(networks_file) or {}
raw = networks.get("defaults_networks", {}) if isinstance(networks, dict) else {}
local = raw.get("local", {}) if isinstance(raw, dict) else {}
if not isinstance(local, dict):
return {}
result: dict[str, dict[str, Any]] = {}
for role_name, value in local.items():
if isinstance(value, str):
result[role_name] = {"subnet": value}
elif isinstance(value, dict):
entry: dict[str, Any] = {}
for k in ("subnet", "dns_resolver"):
if k in value:
entry[k] = value[k]
if entry:
result[role_name] = entry
return result
def build_port_index(
ports_file: Path, roles_dir: Path
) -> tuple[
dict[str, dict[str, dict[str, Any]]],
dict[str, dict[str, dict[str, int]]],
]:
"""Return ``(ports_for_role, relays_for_role)`` indexed by role -> entity."""
ports_doc = yaml_io.load(ports_file) or {}
ports_root = ports_doc.get("ports", {}) if isinstance(ports_doc, dict) else {}
if not isinstance(ports_root, dict):
return {}, {}
ports_for_role: dict[str, dict[str, dict[str, Any]]] = {}
relays_for_role: dict[str, dict[str, dict[str, int]]] = {}
for scope in ("localhost", "public"):
scope_block = ports_root.get(scope, {})
if not isinstance(scope_block, dict):
continue
scope_label = "local" if scope == "localhost" else "public"
for category, entries in scope_block.items():
if category == "relay_port_ranges":
_absorb_relays(entries, relays_for_role, roles_dir)
continue
if not isinstance(entries, dict):
continue
for combined_key, port_value in entries.items():
if not isinstance(port_value, int):
continue
role_name, entity = _split_role_and_entity(combined_key, roles_dir)
entity_key = entity or get_entity_name(role_name) or role_name
role_ports = ports_for_role.setdefault(role_name, {})
entity_ports = role_ports.setdefault(entity_key, {})
scope_map = entity_ports.setdefault(scope_label, {})
scope_map[category] = port_value
return ports_for_role, relays_for_role
def _absorb_relays(
entries: Any,
relays_for_role: dict[str, dict[str, dict[str, int]]],
roles_dir: Path,
) -> None:
if not isinstance(entries, dict):
return
for combined_key, port_value in entries.items():
if not isinstance(port_value, int):
continue
if combined_key.endswith("_start"):
base, kind = combined_key[: -len("_start")], "start"
elif combined_key.endswith("_end"):
base, kind = combined_key[: -len("_end")], "end"
else:
continue
role_name, entity = _split_role_and_entity(base, roles_dir)
entity_key = entity or get_entity_name(role_name) or role_name
role_relays = relays_for_role.setdefault(role_name, {})
role_relays.setdefault(entity_key, {})[kind] = port_value
def _split_role_and_entity(
combined_key: str, roles_dir: Path
) -> tuple[str, str | None]:
"""Return ``(role_name, entity_or_None)`` for a `09_ports.yml` key."""
known = _all_role_names(roles_dir)
if combined_key in known:
return combined_key, None
if "_" in combined_key:
prefix, suffix = combined_key.rsplit("_", 1)
if prefix in known:
return prefix, suffix
return combined_key, None
@cache
def _all_role_names(roles_dir: Path) -> frozenset[str]:
return frozenset(child.name for child in roles_dir.iterdir() if child.is_dir())