Files
computer-playbook/cli/deploy/development/down.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

84 lines
2.4 KiB
Python

from __future__ import annotations
import argparse
import os
import shutil
import subprocess
from pathlib import Path
from .common import cache_env_overrides, compose_file_args, resolve_distro
from .profile import Profile
from . import PROJECT_ROOT
CI_DOCKER_ROOT = Path("/mnt/docker")
CI_DOCKER_ROOT_STR = str(CI_DOCKER_ROOT)
def _base_env(*, distro: str) -> dict[str, str]:
env = dict(os.environ)
env["INFINITO_DISTRO"] = distro
env.update(cache_env_overrides())
return env
def _compose_run(*, repo_root: Path, distro: str, args: list[str]) -> None:
cmd = ["docker", "compose", "--env-file", "env.ci"]
env_development = repo_root / "env.development"
if env_development.exists():
cmd += ["--env-file", "env.development"]
cmd += compose_file_args()
cmd += Profile().args()
cmd += list(args)
env = _base_env(distro=distro)
env.setdefault("NIX_CONFIG", "")
subprocess.run(cmd, cwd=repo_root, env=env, check=True, text=True)
def _cleanup_docker_root() -> None:
docker_root = CI_DOCKER_ROOT
if os.environ.get("RUNNING_ON_GITHUB") != "true":
print(f">>> Not on GitHub - No bind volumes will be deleted: {docker_root}")
return
docker_root_env = os.environ.get("INFINITO_DOCKER_VOLUME", "").strip().rstrip("/")
if docker_root_env and docker_root_env != CI_DOCKER_ROOT_STR:
raise RuntimeError(
"SECURITY VIOLATION: "
f"INFINITO_DOCKER_VOLUME={docker_root_env} is not allowed on GitHub runner. "
f"Only {CI_DOCKER_ROOT_STR} is permitted."
)
if not docker_root.exists():
print(f">>> Docker root does not exist, nothing to clean: {docker_root}")
return
print(f">>> CI cleanup: wiping Docker root: {docker_root}")
shutil.rmtree(docker_root, ignore_errors=True)
docker_root.mkdir(parents=True, exist_ok=True)
def down_stack(*, repo_root: Path, distro: str) -> None:
print(">>> Stopping compose stack and removing volumes")
try:
_compose_run(
repo_root=repo_root,
distro=distro,
args=["down", "--remove-orphans", "-v"],
)
finally:
_cleanup_docker_root()
def add_parser(sub: argparse._SubParsersAction) -> None:
p = sub.add_parser("down", help="Stop compose stack and remove volumes.")
p.set_defaults(_handler=handler)
def handler(args: argparse.Namespace) -> int:
down_stack(repo_root=PROJECT_ROOT, distro=resolve_distro())
return 0