From efacb56985b7cbfe47d8ff7ae817b147e879e52f Mon Sep 17 00:00:00 2001 From: Kevin Veen-Birkenbach Date: Fri, 8 May 2026 16:04:56 +0200 Subject: [PATCH] refactor(cli): retire one-shot fix tools, move docker version updater MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Drop four one-shot or now-redundant tools from cli/fix/: * vars_main_files — bulk-created vars/main.yml with application_id per role-prefix during the SPOT migration. The schema is now enforced declaratively by tests/integration/roles/applications/id/ test_matches_role_name.py and the role-mapping SPOT lint. * move_unnecessary_dependencies — moved meta dependencies to guarded include_role on first sweep. Permanent enforcement lives in tests/integration/roles/meta/dependencies/test_unnecessary.py. * tabs — replaced literal tab characters with two-space indentation in YAML files. Autoformat covers new occurrences. * ini_py — generic helper that filled missing __init__.py files; new packages now ship them from the start. Move the remaining (still-actively-used) docker version updater out from under cli/fix/ and into cli/contributing/, where the recurring maintenance tooling lives: * cli/fix/docker_image_versions → cli/contributing/docker/update_versions Update the corresponding wiring: * scripts/github/update_docker_image_versions.sh now calls python -m cli.contributing.docker.update_versions (the entry point invoked daily by .github/workflows/update.yml). * docs/requirements/008-role-meta-layout.md references the new path. * PROJECT_ROOT in __init__.py drops one parents[] level (the package sits one folder deeper now). cli/fix/ is fully removed; new contributor-facing tooling belongs under cli/contributing/. Co-Authored-By: Claude Opus 4.7 (1M context) --- cli/contributing/docker/__init__.py | 0 .../docker/update_versions}/__init__.py | 2 +- .../docker/update_versions}/__main__.py | 0 cli/fix/__init__.py | 1 - cli/fix/ini_py/__init__.py | 14 -- cli/fix/ini_py/__main__.py | 50 ----- .../move_unnecessary_dependencies/__init__.py | 10 - .../move_unnecessary_dependencies/__main__.py | 159 ---------------- .../move_unnecessary_dependencies/analysis.py | 175 ------------------ .../move_unnecessary_dependencies/apply.py | 107 ----------- .../move_unnecessary_dependencies/yaml_io.py | 96 ---------- cli/fix/tabs/__init__.py | 14 -- cli/fix/tabs/__main__.py | 61 ------ cli/fix/vars_main_files/__init__.py | 32 ---- cli/fix/vars_main_files/__main__.py | 104 ----------- docs/requirements/008-role-meta-layout.md | 2 +- .../github/update_docker_image_versions.sh | 2 +- tests/unit/cli/fix/test_vars_main_files.py | 86 --------- 18 files changed, 3 insertions(+), 912 deletions(-) create mode 100644 cli/contributing/docker/__init__.py rename cli/{fix/docker_image_versions => contributing/docker/update_versions}/__init__.py (61%) rename cli/{fix/docker_image_versions => contributing/docker/update_versions}/__main__.py (100%) delete mode 100644 cli/fix/__init__.py delete mode 100644 cli/fix/ini_py/__init__.py delete mode 100755 cli/fix/ini_py/__main__.py delete mode 100644 cli/fix/move_unnecessary_dependencies/__init__.py delete mode 100755 cli/fix/move_unnecessary_dependencies/__main__.py delete mode 100644 cli/fix/move_unnecessary_dependencies/analysis.py delete mode 100644 cli/fix/move_unnecessary_dependencies/apply.py delete mode 100644 cli/fix/move_unnecessary_dependencies/yaml_io.py delete mode 100644 cli/fix/tabs/__init__.py delete mode 100755 cli/fix/tabs/__main__.py delete mode 100644 cli/fix/vars_main_files/__init__.py delete mode 100755 cli/fix/vars_main_files/__main__.py delete mode 100644 tests/unit/cli/fix/test_vars_main_files.py diff --git a/cli/contributing/docker/__init__.py b/cli/contributing/docker/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cli/fix/docker_image_versions/__init__.py b/cli/contributing/docker/update_versions/__init__.py similarity index 61% rename from cli/fix/docker_image_versions/__init__.py rename to cli/contributing/docker/update_versions/__init__.py index 77ffe32ea2..5f155e82ff 100644 --- a/cli/fix/docker_image_versions/__init__.py +++ b/cli/contributing/docker/update_versions/__init__.py @@ -1,5 +1,5 @@ from pathlib import Path -PROJECT_ROOT: Path = Path(__file__).resolve().parents[3] +PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] """CLI entry point package for Docker image version updates.""" diff --git a/cli/fix/docker_image_versions/__main__.py b/cli/contributing/docker/update_versions/__main__.py similarity index 100% rename from cli/fix/docker_image_versions/__main__.py rename to cli/contributing/docker/update_versions/__main__.py diff --git a/cli/fix/__init__.py b/cli/fix/__init__.py deleted file mode 100644 index 8b13789179..0000000000 --- a/cli/fix/__init__.py +++ /dev/null @@ -1 +0,0 @@ - diff --git a/cli/fix/ini_py/__init__.py b/cli/fix/ini_py/__init__.py deleted file mode 100644 index 7dd3f4d735..0000000000 --- a/cli/fix/ini_py/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Compatibility wrapper. - -This package was migrated from a flat module (ini_py.py) to a package layout: - ini_py/__main__.py contains the original implementation. - -We re-export the public API so existing imports keep working. -""" - -from __future__ import annotations - -from . import __main__ as _main - -__all__ = getattr(_main, "__all__", [n for n in dir(_main) if not n.startswith("_")]) # noqa: PLE0605 -globals().update({name: getattr(_main, name) for name in __all__}) diff --git a/cli/fix/ini_py/__main__.py b/cli/fix/ini_py/__main__.py deleted file mode 100755 index abf1a2ef00..0000000000 --- a/cli/fix/ini_py/__main__.py +++ /dev/null @@ -1,50 +0,0 @@ -#!/usr/bin/env python3 - -""" -This script creates __init__.py files in every subdirectory under the specified -folder relative to the project root. -""" - -import argparse -import os -import sys -from pathlib import Path - - -def create_init_files(root_folder): - """ - Walk through all subdirectories of root_folder and create an __init__.py file - in each directory if it doesn't already exist. - """ - for dirpath, _dirnames, _filenames in os.walk(root_folder): - init_file = str(Path(dirpath) / "__init__.py") - if not Path(init_file).exists(): - Path(init_file).open("w").close() - print(f"Created: {init_file}") - else: - print(f"Skipped (already exists): {init_file}") - - -def main(): - parser = argparse.ArgumentParser( - description="Create __init__.py files in every subdirectory." - ) - parser.add_argument( - "folder", help="Relative path to the target folder (e.g., cli/fix)" - ) - args = parser.parse_args() - - # Determine the absolute path based on the current working directory - root_folder = str(Path(args.folder).resolve()) - - if not Path(root_folder).is_dir(): - print( - f"Error: The folder '{args.folder}' does not exist or is not a directory." - ) - sys.exit(1) - - create_init_files(root_folder) - - -if __name__ == "__main__": - main() diff --git a/cli/fix/move_unnecessary_dependencies/__init__.py b/cli/fix/move_unnecessary_dependencies/__init__.py deleted file mode 100644 index 79e66648e5..0000000000 --- a/cli/fix/move_unnecessary_dependencies/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Move unnecessary meta dependencies to guarded include_role/import_role. - -Run via ``python3 -m cli.fix.move_unnecessary_dependencies``. The -implementation is split across: - -* ``__main__`` — argparse + per-role orchestration. -* ``analysis`` — provider / consumer static analysis. -* ``apply`` — YAML rewrite + include-block prepending. -* ``yaml_io`` — ruamel round-trip helpers + role-tree discovery. -""" diff --git a/cli/fix/move_unnecessary_dependencies/__main__.py b/cli/fix/move_unnecessary_dependencies/__main__.py deleted file mode 100755 index 30618bc04b..0000000000 --- a/cli/fix/move_unnecessary_dependencies/__main__.py +++ /dev/null @@ -1,159 +0,0 @@ -#!/usr/bin/env python3 -"""Move unnecessary meta dependencies to guarded include_role/import_role. - -A dependency is considered unnecessary when the consumer: - -* does NOT use provider variables in defaults/vars/handlers (no - early-var need), AND -* in tasks, any usage of provider vars or notifications of - provider handlers happens only AFTER an include/import of the - provider in the same file (or never). - -Action per qualifying role: - -* Remove the entry from ``roles//meta/main.yml``. -* Prepend a guarded include block to - ``roles//tasks/01_core.yml`` (preferred) or - ``roles//tasks/main.yml`` if the former is absent. -* When more than one dependency is moved, the include block uses a - ``loop:``. - -The heuristic mirrors -``tests/integration/test_unnecessary_role_dependencies.py``. YAML -round-trip preservation (comments, quotes, key order) is delegated -to ``ruamel.yaml`` via :mod:`.yaml_io`. Modified files get a -``.bak`` sibling. -""" - -from __future__ import annotations - -import argparse -import sys -from pathlib import Path - -from utils.roles.mapping import ROLE_FILE_META_MAIN, ROLE_FILE_TASKS_MAIN - -from .analysis import ( - collect_role_defined_vars, - collect_role_handler_names, - dependency_is_unnecessary, - parse_meta_dependencies, -) -from .apply import ( - build_include_block_yaml, - prepend_tasks, - update_meta_remove_deps, -) -from .yaml_io import ( - iter_role_dirs, - path_if_exists, - role_name_from_dir, - roles_root, -) - - -def build_providers_index( - all_roles: list[str], -) -> dict[str, tuple[set[str], set[str]]]: - return { - role_name_from_dir(rd): ( - collect_role_defined_vars(rd), - collect_role_handler_names(rd), - ) - for rd in all_roles - } - - -def process_role( - role_dir: str, - providers_index: dict[str, tuple[set[str], set[str]]], - only_role: str | None, - dry_run: bool, -) -> bool: - consumer_name = role_name_from_dir(role_dir) - if only_role and only_role != consumer_name: - return False - - meta_deps = parse_meta_dependencies(role_dir) - if not meta_deps: - return False - - moved: list[str] = [] - for producer in meta_deps: - if producer not in providers_index: - continue - pvars, phandlers = providers_index[producer] - if dependency_is_unnecessary( - role_dir, consumer_name, producer, pvars, phandlers - ): - moved.append(producer) - - if not moved: - return False - - update_meta_remove_deps( - str(Path(role_dir) / ROLE_FILE_META_MAIN), moved, dry_run=dry_run - ) - - target_tasks = path_if_exists(role_dir, "tasks/01_core.yml") or str( - Path(role_dir) / ROLE_FILE_TASKS_MAIN - ) - prepend_tasks( - target_tasks, - build_include_block_yaml(consumer_name, moved), - dry_run=dry_run, - ) - return True - - -def main() -> None: - parser = argparse.ArgumentParser( - description=( - "Move unnecessary meta dependencies to guarded include_role for " - "performance (preserve comments/quotes)." - ) - ) - parser.add_argument( - "--project-root", - # nocheck: project-root-import CLI default arg - default=str(Path(__file__).resolve().parents[3]), - help="Path to project root (default: two levels up from this script).", - ) - parser.add_argument( - "--role", - dest="only_role", - default=None, - help="Only process a specific role name (e.g., 'docker-core').", - ) - parser.add_argument( - "--dry-run", - action="store_true", - help="Analyze and print planned changes without modifying files.", - ) - args = parser.parse_args() - - roles = iter_role_dirs(args.project_root) - if not roles: - print( - f"[ERR] No roles found under {roles_root(args.project_root)}", - file=sys.stderr, - ) - sys.exit(2) - - providers_index = build_providers_index(roles) - - changed_any = False - for role_dir in roles: - if process_role(role_dir, providers_index, args.only_role, args.dry_run): - changed_any = True - - if not changed_any: - print("[OK] No unnecessary meta dependencies to move (per heuristic).") - elif args.dry_run: - print("[DRY-RUN] Completed analysis. No files were changed.") - else: - print("[OK] Finished moving unnecessary dependencies.") - - -if __name__ == "__main__": - main() diff --git a/cli/fix/move_unnecessary_dependencies/analysis.py b/cli/fix/move_unnecessary_dependencies/analysis.py deleted file mode 100644 index 6fe8313848..0000000000 --- a/cli/fix/move_unnecessary_dependencies/analysis.py +++ /dev/null @@ -1,175 +0,0 @@ -"""Static analysis helpers: provider vars/handlers + consumer scan.""" - -from __future__ import annotations - -import re -from pathlib import Path - -from utils.roles.mapping import ( - ROLE_FILE_DEFAULTS_MAIN, - ROLE_FILE_HANDLERS_MAIN, - ROLE_FILE_META_MAIN, - ROLE_FILE_VARS_MAIN, -) - -from .yaml_io import ( - gather_yaml_files, - load_yaml_rt, - path_if_exists, - read_text, -) - - -def flatten_keys(data) -> set[str]: - out: set[str] = set() - if isinstance(data, dict): - for k, v in data.items(): - if isinstance(k, str): - out.add(k) - out |= flatten_keys(v) - elif isinstance(data, list): - for item in data: - out |= flatten_keys(item) - return out - - -def collect_role_defined_vars(role_dir: str) -> set[str]: - """Vars a role 'provides': defaults/vars keys + set_fact keys in tasks.""" - provided: set[str] = set() - - for rel in (ROLE_FILE_DEFAULTS_MAIN, ROLE_FILE_VARS_MAIN): - p = path_if_exists(role_dir, rel) - if p: - provided |= flatten_keys(load_yaml_rt(p)) - - task_files = gather_yaml_files(str(Path(role_dir) / "tasks"), ["**/*.yml", "*.yml"]) - for tf in task_files: - data = load_yaml_rt(tf) - if not isinstance(data, list): - continue - for task in data: - if isinstance(task, dict) and isinstance(task.get("set_fact"), dict): - provided |= set(task["set_fact"].keys()) - - noisy = {"when", "name", "vars", "tags", "register"} - return {v for v in provided if isinstance(v, str) and v and v not in noisy} - - -def collect_role_handler_names(role_dir: str) -> set[str]: - handler_file = path_if_exists(role_dir, ROLE_FILE_HANDLERS_MAIN) - if not handler_file: - return set() - data = load_yaml_rt(handler_file) - names: set[str] = set() - if isinstance(data, list): - for task in data: - if isinstance(task, dict): - nm = task.get("name") - if isinstance(nm, str) and nm.strip(): - names.add(nm.strip()) - return names - - -def find_var_positions(text: str, varname: str) -> list[int]: - if not varname: - return [] - pattern = re.compile(rf"(? int | None: - first: int | None = None - for v in provided_vars: - for off in find_var_positions(text, v): - if first is None or off < first: - first = off - return first - - -def first_include_offset_for_role(text: str, producer_role: str) -> int | None: - pattern = re.compile( - r"(include_role|import_role)\s*:\s*\{[^}]*\bname\s*:\s*['\"]?" - + re.escape(producer_role) - + r"['\"]?[^}]*\}" - r"|" - r"(include_role|import_role)\s*:\s*\n(?:\s+[a-z_]+\s*:\s*.*\n)*\s*name\s*:\s*['\"]?" - + re.escape(producer_role) - + r"['\"]?", - re.IGNORECASE, - ) - m = pattern.search(text) - return m.start() if m else None - - -def find_notify_offsets_for_handlers(text: str, handler_names: set[str]) -> list[int]: - """For each handler name, return offsets that follow a `notify:` within ~200 chars.""" - if not handler_names: - return [] - offsets: list[int] = [] - for h in handler_names: - for m in re.finditer(re.escape(h), text): - start = m.start() - context = text[max(0, start - 200) : start] - if re.search(r"notify\s*:", context): - offsets.append(start) - return sorted(offsets) - - -def parse_meta_dependencies(role_dir: str) -> list[str]: - meta = path_if_exists(role_dir, ROLE_FILE_META_MAIN) - if not meta: - return [] - data = load_yaml_rt(meta) - raw = data.get("dependencies") - deps: list[str] = [] - if isinstance(raw, list): - for item in raw: - if isinstance(item, str): - deps.append(item) - elif isinstance(item, dict): - role = item.get("role") or item.get("name") - if role is not None: - deps.append(str(role)) - return deps - - -def dependency_is_unnecessary( - consumer_dir: str, - consumer_name: str, - producer_name: str, - provider_vars: set[str], - provider_handlers: set[str], -) -> bool: - """True iff the consumer can safely move the meta dep to a guarded include.""" - early_files = [ - p - for p in ( - path_if_exists(consumer_dir, ROLE_FILE_DEFAULTS_MAIN), - path_if_exists(consumer_dir, ROLE_FILE_VARS_MAIN), - path_if_exists(consumer_dir, ROLE_FILE_HANDLERS_MAIN), - ) - if p - ] - for p in early_files: - if first_var_use_offset_in_text(read_text(p), provider_vars) is not None: - return False - - task_files = gather_yaml_files( - str(Path(consumer_dir) / "tasks"), ["**/*.yml", "*.yml"] - ) - for p in task_files: - text = read_text(p) - if not text: - continue - include_off = first_include_offset_for_role(text, producer_name) - var_use_off = first_var_use_offset_in_text(text, provider_vars) - notify_offs = find_notify_offsets_for_handlers(text, provider_handlers) - - if var_use_off is not None and ( - include_off is None or include_off > var_use_off - ): - return False - for noff in notify_offs: - if include_off is None or include_off > noff: - return False - return True diff --git a/cli/fix/move_unnecessary_dependencies/apply.py b/cli/fix/move_unnecessary_dependencies/apply.py deleted file mode 100644 index 0d935d4cfb..0000000000 --- a/cli/fix/move_unnecessary_dependencies/apply.py +++ /dev/null @@ -1,107 +0,0 @@ -"""Apply the chosen fix: rewrite meta + prepend guarded include block.""" - -from __future__ import annotations - -from pathlib import Path - -from ruamel.yaml.comments import CommentedSeq - -from .yaml_io import dump_yaml_rt, load_yaml_rt - - -def sanitize_run_once_var(role_name: str) -> str: - return "run_once_" + role_name.replace("-", "_") - - -def build_include_block_yaml(consumer_role: str, moved_deps: list[str]) -> list[dict]: - """Guarded block prepended to tasks/01_core.yml or tasks/main.yml.""" - guard_var = sanitize_run_once_var(consumer_role) - - if len(moved_deps) == 1: - inner_tasks: list[dict] = [ - { - "name": f"Include dependency '{moved_deps[0]}'", - "include_role": {"name": moved_deps[0]}, - } - ] - else: - inner_tasks = [ - { - "name": "Include dependencies", - "include_role": {"name": "{{ item }}"}, - "loop": moved_deps, - } - ] - inner_tasks.append({"set_fact": {guard_var: True}}) - - return [ - { - "name": "Load former meta dependencies once", - "block": inner_tasks, - "when": f"{guard_var} is not defined", - } - ] - - -def prepend_tasks(tasks_path: str, new_tasks, dry_run: bool) -> None: - if Path(tasks_path).exists(): - existing = load_yaml_rt(tasks_path) - if isinstance(existing, list): - combined = CommentedSeq() - for item in new_tasks: - combined.append(item) - for item in existing: - combined.append(item) - elif isinstance(existing, dict): - combined = CommentedSeq() - for item in new_tasks: - combined.append(item) - combined.append(existing) - else: - combined = new_tasks - else: - Path(str(Path(tasks_path).parent)).mkdir(parents=True, exist_ok=True) - combined = new_tasks - - if dry_run: - print( - f"[DRY-RUN] Would write {tasks_path} with {len(new_tasks)} prepended task(s)." - ) - return - - dump_yaml_rt(combined, tasks_path) - print(f"[OK] Updated {tasks_path} (prepended {len(new_tasks)} task(s)).") - - -def update_meta_remove_deps(meta_path: str, remove: list[str], dry_run: bool) -> bool: - """Drop given entries from meta.dependencies, preserving everything else.""" - if not Path(meta_path).exists(): - return False - doc = load_yaml_rt(meta_path) - deps = doc.get("dependencies") - if not isinstance(deps, list): - return False - - keep = CommentedSeq() - removed: list[str] = [] - for item in deps: - name = item.get("role") or item.get("name") if isinstance(item, dict) else item - if name in remove: - removed.append(name) - else: - keep.append(item) - - if not removed: - return False - - if keep: - doc["dependencies"] = keep - elif "dependencies" in doc: - del doc["dependencies"] - - if dry_run: - print(f"[DRY-RUN] Would rewrite {meta_path}; removed: {', '.join(removed)}") - return True - dump_yaml_rt(doc, meta_path) - print(f"[OK] Rewrote {meta_path}; removed: {', '.join(removed)}") - return True diff --git a/cli/fix/move_unnecessary_dependencies/yaml_io.py b/cli/fix/move_unnecessary_dependencies/yaml_io.py deleted file mode 100644 index db93470137..0000000000 --- a/cli/fix/move_unnecessary_dependencies/yaml_io.py +++ /dev/null @@ -1,96 +0,0 @@ -"""YAML round-trip + role-discovery helpers shared across the fix package.""" - -from __future__ import annotations - -import glob -import logging -import os -import shutil -import sys -from pathlib import Path - -logger = logging.getLogger(__name__) - -try: - from ruamel.yaml import YAML - from ruamel.yaml.comments import CommentedMap - from ruamel.yaml.scalarstring import SingleQuotedScalarString - - _HAVE_RUAMEL = True -except Exception: - _HAVE_RUAMEL = False - -if not _HAVE_RUAMEL: - logger.error( - "ruamel.yaml is required to preserve comments/quotes. " - "Install with: pip install ruamel.yaml" - ) - sys.exit(3) - -yaml_rt = YAML() -yaml_rt.preserve_quotes = True -yaml_rt.width = 10**9 - - -def backup(path: str) -> None: - if Path(path).exists(): - shutil.copy2(path, path + ".bak") - - -def read_text(path: str) -> str: - try: - with Path(path).open(encoding="utf-8") as f: - return f.read() - except Exception: - return "" - - -def load_yaml_rt(path: str): - try: - with Path(path).open(encoding="utf-8") as f: - data = yaml_rt.load(f) - return data if data is not None else CommentedMap() - except FileNotFoundError: - return CommentedMap() - except Exception as e: - print(f"[WARN] Failed to parse YAML: {path}: {e}", file=sys.stderr) - return CommentedMap() - - -def dump_yaml_rt(data, path: str) -> None: - backup(path) - with Path(path).open("w", encoding="utf-8") as f: - yaml_rt.dump(data, f) - - -def sq(value: str): - """Single-quoted scalar for consistent ruamel quoting.""" - return SingleQuotedScalarString(value) - - -def roles_root(project_root: str) -> str: - return str(Path(project_root) / "roles") - - -def iter_role_dirs(project_root: str) -> list[str]: - return [ - d - for d in glob.glob(str(Path(roles_root(project_root)) / "*")) - if Path(d).is_dir() - ] - - -def role_name_from_dir(role_dir: str) -> str: - return Path(role_dir.rstrip(os.sep)).name - - -def path_if_exists(*parts: str) -> str | None: - p = str(Path(*parts)) - return p if Path(p).exists() else None - - -def gather_yaml_files(base: str, patterns: list[str]) -> list[str]: - files: list[str] = [] - for pat in patterns: - files.extend(glob.glob(str(Path(base) / pat), recursive=True)) - return [f for f in files if Path(f).is_file()] diff --git a/cli/fix/tabs/__init__.py b/cli/fix/tabs/__init__.py deleted file mode 100644 index 4004664a5f..0000000000 --- a/cli/fix/tabs/__init__.py +++ /dev/null @@ -1,14 +0,0 @@ -"""Compatibility wrapper. - -This package was migrated from a flat module (tabs.py) to a package layout: - tabs/__main__.py contains the original implementation. - -We re-export the public API so existing imports keep working. -""" - -from __future__ import annotations - -from . import __main__ as _main - -__all__ = getattr(_main, "__all__", [n for n in dir(_main) if not n.startswith("_")]) # noqa: PLE0605 -globals().update({name: getattr(_main, name) for name in __all__}) diff --git a/cli/fix/tabs/__main__.py b/cli/fix/tabs/__main__.py deleted file mode 100755 index e1001adb3e..0000000000 --- a/cli/fix/tabs/__main__.py +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env python3 - -import argparse -import sys -from pathlib import Path - -FILES_FIXED = [] - - -def fix_tabs_in_file(file_path): - """Replaces tab characters with two spaces in the specified file.""" - with Path(file_path).open(encoding="utf-8") as f: - lines = f.readlines() - - if any("\t" in line for line in lines): - fixed_lines = [line.replace("\t", " ") for line in lines] - with Path(file_path).open("w", encoding="utf-8") as f: - f.writelines(fixed_lines) - FILES_FIXED.append(str(file_path)) - - -def find_yml_files(path): - """Yield all .yml files under a given path recursively.""" - for file in path.rglob("*.yml"): - if file.is_file(): - yield file - - -def main(): - parser = argparse.ArgumentParser( - description="Fix tab characters in all .yml files under a given path (recursively)." - ) - parser.add_argument( - "path", - nargs="?", - default="./", - help="Base path to search for .yml files (default: ./)", - ) - args = parser.parse_args() - - base_path = Path(args.path).resolve() - - if not base_path.exists(): - print(f"❌ Path does not exist: {base_path}") - sys.exit(1) - - print(f"🔍 Searching for .yml files under: {base_path}\n") - - for yml_file in find_yml_files(base_path): - fix_tabs_in_file(yml_file) - - if FILES_FIXED: - print("✅ Fixed tab characters in the following files:") - for f in FILES_FIXED: - print(f" - {f}") - else: - print("✅ No tabs found in any .yml files.") - - -if __name__ == "__main__": - main() diff --git a/cli/fix/vars_main_files/__init__.py b/cli/fix/vars_main_files/__init__.py deleted file mode 100644 index a0209fbb9e..0000000000 --- a/cli/fix/vars_main_files/__init__.py +++ /dev/null @@ -1,32 +0,0 @@ -from __future__ import annotations - -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[3] - -# `__main__` does `from . import PROJECT_ROOT` at import time, so the -# constant has to be defined first. -from . import __main__ as _main # noqa: E402 - -# Expose configuration that tests monkeypatch -ROLES_DIR = _main.ROLES_DIR - - -def run(prefix: str, preview: bool = False, overwrite: bool = False): - # sync patched value into the implementation module - _main.ROLES_DIR = ROLES_DIR - return _main.run(prefix=prefix, preview=preview, overwrite=overwrite) - - -def process_role(*args, **kwargs): - _main.ROLES_DIR = ROLES_DIR - return _main.process_role(*args, **kwargs) - - -def main(): - _main.ROLES_DIR = ROLES_DIR - return _main.main() - - -def __getattr__(name: str): - return getattr(_main, name) diff --git a/cli/fix/vars_main_files/__main__.py b/cli/fix/vars_main_files/__main__.py deleted file mode 100755 index 754b7413b8..0000000000 --- a/cli/fix/vars_main_files/__main__.py +++ /dev/null @@ -1,104 +0,0 @@ -#!/usr/bin/env python3 -""" -Script to ensure each Ansible role under ../roles/ with a given prefix has a vars/main.yml -containing the correct application_id. Can preview actions or overwrite mismatches. -""" - -import argparse -import sys -from pathlib import Path - -import yaml - -from utils.cache.yaml import dump_yaml, load_yaml_any - -from . import PROJECT_ROOT - -# Directory containing roles; can be overridden by tests -ROLES_DIR = (PROJECT_ROOT / "roles").resolve() - - -def process_role(role_dir: Path, prefix: str, preview: bool, overwrite: bool): - name = role_dir.name - if not name.startswith(prefix): - return - # Expected application_id is role name minus prefix - expected_id = name[len(prefix) :] - vars_dir = role_dir / "vars" - vars_file = vars_dir / "main.yml" - if vars_file.exists(): - # Load existing variables (cached parse). - try: - existing = load_yaml_any(str(vars_file), default_if_missing={}) or {} - except yaml.YAMLError as e: - print(f"Error parsing YAML in {vars_file}: {e}", file=sys.stderr) - return - if not isinstance(existing, dict): - print( - f"Error parsing YAML in {vars_file}: expected mapping at root", - file=sys.stderr, - ) - return - actual_id = existing.get("application_id") - if actual_id == expected_id: - # Already correct - return - if overwrite: - # Update only application_id - existing["application_id"] = expected_id - if preview: - print( - f"[PREVIEW] Would update {vars_file}: application_id -> {expected_id}" - ) - else: - dump_yaml(vars_file, existing) - print(f"Updated {vars_file}: application_id -> {expected_id}") - else: - print( - f"Mismatch in {vars_file}: application_id='{actual_id}', expected='{expected_id}'" - ) - # Create new vars/main.yml - elif preview: - print(f"[PREVIEW] Would create {vars_file} with application_id: {expected_id}") - else: - vars_dir.mkdir(parents=True, exist_ok=True) - dump_yaml(vars_file, {"application_id": expected_id}) - print(f"Created {vars_file} with application_id: {expected_id}") - - -def run(prefix: str, preview: bool = False, overwrite: bool = False): - """ - Ensure vars/main.yml for roles under ROLES_DIR with the given prefix has correct application_id. - """ - for role in sorted(Path(ROLES_DIR).iterdir()): - if role.is_dir(): - process_role(role, prefix, preview, overwrite) - - -def main(): - parser = argparse.ArgumentParser( - description="Ensure vars/main.yml for roles with a given prefix has correct application_id" - ) - parser.add_argument( - "--prefix", - required=True, - help="Role name prefix to filter (e.g. 'web-', 'svc-', 'desk-')", - ) - parser.add_argument( - "--preview", - action="store_true", - help="Show what would be done without making changes", - ) - parser.add_argument( - "--overwrite", - action="store_true", - help="If vars/main.yml exists but application_id mismatches, overwrite only that key", - ) - args = parser.parse_args() - - # Run processing - run(prefix=args.prefix, preview=args.preview, overwrite=args.overwrite) - - -if __name__ == "__main__": - main() diff --git a/docs/requirements/008-role-meta-layout.md b/docs/requirements/008-role-meta-layout.md index 5fc61766f3..d6d9bfb552 100644 --- a/docs/requirements/008-role-meta-layout.md +++ b/docs/requirements/008-role-meta-layout.md @@ -304,7 +304,7 @@ the old `compose.…` or top-level paths. - `plugins/lookup/nginx.py` - `plugins/lookup/application_gid.py` - `plugins/lookup/rbac_group_path.py` - - `cli/fix/docker_image_versions/__main__.py` + - `cli/contributing/docker/update_versions/__main__.py` - `cli/deploy/development/inventory.py` - `cli/meta/roles/applications/resolution/combined/role_introspection.py` - `cli/meta/roles/applications/resolution/services/resolver.py` diff --git a/scripts/github/update_docker_image_versions.sh b/scripts/github/update_docker_image_versions.sh index 1c421eb840..2639933e1b 100755 --- a/scripts/github/update_docker_image_versions.sh +++ b/scripts/github/update_docker_image_versions.sh @@ -5,4 +5,4 @@ SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" REPO_ROOT="$(cd -- "${SCRIPT_DIR}/../.." && pwd)" cd "${REPO_ROOT}" -python3 -m cli.fix.docker_image_versions "$@" +python3 -m cli.contributing.docker.update_versions "$@" diff --git a/tests/unit/cli/fix/test_vars_main_files.py b/tests/unit/cli/fix/test_vars_main_files.py deleted file mode 100644 index f71db50351..0000000000 --- a/tests/unit/cli/fix/test_vars_main_files.py +++ /dev/null @@ -1,86 +0,0 @@ -import shutil -import tempfile -import unittest -from pathlib import Path - -# Adjust this import to match the real path in your project -from cli.fix.vars_main_files import ROLES_DIR, run -from utils.cache.yaml import dump_yaml, load_yaml_any -from utils.roles.mapping import ROLE_FILE_VARS_MAIN - - -class TestEnsureVarsMain(unittest.TestCase): - def setUp(self): - # create a temporary directory to act as our roles dir - self.tmpdir = tempfile.mkdtemp() - self.roles_dir = str(Path(self.tmpdir) / "roles") - Path(self.roles_dir).mkdir() - - # Monkey-patch the module's ROLES_DIR to point here - self._orig_roles_dir = ROLES_DIR - __import__( - "cli.fix.vars_main_files", fromlist=["ROLES_DIR"] - ).ROLES_DIR = self.roles_dir - - def tearDown(self): - # restore and cleanup - __import__( - "cli.fix.vars_main_files", fromlist=["ROLES_DIR"] - ).ROLES_DIR = self._orig_roles_dir - shutil.rmtree(self.tmpdir) - - def _make_role(self, name, vars_content=None): - """ - Create a role under self.roles_dir/name - If vars_content is given, writes that to vars/main.yml - """ - role_path = str(Path(self.roles_dir) / name) - Path(str(Path(role_path) / "vars")).mkdir(parents=True) - if vars_content is not None: - dump_yaml(str(Path(role_path) / ROLE_FILE_VARS_MAIN), vars_content) - return role_path - - def test_creates_missing_vars_main(self): - # Create a role with no vars/main.yml - role = self._make_role("desk-foobar") - # Ensure no file exists yet - self.assertFalse(Path(str(Path(role) / ROLE_FILE_VARS_MAIN)).exists()) - - # Run with overwrite=False, preview=False - run(prefix="desk-", preview=False, overwrite=False) - - # Now file must exist - vm = str(Path(role) / ROLE_FILE_VARS_MAIN) - self.assertTrue(Path(vm).exists()) - - data = load_yaml_any(vm) - # Expect application_id: 'foobar' - self.assertEqual(data.get("application_id"), "foobar") - - def test_overwrite_updates_only_application_id(self): - # Create a role with an existing vars/main.yml - initial = {"application_id": "wrong", "foo": "bar"} - role = self._make_role("desk-baz", vars_content=initial.copy()) - - run(prefix="desk-", preview=False, overwrite=True) - - path = str(Path(role) / ROLE_FILE_VARS_MAIN) - data = load_yaml_any(path) - - # application_id must be corrected... - self.assertEqual(data.get("application_id"), "baz") - # ...but other keys must survive - self.assertIn("foo", data) - self.assertEqual(data["foo"], "bar") - - def test_preview_mode_does_not_write(self): - # Create a role directory but with no vars/main.yml - role = self._make_role("desk-preview") - vm = str(Path(role) / ROLE_FILE_VARS_MAIN) - # Run in preview => no file creation - run(prefix="desk-", preview=True, overwrite=False) - self.assertFalse(Path(vm).exists()) - - -if __name__ == "__main__": - unittest.main()