diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 758e24b5..b06f762b 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -122,11 +122,13 @@ def _load_config( args: argparse.Namespace, root: Path, *, pin_checks: bool = False, previous: Config | None = None, refresh: bool = False, ) -> Config: + require_ci = pin_checks and args.command in {"ready", "merge"} and not getattr(args, "cancel", False) if not pin_checks or args.config: if pin_checks: print("checks are unpinned because --config was provided") - return config_mod.load(args.config or root / "workflow.toml") - config = config_mod.load_trusted(root, previous=previous, refresh=refresh, read_timeout=github._read_timeout) + return config_mod.load(args.config or root / "workflow.toml", require_ci=require_ci) + config = config_mod.load_trusted(root, previous=previous, refresh=refresh, + require_ci=require_ci, read_timeout=github._read_timeout) if args.command == "check": if not config.checks: raise config_mod.ConfigError( diff --git a/src/loopzero/config.py b/src/loopzero/config.py index 6216971b..fd71263c 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -41,7 +41,7 @@ class ConfigError(LoopZeroError): """The configuration file is missing, unreadable, or has invalid content.""" -def load(path: Path | str) -> Config: +def load(path: Path | str, *, require_ci: bool = False) -> Config: """Load and validate a workflow file.""" path = Path(path) try: @@ -53,12 +53,17 @@ def load(path: Path | str) -> Config: "(https://github.com/feder-positronics/loop-zero/blob/main/SETUP.md#configure), " "or follow this repository's review process if it has one." ) from exc - return _parse_workflow(raw, path) + return _parse_workflow(raw, path, require_ci=require_ci) -def _parse_workflow(raw: bytes, source: Path | str, hint: str = "") -> Config: +def _parse_workflow(raw: bytes, source: Path | str, hint: str = "", *, + require_ci: bool = False, branch: str | None = None) -> Config: try: - return _build(tomllib.loads(raw.decode("utf-8"))) + data = tomllib.loads(raw.decode("utf-8")) + policy = _build(data) + if require_ci and (branch is None or policy.base_branch == branch): + _require_ci(data.get("checks", {})) + return policy except UnicodeDecodeError as exc: raise ConfigError(f"{source}: {exc}") from exc except (tomllib.TOMLDecodeError, ConfigError) as exc: @@ -101,7 +106,7 @@ def _has_replacement_refs(common_dir: Path) -> bool: def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, - refresh: bool, read_timeout: Callable[[float], float]) -> tuple[Config, str]: + refresh: bool, require_ci: bool, read_timeout: Callable[[float], float]) -> tuple[Config, str]: source = f"origin/{branch}:workflow.toml" hint = "Fetch the trusted base workflow, or supply --config for bootstrap or an override." ref = f"refs/remotes/origin/{branch}" @@ -127,12 +132,13 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, ) if shown.exit_code != 0: raise ConfigError(f"cannot read {source}. {hint}") - return _parse_workflow(shown.stdout.encode("utf-8", "surrogateescape"), source, f". {hint}"), revision + return _parse_workflow(shown.stdout.encode("utf-8", "surrogateescape"), source, f". {hint}", + require_ci=require_ci, branch=branch), revision -def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: bool = False, +def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: bool = False, require_ci: bool = False, read_timeout: Callable[[float], float] = float) -> Config: - """Select delivery policy using Git's origin default and its trusted workflow.""" + """Select trusted delivery policy, reusing earlier loads from the same validation mode.""" prefix = "refs/remotes/origin/" default = run_git(worktree, "symbolic-ref", "--quiet", f"{prefix}HEAD", timeout=read_timeout(60)) ref = default.stdout.strip() @@ -143,13 +149,21 @@ def load_trusted(worktree: Path, *, previous: Config | None = None, refresh: boo ) branch = ref.removeprefix(prefix) for _ in range(2): - policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh, read_timeout=read_timeout) + policy, revision = _remote_workflow(worktree, branch, previous, refresh=refresh, + require_ci=require_ci, read_timeout=read_timeout) if policy.base_branch == branch: return replace(policy, trusted_base_revision=revision) branch = policy.base_branch raise ConfigError("trusted origin workflows disagree on repo.base; align them or supply --config") +def _require_ci(checks: dict[str, Any]) -> None: + if "required_ci" not in checks: + raise ConfigError( + "checks.required_ci must list the required contexts or explicitly set required_ci = [] if none are required" + ) + + def _build(data: dict[str, Any]) -> Config: _reject_unknown("top level", data, _SECTIONS) sections = { diff --git a/tests/test_cli.py b/tests/test_cli.py index 466e6377..0bfb7f6f 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -2512,6 +2512,49 @@ def test_ready_not_ready_lists_reasons(wt: Path, gh: FakeGh, capsys, head) -> No assert not any("actions/runs" in " ".join(c["argv"]) for c in gh.calls) +@pytest.mark.parametrize("command,required,code,override", [ + ("ready", "", 1, False), ("merge", "", 1, False), ("ready", "", 1, True), + ("ready", "required_ci = []", 0, False), ("ready", 'required_ci = ["checks"]', 1, False), +]) +def test_delivery_requires_explicit_ci_policy(wt, gh, capsys, head, tmp_path, command, required, code, override): + if not required: + arm_approved_pr_with_check_result(gh, head, wt, "failure", isDraft=False) + publish_workflow(wt, WORKFLOW.replace('required_ci = ["checks"]', required) + "\n") + if required: + arm_approved_pr_with_check_result(gh, head, wt, "failure", isDraft=False) + source, options = "origin/main:workflow.toml", () + if override: + path = tmp_path / "override.toml" + path.write_text(WORKFLOW.replace('required_ci = ["checks"]', required)) + source, options = str(path), ("--config", str(path)) + actual, out, err = run(capsys, *options, command) + assert actual == code, (out, err) + if not required: + assert f"{source}: checks.required_ci must list the required contexts" in err + assert "required_ci = []" in err and not gh.calls + elif code: + assert "required check 'checks' is failure" in out + else: + assert not any("/check-runs" in " ".join(call["argv"]) for call in gh.calls) + + +@pytest.mark.parametrize("declared", [False, True]) +def test_ready_reads_required_ci_from_selected_workflow(wt, repo, declared): + redirect = WORKFLOW.replace('base = "main"', 'base = "release"').replace('required_ci = ["checks"]', "") + publish_workflow(wt, redirect) + if declared: + policy = redirect.replace('commands = ', 'required_ci = []\ncommands = ') + commit_file(repo, "workflow.toml", policy, "set release policy") + git(repo, "push", "-q", "origin", "HEAD:refs/heads/release") + args = SimpleNamespace(config=None, command="ready") + if declared: + config = cli._load_config(args, wt, pin_checks=True, refresh=True) + assert config.base_branch == "release" and config.required_ci == () + else: + with pytest.raises(cli.config_mod.ConfigError, match=r"origin/release:workflow\.toml: checks\.required_ci"): + cli._load_config(args, wt, pin_checks=True, refresh=True) + + @pytest.mark.parametrize("retargeted,reason", [ (True, "PR targets release, configured base is main"), (False, f"required check 'checks' is failure{FAILED_CHECK_HINT}"),