mirror of
https://github.com/kevinveenbirkenbach/computer-playbook.git
synced 2026-11-14 06:37:25 +00:00
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>
109 lines
3.3 KiB
Python
109 lines
3.3 KiB
Python
from __future__ import annotations
|
|
|
|
import re
|
|
import unittest
|
|
from typing import TYPE_CHECKING, Any
|
|
|
|
from utils.cache.yaml import load_yaml_str
|
|
from utils.docker.image.ref import is_valid_image_name
|
|
from utils.roles.mapping import ROLE_FILE_META_SERVICES
|
|
|
|
from . import PROJECT_ROOT
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Iterable
|
|
from pathlib import Path
|
|
|
|
# Docker tag (version)
|
|
TAG_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9_.-]{0,127}$")
|
|
|
|
|
|
def _safe_mapping(obj: Any) -> dict[str, Any]:
|
|
return obj if isinstance(obj, dict) else {}
|
|
|
|
|
|
def _iter_role_config_files(repo_root: Path) -> list[Path]:
|
|
roles_dir = repo_root / "roles"
|
|
if not roles_dir.is_dir():
|
|
return []
|
|
return sorted(roles_dir.glob(f"*/{ROLE_FILE_META_SERVICES}"))
|
|
|
|
|
|
def _extract_services(cfg: dict[str, Any]) -> dict[str, Any]:
|
|
# Per req-008 the file root of meta/services.yml IS the services
|
|
# map (no `compose.services` wrapper).
|
|
return _safe_mapping(cfg)
|
|
|
|
|
|
def _iter_declared_fields(
|
|
services: dict[str, Any],
|
|
) -> Iterable[tuple[str, str, Any]]:
|
|
"""
|
|
Yield (service_name, field_name, value) for each declared field
|
|
where field_name ∈ {"image", "version"}.
|
|
"""
|
|
for svc_name, svc_cfg in services.items():
|
|
svc_map = _safe_mapping(svc_cfg)
|
|
for field in ("image", "version"):
|
|
if field in svc_map:
|
|
yield svc_name, field, svc_map.get(field)
|
|
|
|
|
|
def _is_valid_image(image: Any) -> bool:
|
|
return is_valid_image_name(image)
|
|
|
|
|
|
def _is_valid_version(version: Any) -> bool:
|
|
if not isinstance(version, str):
|
|
return False
|
|
version = version.strip()
|
|
if not version or " " in version:
|
|
return False
|
|
return TAG_RE.fullmatch(version) is not None
|
|
|
|
|
|
class TestDockerServicesImageVersionValid(unittest.TestCase):
|
|
def test_declared_docker_service_image_and_version_are_valid(self) -> None:
|
|
"""
|
|
Rules:
|
|
- `image` is OPTIONAL → only validated if present
|
|
- `version` is OPTIONAL → only validated if present
|
|
- No coupling required between image/version
|
|
"""
|
|
repo_root = PROJECT_ROOT
|
|
failures: list[str] = []
|
|
|
|
config_files = _iter_role_config_files(repo_root)
|
|
self.assertTrue(
|
|
config_files,
|
|
f"No role config files found under: {repo_root / 'roles' / f'*/{ROLE_FILE_META_SERVICES}'}",
|
|
)
|
|
|
|
for cfg_path in config_files:
|
|
with cfg_path.open("r", encoding="utf-8") as f:
|
|
data = load_yaml_str(f) or {}
|
|
|
|
cfg = _safe_mapping(data)
|
|
services = _extract_services(cfg)
|
|
|
|
for svc_name, field, value in _iter_declared_fields(services):
|
|
if field == "image" and not _is_valid_image(value):
|
|
failures.append(
|
|
f"{cfg_path}: services.{svc_name}.image invalid: {value!r}"
|
|
)
|
|
|
|
if field == "version" and not _is_valid_version(value):
|
|
failures.append(
|
|
f"{cfg_path}: services.{svc_name}.version invalid: {value!r}"
|
|
)
|
|
|
|
if failures:
|
|
self.fail(
|
|
"Invalid services image/version entries found:\n"
|
|
+ "\n".join(f"- {x}" for x in failures)
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|