Files
computer-playbook/utils/valid_deploy_id.py
T
kevinveenbirkenbachandClaude Opus 4.7 26ef3ff504 chore(ruff): enable strict ruleset (E/F/I/B/UP, py311) — 2819 → 0
Adds ``[tool.ruff.lint]`` with ``select = ["E", "F", "I", "B", "UP"]``
and ``target-version = "py311"``. ``E501`` is ignored because
``ruff format`` already reflows what it can; the remaining long lines
are unsplittable string literals / URLs.

Auto-fixed (2753 issues, behavior-preserving):
- UP006/UP035: ``List[X]`` → ``list[X]``, ``Dict[X]`` → ``dict[X]``,
  ``from typing import …`` redirected where superseded by builtins.
- UP045: ``Optional[X]`` → ``X | None``.
- UP010/UP009/UP015: dropped Python-2-era pragmas (``from __future__
  import absolute_import, division, print_function``,
  ``# -*- coding: utf-8 -*-``), redundant ``open(..., "r")`` mode.
- UP004: dropped implicit ``class X(object):``.
- UP022/UP008/UP032: stdlib idiom modernization (``capture_output``,
  super-call simplification, etc.).
- B905: ``zip(...)`` → ``zip(..., strict=False)`` (preserves prior
  behavior; switching to ``strict=True`` is a separate semantic
  choice not made here).
- I001: import-block ordering.

Hand-fixed (66 issues):
- B904 × 54: appended ``from <bound>`` (when the enclosing ``except``
  binds a name) or ``from None`` (when it doesn't) so chained
  exceptions stay distinguishable from errors-during-exception-
  handling. Applied via a small AST-aware script that walked back to
  the enclosing ``except`` clause and matched the binding.
- B017 × 4: narrowed broad ``assertRaises(Exception)`` to the actual
  ``AnsibleError`` / ``AnsibleFilterError`` raised by the code under
  test.
- B023 × 2: bound captured loop variables via default args
  (``def _record(name, *, _path_real=path_real, ...)``) so each
  closure gets its own snapshot.
- B007 × 2: unused loop control variables renamed to ``_`` /
  rewritten to ``.values()``.
- UP007 × 2: ``Union[X, Y]`` → ``X | Y`` (plus dropping the now-unused
  ``from typing import Union``).
- B018 × 1: Odoo addon manifests are bare dict expressions at module
  level by design — suppressed with an inline ``# noqa: B018`` and
  rationale comment.
- UP031 × 1: printf-style format → f-string.

The 65 ``# noqa: …`` markers introduced by the auto-fixer all carry
real ruff codes (``B018``, ``E402``, ``F401``, etc.), so
``test_noqa_only_ruff_codes`` stays green.

Verification
============
- ``ruff check .`` → All checks passed
- ``ruff format --check .`` → 894 files already formatted
- ``tests.lint.repository.{test_project_root_import,
  test_no_direct_yaml_calls, test_noqa_only_ruff_codes}`` and
  ``tests.unit.utils.annotations.test_suppress`` → 20 tests OK
- 1621 unit tests → all pass
- Integration suite: 44 failures (pre-existing baseline, none from
  this change), 1 skipped.

Going forward, the new rules block regressions on E (style), F
(pyflakes), I (import order), B (likely-bug patterns), and UP
(modernization to py311) for any new code.

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

100 lines
3.2 KiB
Python

"""
Utility for validating deployment application IDs against defined roles and inventory.
"""
from __future__ import annotations
import os
from plugins.filter.get_all_application_ids import get_all_application_ids
from utils.cache.yaml import load_yaml_any
from . import PROJECT_ROOT
class ValidDeployId:
def __init__(self) -> None:
"""
Always resolve roles/ from the repository root, independent of CWD.
"""
repo_root = PROJECT_ROOT
roles_dir = repo_root / "roles"
if not roles_dir.is_dir():
raise RuntimeError(
f"roles directory not found at expected location: {roles_dir}"
)
self.roles_dir = roles_dir
self.valid_ids = set(get_all_application_ids(str(roles_dir)))
def validate(
self, inventory_path: str, ids: list[str]
) -> dict[str, dict[str, bool]]:
"""
Validate a list of application IDs against both role definitions and inventory.
Returns:
{
"app1": {"in_roles": False, "in_inventory": True},
"app2": {"in_roles": True, "in_inventory": False},
}
"""
invalid: dict[str, dict[str, bool]] = {}
for app_id in ids:
in_roles = app_id in self.valid_ids
in_inventory = self._exists_in_inventory(inventory_path, app_id)
if not (in_roles and in_inventory):
invalid[app_id] = {
"in_roles": in_roles,
"in_inventory": in_inventory,
}
return invalid
def _exists_in_inventory(self, inventory_path: str, app_id: str) -> bool:
_, ext = os.path.splitext(inventory_path)
if ext in (".yml", ".yaml"):
return self._search_yaml_keys(inventory_path, app_id)
return self._search_ini_sections(inventory_path, app_id)
def _search_ini_sections(self, inventory_path: str, app_id: str) -> bool:
with open(inventory_path, encoding="utf-8") as f:
current_section = None
for raw in f:
line = raw.strip()
if not line or line.startswith(("#", ";")):
continue
if line.startswith("[") and line.endswith("]"):
current_section = line[1:-1].strip()
if current_section == app_id:
return True
continue
if current_section:
for part in line.replace(",", " ").split():
if part.strip() == app_id:
return True
return False
def _search_yaml_keys(self, inventory_path: str, app_id: str) -> bool:
data = load_yaml_any(inventory_path, default_if_missing={})
return self._find_key(data, app_id)
def _find_key(self, node, key: str) -> bool:
if isinstance(node, dict):
for k, v in node.items():
if k == key and isinstance(v, (dict, list)):
return True
if self._find_key(v, key):
return True
elif isinstance(node, list):
for item in node:
if self._find_key(item, key):
return True
return False