diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index 3bfaf9a0..8ac581fa 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -100,8 +100,7 @@ def build_env( ) -> dict[str, str]: """Copy only allowlisted variables from the current environment, then apply extras.""" env = {key: os.environ[key] for key in env_allowlist if key in os.environ} - if extra_env: - env.update(extra_env) + env.update(extra_env or {}) return env @@ -138,7 +137,6 @@ def run( stdin=subprocess.PIPE if input is not None else subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT if merge_output else subprocess.PIPE, - text=not preserve_newlines, encoding=None if preserve_newlines else encoding, errors=None if preserve_newlines else "replace", start_new_session=os.name == "posix", diff --git a/src/loopzero/candidate.py b/src/loopzero/candidate.py index aa314ef5..fed9dee8 100644 --- a/src/loopzero/candidate.py +++ b/src/loopzero/candidate.py @@ -18,7 +18,7 @@ import time from collections.abc import Callable, Iterator from pathlib import Path -from typing import Any +from typing import Any, BinaryIO MERGIFY_APP_ID = 10562 MERGIFY_APP_OWNER = "Mergifyio" @@ -276,18 +276,37 @@ def _attest_source( return source_sha -@contextlib.contextmanager -def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: - """Run bounded Git commands on fetched objects in an isolated bare repository.""" +def _require_git_exit(operation: str, returncode: int, output: BinaryIO) -> None: + if operation == "fetch" and returncode: + from loopzero import github + + output.seek(0) + diagnostic = output.read(_TREE_OUTPUT).decode(errors="replace") + if github._transient_error(diagnostic, False) or re.search(r"returned error: (?:429|5\d\d)", diagnostic): + raise github.GhUnavailable(("git", "fetch"), "GitHub objects temporarily unavailable") + _require(returncode == 0, f"git {operation} exited {returncode}: objects unavailable, " + "resource bound hit, or integration conflict") + + +def _fetch_token() -> str: from loopzero import github token = os.environ.get("GH_TOKEN") or os.environ.get("GITHUB_TOKEN") if not token: try: token = github.auth_token() + except github.GhUnavailable: + raise except github.GhError: raise CandidateError("GitHub fetch authentication unavailable") from None _require(bool(token), "GitHub fetch authentication unavailable") + return token + + +@contextlib.contextmanager +def fetched_git(repo: str, heads: list[str]) -> Iterator[Callable[..., str]]: + """Run bounded Git commands on fetched objects in an isolated bare repository.""" + token = _fetch_token() with tempfile.TemporaryDirectory(prefix="loopzero-candidate-") as directory: root = Path(directory) env = { @@ -311,7 +330,8 @@ def git(*args: str, command_env: dict[str, str] = env) -> str: [sys.executable, "-I", "-S", "-c", _LIMITED_GIT, str(_TREE_BYTES), "git", "-c", "core.hooksPath=/dev/null", "-c", "gc.auto=0", "-c", "maintenance.auto=false", *args], cwd=root, env=command_env, - stdin=subprocess.DEVNULL, stdout=output, stderr=subprocess.DEVNULL, + stdin=subprocess.DEVNULL, stdout=output, + stderr=output if args[0] == "fetch" else subprocess.DEVNULL, start_new_session=True, ) def store_size() -> int: # Git renames temporaries: skip files that vanish @@ -328,9 +348,7 @@ def store_size() -> int: # Git renames temporaries: skip files that vanish _require(time.monotonic() < deadline, "Git time bound exceeded") with contextlib.suppress(subprocess.TimeoutExpired): process.wait(timeout=0.02) - _require(process.returncode == 0, - f"git {args[0]} exited {process.returncode}: objects unavailable, " - "resource bound hit, or integration conflict") + _require_git_exit(args[0], process.returncode, output) _require(store_size() <= _TREE_BYTES, "Git object/size bound exceeded") output.seek(0) result = output.read(_TREE_OUTPUT + 1) diff --git a/src/loopzero/eligibility.py b/src/loopzero/eligibility.py index 6cd10e1d..965efd5d 100644 --- a/src/loopzero/eligibility.py +++ b/src/loopzero/eligibility.py @@ -121,6 +121,8 @@ def _clean_base_merges(repo: str, number: int, reviewed: str, head: str, base_br return False cursor = first return cursor == reviewed + except github.GhUnavailable: + raise except (candidate.CandidateError, github.GhError, KeyError, OSError, TypeError, ValueError): return False diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 53aba75a..874b79fa 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -69,7 +69,11 @@ def __init__(self, command: tuple[str, ...], tail: str, *, super().__init__(f"{command_text} failed: {self.tail.strip()[-600:]}") -class ReadDeadline(GhError): +class GhUnavailable(GhError): + """GitHub could not supply a result because of a transient fault or limit.""" + + +class ReadDeadline(GhUnavailable): """A shared GitHub read deadline elapsed.""" @@ -306,12 +310,22 @@ def _select_token(token: str | None, scope: tuple[float, str | None, bool] | Non return selected if selected is not None else (app_token() if read_only else "") -def _transient_error(tail: str, retry_idempotent: bool) -> bool: - return bool(TRANSIENT_RE.search(tail)) or ( +def _transient_error(tail: str, retry_idempotent: bool, status: str | None = None) -> bool: + return (status or "").startswith("5") or bool(TRANSIENT_RE.search(tail)) or ( retry_idempotent and "something went wrong while executing your query" in tail.lower() ) +def _request_error(transient: bool) -> type[GhError]: + return GhUnavailable if transient else GhError + + +def _rate_limited(status: str | None, headers: dict[str, str], tail: str) -> bool: + return (status == "429" + or (status == "403" and (headers.get("x-ratelimit-remaining") == "0" or "retry-after" in headers)) + or bool(re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE))) + + def _pr_list_error_guidance(args: tuple[str, ...], stderr: str, using_app: bool) -> str: if (using_app and len(args) > 1 and args[0] == "api" and re.fullmatch(r"repos/[^/]+/[^/]+/pulls\?.+", args[1]) @@ -356,16 +370,16 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, status, headers, body = (_included_response(done.stdout) if rest_api or diagnostic_api else (None, {}, done.stdout)) tail = "\n".join(part for part in (done.stderr, body if rest_api else done.stdout) if part) - if done.exit_code and ((rest_api and status == "429") - or re.search(r"rate limit|HTTP 429", tail, re.IGNORECASE)): + if done.exit_code and _rate_limited(status, headers, tail): guidance = (_redact_tokens(_rest_rate_limit(headers), selected) if rest_api else _graphql_reset(args, tail, cwd, selected) + RATE_LIMIT_GUIDANCE) if diagnostic_api or patch_error: detail = _api_error_detail(args, done.stdout if diagnostic_api else "", done.stderr, selected, message_tail=None if diagnostic_api else tail) - raise GhError(("GitHub API request",), detail, token=selected, guidance=guidance) - raise GhError(argv, tail, token=selected, guidance=guidance) - if done.exit_code == 0 or delay is None or not retryable or not _transient_error(tail, retry_idempotent): + raise GhUnavailable(("GitHub API request",), detail, token=selected, guidance=guidance) + raise GhUnavailable(argv, tail, token=selected, guidance=guidance) + transient = _transient_error(tail, retry_idempotent, status) + if done.exit_code == 0 or delay is None or not retryable or not transient: break _retry_sleep(_read_timeout(delay) if scope else delay) if done.exit_code != 0: @@ -376,7 +390,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, if "gh auth login" in tail or "not logged in" in tail.lower(): raise GhAuth(error_command, error_tail.rstrip(), token=selected, guidance=f"\n{GH_AUTH_REMEDY}") guidance = _pr_list_error_guidance(args, done.stderr, bool(read_only and selected and token is None)) - raise GhError(error_command, error_tail, token=selected, guidance=guidance) + raise _request_error(transient)(error_command, error_tail, token=selected, guidance=guidance) return body diff --git a/src/loopzero/hosted.py b/src/loopzero/hosted.py index 3b963850..2f723a65 100644 --- a/src/loopzero/hosted.py +++ b/src/loopzero/hosted.py @@ -36,8 +36,26 @@ def main() -> int: except config.ConfigError as exc: print(exc, file=sys.stderr) return 1 - with github.api_error_diagnostics(): - return _run(cfg) + try: + with github.api_error_diagnostics(): + return _run(cfg) + except (github.GhUnavailable, github.ProcTimeout) as exc: + print(f"Eligibility unconfirmed before pending status publication: {exc}", file=sys.stderr) + return 1 + + +def _candidate_event(event: dict, head: str) -> bool: + event_pr = event.get("pull_request") + if not isinstance(event_pr, dict): + raise LoopZeroError("candidate eligibility requires a pull_request_target " + "creation or head-update event") + if event.get("action") not in {"opened", "synchronize"}: + print("ignored candidate metadata event") + return False + event_head = event_pr.get("head") + if not isinstance(event_head, dict) or event_head.get("sha") != head: + raise LoopZeroError("candidate event head is no longer current") + return True def _run(cfg: Config) -> int: @@ -51,17 +69,8 @@ def _run(cfg: Config) -> int: or pr["user"]["login"] == "mergify[bot]") if not candidate and pr.get("merged") is True: return 0 # A landed source needs no new verdict; a late refresh must not turn it red. - if candidate: - event_pr = event.get("pull_request") - if not isinstance(event_pr, dict): - raise LoopZeroError("candidate eligibility requires a pull_request_target " - "creation or head-update event") - if event.get("action") not in {"opened", "synchronize"}: - print("ignored candidate metadata event") - return 0 - event_head = event_pr.get("head") - if not isinstance(event_head, dict) or event_head.get("sha") != head: - raise LoopZeroError("candidate event head is no longer current") + if candidate and not _candidate_event(event, head): + return 0 def publish(state: str, message: str) -> None: github.commit_status(cfg.repo, head, eligibility.CONTEXT, state, message[:140]) publish("pending", "Refreshing live source review evidence") @@ -89,6 +98,9 @@ def policy(source_number: int, source: dict) -> None: if not candidate and not ready and result.reasons == (github.MISSING_REVIEW_REASON,): message = "Awaiting trusted review of current source head" state = "pending" + except (github.GhUnavailable, github.ProcTimeout) as exc: + print(f"Eligibility pending: evidence unavailable ({exc})", file=sys.stderr) + return 0 except Exception as exc: _mark_refresh_failed(publish, exc) raise diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 7a994ac3..6a53d3e1 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -101,10 +101,12 @@ def _branch_exists(repo_root: Path, branch: str) -> bool: def _ensure_excludes(repo_root: Path) -> None: - common = Path(_git(repo_root, *_ABSOLUTE_COMMON_DIR)) - exclude = common / "info" / "exclude" + common = Path(_git(repo_root, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True)).resolve() + info = (common / "info").resolve() + exclude = (info / "exclude").resolve() + if not info.is_relative_to(common) or not exclude.is_relative_to(common): + raise WorktreeError(f"Git exclude is outside its Git directory: {exclude}") exclude.parent.mkdir(parents=True, exist_ok=True) - exclude = exclude.resolve() existing = exclude.read_text() if exclude.exists() else "" missing = [entry for entry in EXCLUDES if entry not in existing.splitlines()] if missing: @@ -134,9 +136,14 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: raise WorktreeError(refusal) if not existing and _branch_exists(repo_root, branch): raise WorktreeError(f"branch already exists: {branch}") - base_ref = f"refs/remotes/origin/{base_branch}" + remote_ref = f"refs/heads/{base_branch}" + lookup = ("ls-remote", "--refs", "origin", remote_ref) try: - _git(repo_root, "fetch", "--quiet", "origin", f"+refs/heads/{base_branch}:{base_ref}") + advertised = _git(repo_root, *lookup) + base, _, ref = advertised.partition("\t") + if ref != remote_ref: + raise GitError(("git", *lookup), f"origin did not report a unique {remote_ref}") + _git(repo_root, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--refmap=", "origin", base) except GitError: if "origin" not in _git(repo_root, "remote").splitlines(): raise WorktreeError( @@ -145,7 +152,7 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path: "with `git remote rename origin`." ) from None raise - base = _git(repo_root, "rev-parse", "--verify", f"{base_ref}^{{commit}}") + _git(repo_root, "update-ref", "--no-deref", f"refs/remotes/origin/{base_branch}", base) if existing: existing_head = _resumable_head(repo_root, wt, branch) if existing_head is None: diff --git a/tests/test_candidate.py b/tests/test_candidate.py index c72eb281..9f146759 100644 --- a/tests/test_candidate.py +++ b/tests/test_candidate.py @@ -9,6 +9,7 @@ from __future__ import annotations import base64 +from contextlib import nullcontext import subprocess from copy import deepcopy from functools import partial @@ -19,7 +20,7 @@ import pytest -from loopzero import candidate +from loopzero import candidate, github from loopzero.candidate import CandidateError, CandidateRaceError, attest_candidate from loopzero.types import LoopZeroError from tests.conftest import commit_file, git as isolated_git @@ -672,18 +673,16 @@ def run(): assert clock[0] == {"closed": 2, "ambiguous": 90, "slow": 100 * (1 + second), "oversleep": 100}[stop] -@pytest.mark.parametrize("exceeds_bound", [False, True]) -def test_fetched_git_waits_for_exit_or_resumes_size_checks(monkeypatch, exceeds_bound): - waits = [] - killed = [] - +@pytest.mark.parametrize("outcome", ["normal", "bound", "fetch"]) +def test_fetched_git_waits_for_exit_or_resumes_size_checks(monkeypatch, outcome): + waits, killed = [], [] class Child: pid = 123 - returncode = 0 - def __init__(self, argv, cwd, **kwargs): - self.root = cwd - self.running = "test-command" in argv + self.root, self.running = cwd, "test-command" in argv + self.returncode = 128 if outcome == "fetch" and "fetch" in argv else 0 + if self.returncode: + kwargs["stderr"].write(b"fatal: The requested URL returned error: 503") def poll(self): return None if self.running else self.returncode @@ -691,7 +690,7 @@ def poll(self): def wait(self, timeout=None): if self.running: waits.append(timeout) - if timeout is not None and exceeds_bound: + if timeout is not None and outcome == "bound": (self.root / "oversized").write_bytes(b"x" * 65) raise subprocess.TimeoutExpired("test-command", timeout) self.running = False @@ -703,12 +702,13 @@ def wait(self, timeout=None): monkeypatch.setattr(candidate.os, "killpg", lambda pid, sig: killed.append((pid, sig))) monkeypatch.setattr(candidate.time, "sleep", lambda _: pytest.fail("used a fixed delay")) - with candidate.fetched_git("owner/repo", []) as git: - if exceeds_bound: + error = pytest.raises(github.GhUnavailable, match="temporarily unavailable") if outcome == "fetch" else nullcontext() + with error, candidate.fetched_git("owner/repo", []) as git: + if outcome == "bound": with pytest.raises(CandidateError, match="Git object/size bound exceeded"): git("test-command") else: assert git("test-command") == "" - assert waits == ([0.02, None] if exceeds_bound else [0.02]) - assert killed == ([(123, candidate.signal.SIGKILL)] if exceeds_bound else []) + assert waits == {"bound": [0.02, None], "normal": [0.02], "fetch": []}[outcome] + assert killed == ([(123, candidate.signal.SIGKILL)] if outcome == "bound" else []) diff --git a/tests/test_hosted.py b/tests/test_hosted.py index abe46760..fd6a9e26 100644 --- a/tests/test_hosted.py +++ b/tests/test_hosted.py @@ -53,8 +53,7 @@ def test_event_selection(event, number): def publisher(tmp_path, fake_bin, monkeypatch): monkeypatch.chdir(tmp_path) monkeypatch.setenv("GITHUB_REPOSITORY", REPO) - event = tmp_path / "event.json" - event.write_text(json.dumps({"pull_request": {"number": 7}})) + (event := tmp_path / "event.json").write_text(json.dumps({"pull_request": {"number": 7}})) monkeypatch.setenv("GITHUB_EVENT_PATH", str(event)) Path("workflow.toml").write_text(f'[repo]\nname="{REPO}"\nbase="main"\n[delivery]\nreview_publishers=["trusted-publisher"]\n') gh = FakeGh(fake_bin, tmp_path) @@ -64,6 +63,7 @@ def publisher(tmp_path, fake_bin, monkeypatch): gh.respond_pr_view(pr_json()) gh.respond("api graphql", threads_json()) gh.respond(f"api repos/{REPO}/statuses/{HEAD}", {}) + gh.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", []) return gh @@ -144,28 +144,29 @@ def lose_reply(repo, head, context, value, description): assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == ["pending", state] -@pytest.mark.parametrize("error", ["api", "head", "publication", "config"]) -def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, error): - monkeypatch.setattr(github, "_retry_sleep", lambda _: None) - publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", []) - if error == "api": - publisher.respond(f"api repos/{REPO}/pulls/7/reviews?per_page=100&page=1", - {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n{\"message\":\"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"}", "stderr": "gh: Service unavailable (HTTP 503)", "exit": 1}) +@pytest.mark.parametrize("error", ["api", "recover", "head", "publication", "config", "before"]) +def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, capsys, error): + sleeps = [] + monkeypatch.setattr(github, "_retry_sleep", sleeps.append) + endpoint = f"api repos/{REPO}/pulls/7" + ("" if error == "before" else "/reviews?per_page=100&page=1") + if error in {"api", "recover", "before"}: + fault = {"stdout": "HTTP/2.0 503 Service Unavailable\r\nX-GitHub-Request-Id: GHREQ-8774\r\n\r\n{\"message\":\"Service unavailable github_pat_1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ\"}", "exit": 1} + publisher.respond(endpoint, fault, [{"state": "APPROVED", "commit_id": HEAD, "user": {"login": "trusted-publisher"}, "body": f"\nreview: **approve**"}] if error == "recover" else fault) elif error == "head": publisher.respond_pr_view(pr_json(), pr_json(headRefOid="b" * 40)) elif error == "publication": - publisher.respond(f"api repos/{REPO}/statuses/{HEAD}", {}, - {"stdout": "", "exit": 1, "stderr": "invalid description (HTTP 422)"}) + publisher.respond(f"api repos/{REPO}/statuses/{HEAD}", {}, {"stdout": "", "exit": 1, "stderr": "invalid description (HTTP 422)"}) publisher.respond(f"api repos/{REPO}/commits/{HEAD}/statuses", [{"context": "other"}]) else: monkeypatch.setenv("GITHUB_REPOSITORY", "other/repo") - with pytest.raises((github.GhError, hosted.LoopZeroError), match=(r"method=GET endpoint=/repos/acme/widgets/pulls/7/reviews status=503 request_id=GHREQ-8774 message=Service unavailable \[REDACTED\]" if error == "api" else None)) as raised: - hosted.main() - if error == "publication": - assert "invalid description (HTTP 422)" in str(raised.value) - statuses = [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] - assert statuses == ([] if error == "config" else ["pending", "pending"] - if error == "publication" else ["pending", "failure"]) + if error in {"api", "recover", "before"}: + assert hosted.main() == (1 if error == "before" else 0) and sleeps == ([5] if error == "recover" else list(github.RETRY_DELAYS)) + assert ("status=503 request_id=GHREQ-8774 message=Service unavailable [REDACTED]" in capsys.readouterr().err) == (error != "recover") + else: + with pytest.raises(hosted.LoopZeroError, match="invalid description" if error == "publication" else None): + hosted.main() + states = {"before": [], "config": [], "head": ["pending", "failure"], "api": ["pending"], "recover": ["pending", "success"]} + assert [json.loads(c["--input"])["state"] for c in publisher.calls if "--input" in c] == states.get(error, ["pending", "pending"]) @pytest.mark.parametrize("case,error,message", [ @@ -175,15 +176,15 @@ def test_source_errors_cannot_become_successful_waits(publisher, monkeypatch, er ("race", CandidateRaceError, "metadata changed"), ("malformed", CandidateError, "invalid payload"), ("head", hosted.LoopZeroError, "head changed"), ("publisher", CandidateError, "not open"), - ("interrupt", KeyboardInterrupt, ""), + ("interrupt", KeyboardInterrupt, ""), ("api", None, ""), ("manual", hosted.LoopZeroError, "pull_request_target creation"), ("metadata", None, ""), ("stale", hosted.LoopZeroError, "head is no longer current"), ("untrusted", CandidateError, "head event was not sent"), ]) def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatch, case, error, message): event = candidate_event() - event["action"] = "edited" if case == "metadata" else event["action"] - event["sender"]["id"] = 1 if case == "untrusted" else event["sender"]["id"] + event["action"], event["sender"]["id"] = ( + "edited" if case == "metadata" else event["action"], 1 if case == "untrusted" else event["sender"]["id"]) values = candidate_payloads(event) if case in {"valid", "hold"}: gh = FakeGh(fake_bin, tmp_path) @@ -202,11 +203,11 @@ def test_candidate_publication_and_event_controls(tmp_path, fake_bin, monkeypatc values["/repos/owner/repo/pulls/900"]["head"]["sha"] = "d" * 40 if case == "malformed": values["/repos/owner/repo/pulls/101"] = [] - (event_path := tmp_path / "event.json").write_text(json.dumps(event)) + (tmp_path / "event.json").write_text(json.dumps(event)) (tmp_path / "workflow.toml").write_text('[repo]\nname="owner/repo"\nbase="main"\n[delivery]\nreview_publishers=["trusted-publisher"]\n') monkeypatch.chdir(tmp_path) monkeypatch.setenv("GITHUB_REPOSITORY", "owner/repo") - monkeypatch.setenv("GITHUB_EVENT_PATH", str(event_path)) + monkeypatch.setenv("GITHUB_EVENT_PATH", str(tmp_path / "event.json")) attempts, sleeps = [], [] def api_get(path): @@ -228,15 +229,14 @@ def publish(*args): if args[3] == "failure" and case == "publisher": raise RuntimeError("publication details must not replace attestation error") monkeypatch.setattr(github, "commit_status", publish) - evaluated = [] - real_evaluate = hosted.eligibility.evaluate + evaluated, real_evaluate = [], hosted.eligibility.evaluate def evaluate(repo, number, head, base, publishers): evaluated.append((repo, number, head, base, publishers)) if case in {"valid", "hold"}: return real_evaluate(repo, number, head, base, publishers) - if case == "interrupt": - raise KeyboardInterrupt() + if fault := {"interrupt": KeyboardInterrupt(), "api": github.GhUnavailable(("gh",), "HTTP 503")}.get(case): + raise fault reasons = (github.MISSING_REVIEW_REASON,) if case == "policy" else () return github.Readiness(not reasons, reasons) if case not in {"valid", "hold"}: @@ -249,7 +249,7 @@ def evaluate(repo, number, head, base, publishers): hosted.main() else: assert hosted.main() == 0 - terminal = [] if case in {"manual", "metadata", "stale", "interrupt"} else ["failure"] + terminal = [] if case in {"manual", "metadata", "stale", "interrupt", "api"} else ["failure"] expected = [] if case in {"manual", "metadata", "stale"} else ["pending", *terminal] assert case != "race" or (len(attempts) == 3 and sleeps == [2, 2] and len(evaluated) == 6) if case == "valid": diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 8b6c5fc2..b6db1e0e 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -48,18 +48,20 @@ def test_branch_refuses_detached_head(repo: Path) -> None: worktree.branch(repo) -@pytest.mark.parametrize("branch", [None, "feature/ci+release"]) +@pytest.mark.parametrize("branch", [None, "feature/ci+release", "symbolic"]) def test_start_creates_branch_worktree_and_task_file(repo: Path, branch: str | None, monkeypatch) -> None: side = branch or "side" git(repo, "push", "-q", "origin", f"HEAD:refs/heads/{side}") upstream = commit_on_origin(repo, "feature.txt") - if branch: + if branch == "symbolic": + git(repo, "symbolic-ref", "refs/remotes/origin/main", "refs/heads/main") + elif branch: checkout = repo.parent / "single-branch" origin = (repo.parent / "origin.git").as_uri() git(repo, "clone", "-q", "--single-branch", "--branch", branch, origin, str(checkout)) assert not git(checkout, "for-each-ref", "refs/heads/main", "refs/remotes/origin/main").strip() repo = checkout - invoke = worktree._git + invoke, local_head = worktree._git, worktree.head(repo) def interleave(path, *args, **kwargs): result = invoke(path, *args, **kwargs) if args[0] == "fetch": @@ -71,7 +73,8 @@ def interleave(path, *args, **kwargs): assert wt == repo / ".worktrees" / "my-task" assert (wt / "feature.txt").exists(), "fetched origin/main before branching" assert worktree.branch(wt) == "lz/my-task" - assert worktree.head(wt) == upstream + assert worktree.head(wt) == upstream and worktree.head(repo) == local_head + assert git(repo, "rev-parse", "refs/remotes/origin/main").strip() == upstream assert worktree.base_sha(wt) == upstream text = worktree.task_text(wt) assert text.startswith("# My task\n") @@ -131,9 +134,17 @@ def interrupt_after_add(cwd, *args, **kwargs): assert task.read_text().endswith("(filled by `loopzero review`)\n") -def test_start_excludes_worktrees_and_task_dir(repo: Path) -> None: +@pytest.mark.parametrize("redirect", [None, "file", "directory"]) +def test_start_excludes_worktrees_and_task_dir(repo: Path, redirect: str | None) -> None: exclude = repo / ".git" / "info" / "exclude" exclude.write_text("*.log") # no trailing newline on purpose + if redirect: + link = exclude if redirect == "file" else exclude.parent + link.symlink_to(link.rename(repo.parent / "outside")) + with pytest.raises(worktree.WorktreeError, match="outside its Git directory"): + worktree.start(repo, "t1", "main") + assert exclude.read_text() == "*.log" and not (repo / ".worktrees").exists() + return old_inode = exclude.stat().st_ino wt = worktree.start(repo, "t1", "main") assert exclude.stat().st_ino != old_inode @@ -197,7 +208,7 @@ def test_start_explains_missing_origin(repo: Path, change: tuple[str, ...]) -> N def test_start_reports_git_failure_with_command(repo: Path) -> None: with pytest.raises(worktree.GitError) as info: worktree.start(repo, "nobase", "does-not-exist") - assert info.value.command[:2] == ("git", "fetch") + assert info.value.command[:2] == ("git", "ls-remote") assert info.value.tail