diff --git a/.github/workflows/linux-x86-lint.yml b/.github/workflows/linux-x86-lint.yml index 289fc6fa..3e65c119 100644 --- a/.github/workflows/linux-x86-lint.yml +++ b/.github/workflows/linux-x86-lint.yml @@ -19,9 +19,53 @@ concurrency: cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} jobs: + verify: + name: Verify local attestations + if: >- + github.event_name == 'pull_request' && + github.event.pull_request.head.repo.full_name == github.repository && + !contains(github.event.pull_request.labels.*.name, 'ci-full') + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + outputs: + skip_call: ${{ steps.plan.outputs.skip_call }} + skip_unit: ${{ steps.plan.outputs.skip_unit }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.base.sha }} + fetch-depth: 0 + - uses: astral-sh/setup-uv@v5 + - name: Plan PR gates from the base + id: plan + if: hashFiles('ci/prooft_verify.py') != '' && hashFiles('ci-attestations.yml') != '' + env: + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PR_TITLE: ${{ github.event.pull_request.title }} + run: uv run --no-project python ci/prooft_verify.py "$BASE_SHA" "$HEAD_SHA" "$PR_TITLE" + call: + name: Lint (format, Clippy, Dylint) + needs: verify + if: ${{ !cancelled() && needs.verify.outputs.skip_call != 'true' }} uses: ./.github/workflows/_lint.yml with: source-sha: ${{ github.event_name == 'workflow_dispatch' && inputs.candidate_sha || github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} runs-on: ubuntu-24.04 run-dylint: true + + unit: + name: Linux x86 Unit Test + needs: verify + if: >- + !cancelled() && github.event_name == 'pull_request' && + contains(github.event.pull_request.labels.*.name, 'ci-test') && + !contains(github.event.pull_request.labels.*.name, 'ci-full') && + needs.verify.outputs.skip_unit != 'true' + uses: ./.github/workflows/_unit-test.yml + with: + source-sha: ${{ github.event.pull_request.head.sha }} + runs-on: ubuntu-24.04 diff --git a/.github/workflows/linux-x86-unit-test.yml b/.github/workflows/linux-x86-unit-test.yml index 1af9a1ef..1a20b6bd 100644 --- a/.github/workflows/linux-x86-unit-test.yml +++ b/.github/workflows/linux-x86-unit-test.yml @@ -19,8 +19,10 @@ concurrency: cancel-in-progress: ${{ github.ref != 'refs/heads/main' }} jobs: + # ci-test PRs share the verifier in linux-x86-lint.yml. Keep this cell + # for ci-full PR coverage and exact-SHA release dispatches. call: - if: github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && (contains(github.event.pull_request.labels.*.name, 'ci-test') || contains(github.event.pull_request.labels.*.name, 'ci-full'))) + if: github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && contains(github.event.pull_request.labels.*.name, 'ci-full')) uses: ./.github/workflows/_unit-test.yml with: source-sha: ${{ github.event_name == 'workflow_dispatch' && inputs.candidate_sha || github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} diff --git a/ci-attestations.yml b/ci-attestations.yml new file mode 100644 index 00000000..9d4f066a --- /dev/null +++ b/ci-attestations.yml @@ -0,0 +1,16 @@ +version: 1 +lanes: + lint: + inputs: ["crates/**", "dylints/**", "src/**", "ci/**", "tests/**", "examples/**", "demo/**", "vscode-plugin/**", ".github/workflows/_lint.yml", Cargo.toml, Cargo.lock, rust-toolchain.toml, pyproject.toml, uv.lock, setup.py, MANIFEST.in, README.md, LICENSE, lint, push, ci-attestations.yml] + test: + inputs: ["crates/**", "dylints/**", "src/**", "ci/**", "tests/**", "examples/**", "demo/**", "vscode-plugin/**", ".github/workflows/**", Cargo.toml, Cargo.lock, rust-toolchain.toml, pyproject.toml, uv.lock, setup.py, MANIFEST.in, README.md, LICENSE, lint, test, push, ci-attestations.yml] +gates: + general/linux-x64/lint: {lane: lint} + rust/all/fmt: {lane: lint} + rust/x86_64-unknown-linux-gnu/clippy: {lane: lint} + rust/x86_64-unknown-linux-gnu/dylint: {lane: lint} + rust/x86_64-unknown-linux-gnu/test: {lane: test} + python/linux-x64/test: {lane: test} +jobs: + linux-x86-lint.yml:call: [general/linux-x64/lint, rust/all/fmt, rust/x86_64-unknown-linux-gnu/clippy, rust/x86_64-unknown-linux-gnu/dylint] + linux-x86-lint.yml:unit: [rust/x86_64-unknown-linux-gnu/test, python/linux-x64/test] diff --git a/ci/attest_test.py b/ci/attest_test.py new file mode 100644 index 00000000..e08234bd --- /dev/null +++ b/ci/attest_test.py @@ -0,0 +1,28 @@ +"""Run the same unit tests as CI with concurrency scaled to host load.""" + +import os +import subprocess +import sys + + +def load_aware_workers(cpus: int, load: float) -> int: + """Keep full concurrency on an idle host and scale down on a busy host.""" + return min(cpus, max(2, int(cpus * cpus / max(cpus, load)))) + + +def main() -> int: + if sys.platform != "linux": + raise RuntimeError("Linux unit attestations require Linux") + cpus = len(os.sched_getaffinity(0)) + load = os.getloadavg()[0] + workers = str(load_aware_workers(cpus, load)) + print( + f"Unit tests: {workers} workers ({cpus} CPUs, 1-minute load {load:.1f})", + flush=True, + ) + env = {**os.environ, "RUST_TEST_THREADS": workers, "CARGO_BUILD_JOBS": workers} + return subprocess.run(["./test"], env=env, check=False).returncode + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/ci/check_full_coverage.py b/ci/check_full_coverage.py index 3f1d6c78..fc0aba62 100644 --- a/ci/check_full_coverage.py +++ b/ci/check_full_coverage.py @@ -20,6 +20,11 @@ "macos-x86", "macos-arm", } +# The x86 Linux lint workflow also serves ordinary PRs. These two jobs +# are expected to skip during exact-SHA dispatch and ci-full PR runs. +PR_ONLY_JOBS = { + "linux-x86-lint.yml": {"Verify local attestations", "Linux x86 Unit Test"}, +} POLL_SECONDS = 120 # 29 workflows × runs/jobs endpoints; stay well below API limits. @@ -27,7 +32,7 @@ def parse_time(value): return dt.datetime.fromisoformat(value.replace("Z", "+00:00")) -def cell_result(run, jobs, sha, event, earliest): +def cell_result(run, jobs, sha, event, earliest, *, pr_only_jobs=()): if run["head_sha"] != sha or run["event"] != event: return "wrong-sha-or-event" if parse_time(run["created_at"]) < earliest: @@ -36,9 +41,13 @@ def cell_result(run, jobs, sha, event, earliest): return "pending" if run["conclusion"] != "success": return run["conclusion"] or "failed" - if not jobs: + if not any(job.get("name") not in pr_only_jobs for job in jobs): return "missing-jobs" - if any(job["conclusion"] != "success" for job in jobs): + if any( + job["conclusion"] != "success" + and not (job.get("name") in pr_only_jobs and job["conclusion"] == "skipped") + for job in jobs + ): return "skipped-or-failed-job" return "passed" @@ -104,7 +113,14 @@ def collect(repo, sha, event, earliest, workflows): if run["status"] == "completed": jobs = pages(f"repos/{repo}/actions/runs/{run['id']}/jobs", "jobs") report[workflow] = { - "result": cell_result(run, jobs, sha, event, earliest), + "result": cell_result( + run, + jobs, + sha, + event, + earliest, + pr_only_jobs=PR_ONLY_JOBS.get(workflow, ()), + ), "run_id": run["id"], "url": run["html_url"], "jobs": [ diff --git a/ci/prooft_verify.py b/ci/prooft_verify.py new file mode 100644 index 00000000..639f94a3 --- /dev/null +++ b/ci/prooft_verify.py @@ -0,0 +1,34 @@ +"""Plan PR skips using the verifier and policy checked out from the base.""" + +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +PROOFT_SOURCE = ( + "git+https://github.com/forge-ci/prooft@d08d58bebcd8592e4526b9bde9ca4717966a8786" +) + + +def prooft(*args: str) -> list[str]: + return ["uvx", "--from", PROOFT_SOURCE, "prooft", "-C", str(ROOT), *args] + + +def main(base: str, head: str, title: str) -> int: + subprocess.run(["git", "fetch", "--no-tags", "origin", head], cwd=ROOT, check=True) + return subprocess.run( + prooft( + "plan", + "--base", + base, + "--head", + head, + f"--title={title}", + "--github-output", + ), + check=False, + ).returncode + + +if __name__ == "__main__": + raise SystemExit(main(*sys.argv[1:])) diff --git a/push b/push new file mode 100755 index 00000000..9857e3c5 --- /dev/null +++ b/push @@ -0,0 +1,214 @@ +#!/usr/bin/env -S uv run --no-project --script +# /// script +# requires-python = ">=3.11" +# dependencies = [] +# /// +"""Attest Linux x86_64 lint and unit tests, push HEAD, and open a PR. + +Exit codes: 0 success, 1 step failed, 2 usage, 3 refused. +""" + +import argparse +import json +import platform +import subprocess +import sys +from typing import NamedTuple + +from ci.prooft_verify import ROOT, prooft + + +class Lane(NamedTuple): + name: str + gates: set[str] + command: tuple[str, ...] + + +LANES = ( + Lane( + "lint", + { + "general/linux-x64/lint", + "rust/all/fmt", + "rust/x86_64-unknown-linux-gnu/clippy", + "rust/x86_64-unknown-linux-gnu/dylint", + }, + ("./lint",), + ), + Lane( + "test", + {"rust/x86_64-unknown-linux-gnu/test", "python/linux-x64/test"}, + ("uv", "run", "--no-project", "python", "ci/attest_test.py"), + ), +) +# A worktree-local ref keeps the latest proof available across commits. +CACHE = "refs/worktree/fastled-prooft" + + +def git(*args: str) -> str: + return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip() + + +def step(argv: list[str], *, input_text: str | None = None) -> int: + print(f"./push: $ {' '.join(argv)}", flush=True) + return subprocess.run( + argv, cwd=ROOT, input=input_text, text=True, check=False + ).returncode + + +def proof_states(rev: str = "HEAD") -> tuple[int, dict[str, str]]: + result = subprocess.run( + prooft("verify", rev, "--json"), + cwd=ROOT, + stdout=subprocess.PIPE, + text=True, + check=False, + ) + rows = json.loads(result.stdout) + return result.returncode, {row["gate"]: row["state"] for row in rows} + + +def reuse_cached_proof(states: dict[str, str]) -> bool: + """Restore previously verified gates if prooft accepts them for this HEAD.""" + cached = subprocess.run( + ["git", "rev-parse", "--verify", "--quiet", CACHE], + cwd=ROOT, + stdout=subprocess.PIPE, + text=True, + check=False, + ).stdout.strip() + if not cached or cached == git("rev-parse", "HEAD"): + return False + bundle = json.loads(subprocess.check_output(prooft("emit", cached), text=True)) + bundle["attestations"] = [ + proof + for proof in bundle["attestations"] + if states.get(proof["gate"]) != "valid" + ] + if bundle["attestations"]: + # Exit 1 also means the cached inputs no longer match. The next verify + # determines which lanes still need a new run. + return step(prooft("apply", "-"), input_text=json.dumps(bundle)) == 0 + return False + + +def attest() -> str: + _, states = proof_states() + required = set().union(*(lane.gates for lane in LANES)) + if not required.issubset(states): + raise RuntimeError("the policy is missing required gates") + if any(states[gate] != "valid" for gate in required) and reuse_cached_proof(states): + _, states = proof_states() + for lane in LANES: + if all(states.get(gate) == "valid" for gate in lane.gates): + print(f"./push: reusing {lane.name} proof", flush=True) + continue + if step(prooft("run", lane.name, "--", *lane.command)) != 0: + raise RuntimeError(f"the {lane.name} lane failed") + git("update-ref", CACHE, "HEAD") + head = git("rev-parse", "HEAD") + code, states = proof_states(head) + if ( + code + or not required.issubset(states) + or any(state != "valid" for state in states.values()) + ): + raise RuntimeError(f"HEAD did not verify: {states}") + git("update-ref", CACHE, head) + return head + + +def refusal(branch: str, remote: str) -> str | None: + remote_head = subprocess.run( + ["git", "symbolic-ref", "--quiet", "--short", f"refs/remotes/{remote}/HEAD"], + cwd=ROOT, + stdout=subprocess.PIPE, + text=True, + check=False, + ).stdout.strip() + if branch in {"HEAD", "main"} or remote_head == f"{remote}/{branch}": + return "work on a feature branch" + if git("status", "--porcelain", "--untracked-files=no"): + return "tracked files have uncommitted changes" + return None + + +def gh_json(*args: str): + return json.loads(subprocess.check_output(["gh", *args], cwd=ROOT, text=True)) + + +def open_pr(remote: str, branch: str, labels: list[str]) -> int: + url = git("remote", "get-url", "--push", remote) + repo = gh_json("repo", "view", url, "--json", "nameWithOwner,url") + url = repo["url"] + prs = gh_json( + "pr", + "list", + "--repo", + url, + "--head", + branch, + "--state", + "open", + "--limit", + "100", + "--json", + "headRepository,headRefName", + ) + if any( + pr["headRefName"] == branch + and (pr.get("headRepository") or {}).get("nameWithOwner") + == repo["nameWithOwner"] + for pr in prs + ): + return 0 + create = ["gh", "pr", "create", "--repo", url, "--fill", "--head", branch] + for label in labels: + create.extend(("--label", label)) + return int(step(create) != 0) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, allow_abbrev=False) + parser.add_argument( + "--prove-only", action="store_true", help="attest without pushing" + ) + parser.add_argument( + "--no-pr", action="store_true", help="push without opening a PR" + ) + parser.add_argument("--remote", default="origin", help="git remote to push to") + parser.add_argument("--label", action="append", default=[], help="label a new PR") + args = parser.parse_args() + + try: + branch = git("rev-parse", "--abbrev-ref", "HEAD") + if reason := refusal(branch, args.remote): + print(f"./push: refusing: {reason}", file=sys.stderr) + return 3 + if ( + platform.system() != "Linux" + or platform.machine() != "x86_64" + or platform.libc_ver()[0] != "glibc" + ): + raise RuntimeError("the attestation lanes require Linux x86_64 with glibc") + head = attest() + if args.prove_only: + return 0 + if ( + git("rev-parse", "HEAD") != head + or git("rev-parse", "--abbrev-ref", "HEAD") != branch + ): + raise RuntimeError("HEAD or the branch changed after verification") + target = f"{head}:refs/heads/{branch}" + if step(["git", "push", "--force-with-lease", "-u", args.remote, target]): + return 1 + # Git only configures -u automatically when the source is a branch ref. + git("branch", "--set-upstream-to", f"{args.remote}/{branch}", branch) + return 0 if args.no_pr else open_pr(args.remote, branch, args.label) + except (OSError, ValueError, RuntimeError, subprocess.CalledProcessError) as error: + print(f"./push: {error}", file=sys.stderr) + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/unit/test_ci_modes.py b/tests/unit/test_ci_modes.py index 0f4fd8de..92a32be3 100644 --- a/tests/unit/test_ci_modes.py +++ b/tests/unit/test_ci_modes.py @@ -41,7 +41,15 @@ def test_platform_workflows_have_normalized_tiers(): assert ( "types: [opened, synchronize, reopened, labeled, unlabeled]" in workflow ), path.name - if path.name.endswith("-lint.yml"): + if path.name == "linux-x86-lint.yml": + assert "needs.verify.outputs.skip_call != 'true'" in workflow + assert "needs.verify.outputs.skip_unit != 'true'" in workflow + assert "'ci-test'" in workflow + assert ( + "!contains(github.event.pull_request.labels.*.name, 'ci-full')" + in workflow + ) + elif path.name.endswith("-lint.yml"): # Native Dylint runs on every ordinary PR for all lint platforms # (#274), so lint workflows carry no tier gate at all. assert " if: " not in workflow, path.name @@ -52,10 +60,7 @@ def test_platform_workflows_have_normalized_tiers(): " if: github.event_name == 'workflow_dispatch'" in workflow ), path.name assert "'ci-full'" in workflow, path.name - if path.name in { - "linux-x86-unit-test.yml", - "linux-x86-integration-test.yml", - }: + if path.name == "linux-x86-integration-test.yml": assert "'ci-test'" in workflow, path.name else: assert "'ci-test'" not in workflow, path.name @@ -310,6 +315,46 @@ def test_full_coverage_manifest_and_fail_closed_results(): ) +@pytest.mark.parametrize("event", ["pull_request", "workflow_dispatch"]) +def test_full_coverage_requires_lint_when_attestation_jobs_skip(event): + workflow = "linux-x86-lint.yml" + source = (WORKFLOWS / workflow).read_text() + pr_only_jobs = coverage.PR_ONLY_JOBS[workflow] + for name in pr_only_jobs: + assert f" name: {name}\n" in source + sha = "a" * 40 + created = "2026-11-20T00:00:00Z" + run = { + "head_sha": sha, + "event": event, + "created_at": created, + "status": "completed", + "conclusion": "success", + } + auxiliary = [{"name": name, "conclusion": "skipped"} for name in pr_only_jobs] + lint = {"name": "Lint (format, Clippy, Dylint) / lint", "conclusion": "success"} + earliest = coverage.parse_time(created) + assert ( + coverage.cell_result( + run, [*auxiliary, lint], sha, event, earliest, pr_only_jobs=pr_only_jobs + ) + == "passed" + ) + assert ( + coverage.cell_result( + run, auxiliary, sha, event, earliest, pr_only_jobs=pr_only_jobs + ) + == "missing-jobs" + ) + lint["conclusion"] = "skipped" + assert ( + coverage.cell_result( + run, [*auxiliary, lint], sha, event, earliest, pr_only_jobs=pr_only_jobs + ) + == "skipped-or-failed-job" + ) + + def test_publication_requires_exact_sha_full_coverage(): release = (WORKFLOWS / "auto-release.yml").read_text() vscode = (WORKFLOWS / "vscode-extension-release.yml").read_text() diff --git a/tests/unit/test_push_attestation.py b/tests/unit/test_push_attestation.py new file mode 100644 index 00000000..d2fcf455 --- /dev/null +++ b/tests/unit/test_push_attestation.py @@ -0,0 +1,243 @@ +"""Exercise the publishing contract without a real remote or Rust build.""" + +import subprocess +from pathlib import Path + +import pytest + +ROOT = Path(__file__).resolve().parents[2] +VERIFY = ROOT / "ci/prooft_verify.py" + + +def git(repo: Path, *args: str) -> str: + return subprocess.check_output(["git", "-C", str(repo), *args], text=True).strip() + + +@pytest.fixture +def checkout(tmp_path): + git(tmp_path, "init", "--initial-branch=main") + git(tmp_path, "config", "user.email", "test@example.com") + git(tmp_path, "config", "user.name", "FastLED test") + (tmp_path / "push").write_bytes((ROOT / "push").read_bytes()) + (tmp_path / "ci").mkdir() + (tmp_path / "ci/__init__.py").touch() + (tmp_path / "ci/prooft_verify.py").write_bytes(VERIFY.read_bytes()) + git(tmp_path, "add", ".") + git(tmp_path, "commit", "-m", "test") + return tmp_path + + +def run_push(repo: Path, *args: str): + return subprocess.run( + ["uv", "run", "--no-project", "python", "push", *args], + cwd=repo, + text=True, + capture_output=True, + check=False, + ) + + +@pytest.mark.parametrize("state", ["main", "detached", "staged", "unstaged"]) +def test_refuses_unprovable_checkout(checkout, state): + if state == "detached": + git(checkout, "checkout", "--detach") + if state in {"staged", "unstaged"}: + git(checkout, "checkout", "-b", "feature") + with (checkout / "push").open("a") as stream: + stream.write("\n") + if state == "staged": + git(checkout, "add", "push") + assert run_push(checkout).returncode == 3 + + +def test_no_proof_bypass(checkout): + assert run_push(checkout, "--no-proof").returncode == 2 + + +@pytest.fixture +def publisher(checkout, monkeypatch): + from importlib.machinery import SourceFileLoader + from importlib.util import module_from_spec, spec_from_loader + + monkeypatch.syspath_prepend(str(ROOT)) + spec = spec_from_loader( + "publisher", SourceFileLoader("publisher", str(checkout / "push")) + ) + assert spec and spec.loader + module = module_from_spec(spec) + spec.loader.exec_module(module) + monkeypatch.setattr(module, "ROOT", checkout) + monkeypatch.setattr(module.platform, "system", lambda: "Linux") + monkeypatch.setattr(module.platform, "machine", lambda: "x86_64") + monkeypatch.setattr(module.platform, "libc_ver", lambda: ("glibc", "2.39")) + git(checkout, "checkout", "-b", "feature") + (checkout / "untracked.txt").write_text("untracked changes are allowed") + return module + + +@pytest.mark.parametrize( + ("failure", "flags", "expected", "commands"), + [ + (None, ["--no-pr"], 0, ["lint", "test", "verify", "push"]), + (None, ["--prove-only"], 0, ["lint", "test", "verify"]), + ("lint", [], 1, ["lint"]), + ("test", [], 1, ["lint", "test"]), + ("verify", [], 1, ["lint", "test", "verify"]), + ], +) +def test_attest_and_verify_before_push( + publisher, monkeypatch, failure, flags, expected, commands +): + import sys + + calls = [] + states = {gate: "missing" for lane in publisher.LANES for gate in lane.gates} + + head = git(publisher.ROOT, "rev-parse", "HEAD") + + def verify(rev="HEAD"): + if calls: + assert rev == head + calls.append("verify") + return (1 if failure == "verify" else 0), states + return 0, states + + def step(argv): + if argv[0] == "git": + assert argv == [ + "git", + "push", + "--force-with-lease", + "-u", + "mirror", + f"{head}:refs/heads/feature", + ] + calls.append("push") + return 0 + assert argv[0:2] == ["uvx", "--from"] + assert argv[6] == "run" + lane = next(lane for lane in publisher.LANES if lane.name == argv[7]) + calls.append(lane.name) + assert argv[8:] == ["--", *lane.command] + if failure == lane.name: + return 1 + states.update(dict.fromkeys(lane.gates, "valid")) + return 0 + + monkeypatch.setattr(sys, "argv", ["push", "--remote", "mirror", *flags]) + actual_git = publisher.git + + def git_command(*args): + if args[0] == "branch": + assert args == ("branch", "--set-upstream-to", "mirror/feature", "feature") + return "" + return actual_git(*args) + + monkeypatch.setattr(publisher, "git", git_command) + monkeypatch.setattr(publisher, "proof_states", verify) + monkeypatch.setattr(publisher, "step", step) + assert publisher.main() == expected + assert calls == commands + + +def test_valid_lanes_are_reused(publisher, monkeypatch): + states = {gate: "valid" for lane in publisher.LANES for gate in lane.gates} + monkeypatch.setattr(publisher, "proof_states", lambda _rev="HEAD": (0, states)) + monkeypatch.setattr(publisher, "step", lambda *_: pytest.fail("ran a proven lane")) + publisher.attest() + + +def test_verifier_shares_pin_and_uses_base_policy(publisher, monkeypatch): + import ci.prooft_verify as verifier + + calls = [] + + def run(argv, **_): + calls.append(argv) + return subprocess.CompletedProcess(argv, 0) + + monkeypatch.setattr(verifier, "PROOFT_SOURCE", "test-pin") + monkeypatch.setattr(verifier.subprocess, "run", run) + assert verifier.main("base", "head", "--literal title") == 0 + assert calls[0] == ["git", "fetch", "--no-tags", "origin", "head"] + assert calls[1] == publisher.prooft( + "plan", + "--base", + "base", + "--head", + "head", + "--title=--literal title", + "--github-output", + ) + assert calls[1][2] == "test-pin" + + +@pytest.mark.parametrize( + ("cpus", "load", "workers"), [(16, 0, 16), (16, 80, 3), (16, 170, 2), (1, 2, 1)] +) +def test_concurrency_tracks_host_load(monkeypatch, cpus, load, workers): + monkeypatch.syspath_prepend(str(ROOT)) + from ci.attest_test import load_aware_workers + + assert load_aware_workers(cpus, load) == workers + + +def test_changed_head_refuses_to_publish(publisher, monkeypatch): + import sys + + monkeypatch.setattr(sys, "argv", ["push"]) + head = git(publisher.ROOT, "rev-parse", "HEAD") + + def attest(): + git(publisher.ROOT, "commit", "--allow-empty", "-m", "concurrent commit") + return head + + monkeypatch.setattr(publisher, "attest", attest) + monkeypatch.setattr( + publisher, "step", lambda *_: pytest.fail("published another HEAD") + ) + assert publisher.main() == 1 + + +@pytest.mark.parametrize("same_repository", [True, False]) +def test_open_pr_matches_pushed_repository(publisher, monkeypatch, same_repository): + url = "https://github.com/FastLED/cli.git" + branch = "feature" + git(publisher.ROOT, "remote", "add", "mirror", url) + calls = [] + + def gh_json(*args): + if args[:2] == ("repo", "view"): + assert args[2] == url + return {"nameWithOwner": "FastLED/cli", "url": url} + assert args[:6] == ("pr", "list", "--repo", url, "--head", branch) + owner = "FastLED" if same_repository else "another-fork" + return [ + {"headRepository": {"nameWithOwner": f"{owner}/cli"}, "headRefName": branch} + ] + + def create(argv): + calls.append(argv) + return 0 + + monkeypatch.setattr(publisher, "gh_json", gh_json) + monkeypatch.setattr(publisher, "step", create) + assert publisher.open_pr("mirror", branch, ["ci-test"]) == 0 + assert calls == ( + [] + if same_repository + else [ + [ + "gh", + "pr", + "create", + "--repo", + url, + "--fill", + "--head", + branch, + "--label", + "ci-test", + ] + ] + )