#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Classify a pull request for scoped CI checks.""" import os from pathlib import Path import subprocess import sys import tomllib ROOT = Path(__file__).resolve().parents[1] DOC_FILES = {"README.md", "CONTRIBUTING.md", "CHANGELOG.md"} HEADLESS_CRATES = {"alkane-access", "alkane-artifacts", "alkane-cli", "alkane-flash"} def documentation_only(paths: list[str]) -> bool: return bool(paths) and all( path in DOC_FILES or (path.startswith("docs/") and Path(path).suffix in {".md", ".txt"}) for path in paths ) def workflow_only(paths: list[str]) -> bool: """Limit the cheap PR check to workflow YAML, never policy code.""" return bool(paths) and all( path.startswith(".gitea/workflows/") and len(Path(path).parts) == 3 and Path(path).suffix == ".yml" for path in paths ) def headless_packages(paths: list[str]) -> list[str]: """Return tested reverse dependents for code outside the GUI graph.""" changed: set[str] = set() if not paths: return [] for path in paths: parts = Path(path).parts if (len(parts) < 4 or parts[0] != "crates" or parts[1] not in HEADLESS_CRATES or parts[2] not in {"src", "tests"} or Path(path).suffix != ".rs"): return [] changed.add(parts[1]) try: manifests = {} for path in (ROOT / "crates").glob("*/Cargo.toml"): manifest = tomllib.loads(path.read_text()) name = manifest["package"]["name"] if name != path.parent.name: return [] manifests[name] = manifest if not changed <= manifests.keys() or "alkane-gui" not in manifests: return [] def dependencies(value: object) -> set[str]: found: set[str] = set() if isinstance(value, dict): for key, nested in value.items(): if key in {"dependencies", "dev-dependencies", "build-dependencies"}: for dep_name, spec in nested.items(): found.add(spec.get("package", dep_name) if isinstance(spec, dict) else dep_name) else: found.update(dependencies(nested)) return found & manifests.keys() graph = {name: dependencies(manifest) for name, manifest in manifests.items()} affected = changed.copy() while True: added = {name for name, deps in graph.items() if deps & affected} - affected if not added: break affected.update(added) return [] if "alkane-gui" in affected else sorted(affected) except (OSError, KeyError, TypeError, ValueError): return [] def changed_paths() -> list[str]: if os.environ.get("GITHUB_EVENT_NAME") != "pull_request": raise ValueError("not a pull request") if os.environ.get("GITHUB_BASE_REF") != "main": raise ValueError("unknown base branch") merge_base = subprocess.check_output( ["git", "-C", str(ROOT), "merge-base", "HEAD", "refs/remotes/origin/main"], stderr=subprocess.DEVNULL, text=True, ).strip() if len(merge_base) != 40: raise ValueError("missing merge base") raw = subprocess.check_output( ["git", "-C", str(ROOT), "diff", "--no-renames", "--name-only", "-z", merge_base, "HEAD"], stderr=subprocess.DEVNULL, ) return [path.decode("utf-8", "surrogateescape") for path in raw.split(b"\0") if path] def main() -> None: try: paths = changed_paths() docs = documentation_only(paths) workflow = workflow_only(paths) if not docs else False packages = headless_packages(paths) if not docs and not workflow else [] except (OSError, subprocess.CalledProcessError, ValueError): paths = [] docs = False workflow = False packages = [] surface = ("documentation" if docs else "workflow" if workflow else "headless" if packages else "full") print(f"surface={surface}") print(f"packages={' '.join(packages)}") print(f"Changed paths: {len(paths)}", file=sys.stderr) if __name__ == "__main__": main()