#!/usr/bin/env python3 # SPDX-License-Identifier: MIT """Check that unknown changes cannot take a scoped CI path.""" import os from pathlib import Path import shutil import subprocess import tempfile import importlib.util import yaml SCRIPT = Path(__file__).with_name("pr-surface.py") ROOT = SCRIPT.parents[1] spec = importlib.util.spec_from_file_location("pr_surface", SCRIPT) assert spec and spec.loader pr_surface = importlib.util.module_from_spec(spec) spec.loader.exec_module(pr_surface) def git(directory: Path, *args: str) -> str: return subprocess.check_output( ["git", "-C", str(directory), *args], text=True, stderr=subprocess.DEVNULL, ).strip() def check_workflow_contract() -> None: """Keep the short workflow check from silently dropping release gates.""" required = { "release.yml": ("main", "release", ( "Check runner image pins", "Clippy (our crate, warnings are errors)", "Build release", "Unit tests", "Microbenchmarks", "Headless UI self-test", "Coverage", "Microbenchmark coverage", "Generate measured badges", "Publish measured badges", "Record private benchmark history", "Create Gitea release + upload artifact", "Clean generated Toolkit build", )), "next.yml": ("next", "candidate", ( "Check runner image pins", "Build release candidate", "Create private prerelease", "Clean generated Toolkit build", )), "verify.yml": ("main", "verify", ( "Check runner image pins", "Detect changed surface", "Check CI change surface", "Check workflow-only change", "Clippy (our crate, warnings are errors)", "Build", "Unit tests", "Microbenchmarks", "Headless UI self-test", "Clean generated Toolkit build", )), } for filename, (branch, job_name, gates) in required.items(): path = ROOT / ".gitea/workflows" / filename workflow = yaml.load(path.read_text(), Loader=yaml.BaseLoader) event = "pull_request" if filename == "verify.yml" else "push" assert workflow["on"][event]["branches"] == [branch], path job = workflow["jobs"][job_name] assert job["runs-on"] in {"alkane-ci", "alkane-verify"}, path steps = job["steps"] names = [step.get("name") for step in steps] positions = [names.index(gate) for gate in gates] assert positions == sorted(positions), path assert steps[positions[-1]].get("if") == "always()", path for gate, position in zip(gates[:-1], positions[:-1]): condition = steps[position].get("if") if gate in {"Create Gitea release + upload artifact", "Create private prerelease"}: assert condition is not None and "release == 'true'" in condition, path elif filename == "verify.yml" and gate in { "Build", "Unit tests", "Microbenchmarks", "Clippy (our crate, warnings are errors)", "Headless UI self-test"}: assert condition == "steps.surface.outputs.surface == 'full'", path elif filename == "verify.yml" and gate == "Check CI change surface": assert condition == "steps.surface.outputs.surface != 'documentation'", path elif filename == "verify.yml" and gate == "Check workflow-only change": assert condition == "steps.surface.outputs.surface == 'workflow'", path else: assert condition is None, path def main() -> None: check_workflow_contract() with tempfile.TemporaryDirectory(prefix="alkane-toolkit-workflow-policy-") as directory: global ROOT saved_root = ROOT ROOT = Path(directory) (ROOT / ".gitea/workflows").mkdir(parents=True) for filename in ("release.yml", "next.yml", "verify.yml"): shutil.copyfile(saved_root / ".gitea/workflows" / filename, ROOT / ".gitea/workflows" / filename) release = ROOT / ".gitea/workflows/release.yml" original = release.read_text() release.write_text(original.replace("- name: Coverage", "- name: Skipped coverage", 1)) try: check_workflow_contract() except ValueError: pass else: raise AssertionError("removing the coverage gate passed workflow policy") ROOT = saved_root assert pr_surface.documentation_only(["README.md", "docs/setup.md"]) assert pr_surface.workflow_only([".gitea/workflows/release.yml"]) for paths in ([], ["ci/pr-surface.py"], ["ci/coverage.sh"], ["ci/check-runner-image.py"], [".gitea/workflows/release.yml", "ci/check-runner-image.py"], [".gitea/workflows/release.yml", "crates/alkane-gui/src/main.rs"], [".gitea/workflows/../release.yml"]): assert not pr_surface.workflow_only(paths), paths for paths in ([], ["docs/generated.json"], ["src/main.rs"], ["README.md", "ci/pr-surface.py"]): assert not pr_surface.documentation_only(paths), paths assert pr_surface.headless_packages(["crates/alkane-cli/src/main.rs"]) == ["alkane-cli"] assert pr_surface.headless_packages(["crates/alkane-artifacts/src/lib.rs"]) == [ "alkane-artifacts", "alkane-cli", "alkane-flash", ] assert pr_surface.headless_packages([ "crates/alkane-access/src/lib.rs", "crates/alkane-flash/tests/update.rs", ]) == ["alkane-access", "alkane-flash"] for paths in ([], ["crates/alkane-core/src/lib.rs"], ["crates/alkane-discovery/src/lib.rs"], ["crates/alkane-gui/src/main.rs"], ["crates/alkane-artifacts/Cargo.toml"], ["crates/alkane-cli/src/main.rs", "Cargo.lock"], ["crates/alkane-cli/src/main.rs", "ci/pr-surface.py"], ["crates/alkane-cli/README.md"]): assert pr_surface.headless_packages(paths) == [], paths with tempfile.TemporaryDirectory(prefix="alkane-toolkit-graph-") as directory: root = Path(directory) for name, extra in ( ("alkane-gui", ""), ("alkane-artifacts", ""), ("alkane-flash", 'alkane-artifacts = { path = "../alkane-artifacts" }\n'), ): crate = root / "crates" / name crate.mkdir(parents=True) (crate / "Cargo.toml").write_text( f'[package]\nname = "{name}"\nversion = "0.1.0"\n' f'[dependencies]\n{extra}' ) saved_root = pr_surface.ROOT try: pr_surface.ROOT = root changed = ["crates/alkane-artifacts/src/lib.rs"] assert pr_surface.headless_packages(changed) == [ "alkane-artifacts", "alkane-flash", ] with (root / "crates/alkane-gui/Cargo.toml").open("a") as stream: stream.write('alkane-flash = { path = "../alkane-flash" }\n') assert pr_surface.headless_packages(changed) == [] finally: pr_surface.ROOT = saved_root with tempfile.TemporaryDirectory(prefix="alkane-toolkit-pr-surface-") as directory: repo = Path(directory) git(repo, "init", "-q") git(repo, "config", "user.name", "CI Test") git(repo, "config", "user.email", "ci@example.invalid") (repo / "README.md").write_text("initial\n") git(repo, "add", "README.md") git(repo, "commit", "-qm", "base") base = git(repo, "rev-parse", "HEAD") git(repo, "update-ref", "refs/remotes/origin/main", base) (repo / "README.md").write_text("documentation change\n") git(repo, "commit", "-qam", "docs") saved_root = pr_surface.ROOT saved_env = dict(os.environ) try: pr_surface.ROOT = repo os.environ["GITHUB_EVENT_NAME"] = "pull_request" os.environ["GITHUB_BASE_REF"] = "main" assert pr_surface.changed_paths() == ["README.md"] git(repo, "checkout", "-q", "-b", "rename-check", base) git(repo, "mv", "README.md", "code.rs") git(repo, "commit", "-qm", "rename") assert set(pr_surface.changed_paths()) == {"README.md", "code.rs"} os.environ.pop("GITHUB_BASE_REF") try: pr_surface.changed_paths() except ValueError: pass else: raise AssertionError("missing base must fall back to full checks") finally: pr_surface.ROOT = saved_root os.environ.clear() os.environ.update(saved_env) print("Toolkit PR change surface: documentation, workflow, headless, and fallback PASS") if __name__ == "__main__": main()