Files
computer-playbook/cli/deploy/development/common.py
T
kevinveenbirkenbachandClaude Opus 4.7 9f62f9bb0e refactor(repo): clear all project-root-import lint violations + helper inlining
Eliminates the last 102 violations of test_project_root_import by
making PROJECT_ROOT in each package's __init__.py the single source
and inlining every wrapper helper.

Migrations
==========
- ~70 files: ``Path(__file__).resolve().parents[N]`` → ``from <pkg>
  import PROJECT_ROOT`` (single-expression shape, scripted).
- ~12 files: two-statement helpers (``T = Path(__file__).resolve();
  R = T.parents[N]``) and multi-line ``os.path.abspath(os.path.join(...
  os.pardir...))`` chains rewritten by a follow-up scripted pass.
- ~20 files migrated by hand for shapes the scripts couldn't safely
  rewrite (helper functions like ``_repo_root_from_test_file``,
  embedded ``os.pardir`` chains, etc.).

Helpers removed (inlined to PROJECT_ROOT)
=========================================
- All ``def repo_root_from_here() / _project_root_from_here()`` and
  same-shape variants in cli/ (``cli/deploy/development/{down,common,
  build,deploy}.py``, ``cli/meta/categories/invokable/command.py``,
  ``cli/meta/applications/resolution/{combined/repo_paths,
  dependencies/__main__,run_after/__main__}.py``).
- All zero-arg ``def <name>() -> Path: return PROJECT_ROOT`` helpers
  (utils/invokable.py, utils/roles/resource_validation.py, cli/meta/
  runtime/__init__.py, cli/meta/callorder/__main__.py, plus a dozen
  test files).
- 4 ``PROJECT_ROOT = PROJECT_ROOT`` self-assignments removed from
  test files where the class attribute became dead after migration.

Test-mock updates
=================
``patch.object(repo_paths, 'repo_root_from_here', return_value=ROOT)``
→ ``patch.object(repo_paths, 'PROJECT_ROOT', ROOT)`` (27 patches across
8 unit-test files); same shape for ``patch('utils.invokable._repo_root',
return_value=…)``.

Suppressions documented
=======================
5 files marked ``# nocheck: project-root-import`` for the catalog's
documented exemptions:
- 2 lints walking from a discovered glob match (<role>/templates/...)
  up to its role dir, NOT the repo root.
- ``cli/validate/inventory/__main__.py`` invoked as standalone
  subprocess (relative imports unavailable).
- ``plugins/filter/value_generator.py`` loaded by Ansible outside the
  project package (relative imports broken).
- ``roles/test-e2e-playwright/filter_plugins/discover_playwright_roles.py``.

Bugs surfaced and fixed in the same commit
==========================================
The migration uncovered two latent role-content violations that were
silently masked by buggy ``_repo_root()`` helpers in two integration
tests (the helpers walked upward looking for marker dirs and returned
``tests/integration/`` instead of the repo root, so the tests scanned
nothing under ``roles/`` for years):
- roles/web-app-minio: extracted 6-task OIDC block into 02_oidc.yml +
  ``include_tasks`` (the documented "Good" pattern from
  test_block_size; parsing cost is paid only when OIDC is enabled).
- roles/web-app-bluesky/tasks/01_core.yml: collapsed 3 sequential
  ``when: BLUESKY_WEB_ENABLED | bool`` tasks into one ``block:`` with
  the guard at block level (4 → 2 occurrences, under threshold).

Two semantic-bug fixes carried alongside
========================================
- cli/core/app.py: ``cli_dir`` was previously ``parents[1]`` (= cli/),
  not the repo root; rewritten to ``PROJECT_ROOT / "cli"`` to match
  the variable's intent.
- cli/make/__main__.py: pre-existing bug — ``repo_root`` was actually
  the ``cli/`` directory (so ``cli/Makefile`` was the search target,
  which never existed). Now correctly uses PROJECT_ROOT.
- scripts/lint/sort_claude_settings.sh: invokes utils/claude/
  settings_sort.py as a module (``python -m``) so its
  ``from . import PROJECT_ROOT`` resolves.

Verification
============
- ``ruff check .`` → clean
- ``tests.lint.repository.test_project_root_import`` → OK (102 → 0)
- 1621 unit tests → all pass
- Integration suite: 44 failures (baseline, pre-existing, none from
  this commit), 1 skipped

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

107 lines
3.6 KiB
Python

from __future__ import annotations
import os
from typing import TYPE_CHECKING
from .deps import apps_with_deps, resolve_run_after
from . import PROJECT_ROOT
if TYPE_CHECKING:
from .compose import Compose
# Mirrors INVENTORY_VARS_FILE from scripts/meta/env/inventory.sh; a unit
# test locks the two literals together so they cannot drift.
DEV_INVENTORY_VARS_FILE: str = os.environ.get(
"INVENTORY_VARS_FILE", "inventories/development/default.yml"
)
VALID_DISTROS: tuple[str, ...] = ("arch", "debian", "ubuntu", "fedora", "centos")
def compose_file_args() -> list[str]:
"""Compose `-f` flags shared by up and down flows."""
from .profile import Profile
out = ["-f", "compose.yml"]
if Profile().registry_cache_active():
out += ["-f", "compose/cache.override.yml"]
return out
def cache_env_overrides() -> dict[str, str]:
"""Env vars consumed strictly by compose/cache.override.yml."""
from .profile import Profile
if not Profile().registry_cache_active():
return {}
ca_dir = os.environ.get("INFINITO_PACKAGE_CACHE_FRONTEND_CA_DIR", "").strip()
if not ca_dir:
raise SystemExit(
"INFINITO_PACKAGE_CACHE_FRONTEND_CA_DIR is not set. Source "
"scripts/meta/env/cache/package.sh (or scripts/meta/env/all.sh) "
"before invoking cli.deploy.development."
)
return {
"INFINITO_REGISTRY_CACHE_PROXY_CONF": "./compose/registry-cache/proxy.conf",
"INFINITO_PACKAGE_CACHE_PIP_CONF": "./compose/package-cache/pip.conf",
"INFINITO_PACKAGE_CACHE_NPMRC": "./compose/package-cache/npmrc",
"INFINITO_PACKAGE_CACHE_APT_LIST": "./compose/package-cache/apt.list",
"INFINITO_PACKAGE_CACHE_FRONTEND_CA_FILE": f"{ca_dir}/ca.crt",
}
def resolve_distro() -> str:
"""Return INFINITO_DISTRO; raise SystemExit if missing or invalid."""
distro = os.environ.get("INFINITO_DISTRO", "").strip()
if not distro:
raise SystemExit(
"INFINITO_DISTRO is not set. Source scripts/meta/env/defaults.sh "
"or export INFINITO_DISTRO=<arch|debian|ubuntu|fedora|centos> "
"before invoking cli.deploy.development."
)
if distro not in VALID_DISTROS:
raise SystemExit(
f"INFINITO_DISTRO={distro!r} is not a valid distro. "
f"Valid: {', '.join(VALID_DISTROS)}."
)
return distro
def resolve_container() -> str:
"""Return INFINITO_CONTAINER; raise SystemExit if unset."""
container = os.environ.get("INFINITO_CONTAINER", "").strip()
if not container:
raise SystemExit(
"INFINITO_CONTAINER is not set. Source scripts/meta/env/defaults.sh "
"before invoking cli.deploy.development."
)
return container
def make_compose() -> Compose:
from .compose import Compose
distro = resolve_distro()
# Surface env-script gap here rather than as a cryptic compose error later.
resolve_container()
return Compose(repo_root=PROJECT_ROOT, distro=distro)
def resolve_deploy_ids_for_app(compose: Compose, app_id: str) -> list[str]:
deps = resolve_run_after(compose, app_id)
return apps_with_deps(app_id, deps_role_names=deps)
def resolve_deploy_ids_for_apps(compose: Compose, app_spec: str) -> list[str]:
"""Resolve deploy ids for one or more space- or comma-separated app ids."""
app_ids = [a.strip() for a in app_spec.replace(",", " ").split() if a.strip()]
result: list[str] = []
for app_id in app_ids:
for dep in resolve_deploy_ids_for_app(compose, app_id):
if dep not in result:
result.append(dep)
return result