Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 23 additions & 21 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -707,6 +707,7 @@ def cmd_pr(args: argparse.Namespace) -> int:
existing = _sync_task_narrative(wt, pr.body or "") if pr is not None else None
body = _pr_body(wt, head, config, existing)
force_lease = False
git_branch = os.fsdecode(branch.encode("utf-8", "surrogateescape"))
push = ["push", "-u", "origin"]
if pr is not None:
known = config_mod.run_git(wt, "cat-file", "-e", f"{pr.head_sha}^{{commit}}")
Expand All @@ -716,13 +717,13 @@ def cmd_pr(args: argparse.Namespace) -> int:
)
force_lease = pr.head_sha != head and not _is_ancestor(wt, pr.head_sha, head)
if force_lease:
previous_heads = _git(wt, "reflog", "show", "--format=%H", f"refs/heads/{branch}").splitlines()
previous_heads = _git(wt, "reflog", "show", "--format=%H", f"refs/heads/{git_branch}").splitlines()
if not any(_is_ancestor(wt, pr.head_sha, previous) for previous in previous_heads):
raise CliError(
f"PR head {pr.head_sha[:12]} is absent from this task branch's history; integrate it first"
)
push.extend(("--porcelain", f"--force-with-lease={branch}:{pr.head_sha}"))
push.append(branch)
push.extend(("--porcelain", f"--force-with-lease={git_branch}:{pr.head_sha}"))
push.append(git_branch)
_require_push_target(wt, config.repo)
_git_push(wt, push, force_lease=force_lease)
if pr is not None:
Expand Down Expand Up @@ -1847,18 +1848,22 @@ def _cleanup_remote_refs(wt: Path, config: Config, branch: str, expected_head: s
def _delete_tracking_ref(wt: Path, branch: str, expected_head: str) -> None:
if not branch.startswith("lz/") or branch.count("/") != 1:
return
ref = f"refs/remotes/origin/{branch}"
ref = os.fsdecode(f"refs/remotes/origin/{branch}".encode("utf-8", "surrogateescape"))
try:
_repo_root(wt)
current = _git(wt, "for-each-ref", "--format=%(objectname) %(refname) %(symref)", ref)
current = _git(wt, "for-each-ref", "--format=%(objectname) %(refname) %(symref)", ref, paths=True).rstrip(" ")
if current == f"{expected_head} {ref}":
_git(wt, "update-ref", "--no-deref", "-d", ref, expected_head)
except (CliError, OSError, _proc.ProcTimeout) as exc:
print(f"warning: merged but tracking ref cleanup failed for {ref}: {exc}", file=sys.stderr)


def cmd_resolve(args: argparse.Namespace) -> int:
def _print_display(text: str) -> None:
encoding = getattr(sys.stdout, "encoding", None) or "utf-8"
print(text.encode(encoding, "backslashreplace").decode(encoding))


def cmd_resolve(args: argparse.Namespace) -> int:
wt, config = _context(args, pin_checks=True) # publishers come from the base, not the PR
branch = worktree.branch(wt)
pr = _require_pr(config, branch)
Expand All @@ -1867,10 +1872,10 @@ def cmd_resolve(args: argparse.Namespace) -> int:
publishers = config.review_publishers or (github.login(),)
if not args.finding:
for marker_id, _thread, f in github.open_findings(config.repo, pr.number, publishers):
print(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}".encode(encoding, "backslashreplace").decode(encoding))
_print_display(f"{marker_id} {f.severity} {f.path or '-'}:{f.line or '-'} {f.title}")
return 0
finding = github.resolve_finding(config.repo, pr.number, args.finding, args.reply, publishers)
print(f"resolved {args.finding}: {finding.title}".encode(encoding, "backslashreplace").decode(encoding))
_print_display(f"resolved {args.finding}: {finding.title}")
try:
with github.api_error_diagnostics():
remaining = github.open_blocking_findings(config.repo, pr.number, None, publishers)
Expand All @@ -1894,27 +1899,24 @@ def cmd_status(args: argparse.Namespace) -> int:
wt = _toplevel()
config = _load_config(args, wt, pin_checks=True)
branch, head = worktree.branch(wt), worktree.head(wt)
print(f"worktree: {wt}")
print(f"branch: {branch}")
print(f"head: {head}")
print(f"base: {config.base_branch}")
print(f"dirty: {'yes' if worktree.is_dirty(wt) else 'no'}")
_print_display(f"worktree: {wt}\nbranch: {branch}\nhead: {head}\nbase: {config.base_branch}")
_print_display(f"dirty: {'yes' if worktree.is_dirty(wt) else 'no'}")
pr = github.pr_for_branch(config.repo, branch)
if pr is None:
print("pr: none (commit changes and pass `loopzero check` before `loopzero pr`)")
_print_display("pr: none (commit changes and pass `loopzero check` before `loopzero pr`)")
return 0
print(f"pr: #{pr.number} {pr.url} ({'draft' if pr.is_draft else 'ready'}, {pr.state})")
_print_display(f"pr: #{pr.number} {pr.url} ({'draft' if pr.is_draft else 'ready'}, {pr.state})")
reviews = _pr_reviews(config.repo, pr.number)
markers = _pr_markers(reviews, head, config.review_publishers, repo=config.repo, number=pr.number)
if markers:
latest = markers[-1]
print(f"review: {latest.kind} on {latest.head[:12]} ({latest.state.lower() or 'posted'})")
_print_display(f"review: {latest.kind} on {latest.head[:12]} ({latest.state.lower() or 'posted'})")
else:
print("review: none on this PR")
_print_display("review: none on this PR")
readiness = _readiness(wt, config, pr, head, reviews, diagnostics=True)
print(f"ready: {'yes' if readiness.ready else 'no'}")
_print_display(f"ready: {'yes' if readiness.ready else 'no'}")
for reason in readiness.reasons:
print(f" - {reason}")
_print_display(f" - {reason}")
if config.merge_strategy == "mergify" and pr.state == "OPEN" and pr.head_sha == head:
_print_mergify_status(config, pr, readiness)
return 0
Expand All @@ -1932,9 +1934,9 @@ def _print_mergify_status(config: Config, pr: github.PR, readiness: github.Readi
label = "ejected"
elif requested or (readiness.ready and report):
label = "waiting for admission"
print(f"mergify: {label} ({queue})")
_print_display(f"mergify: {label} ({queue})")
if label == "waiting for admission" and report:
print(f" Mergify report: {report}")
_print_display(f" Mergify report: {report}")


def main(argv: list[str] | None = None) -> int:
Expand Down
4 changes: 2 additions & 2 deletions src/loopzero/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120,
try:
done = run(list(argv), cwd=cwd, env_allowlist=GH_ENV,
extra_env={"GH_TOKEN": selected} if selected else None,
timeout=_read_timeout(timeout, scoped=read_only))
timeout=_read_timeout(timeout, scoped=read_only), encoding="utf-8")
except ToolMissing as exc:
raise GhMissing(argv, str(exc), token=selected,
guidance=f"\nInstall GitHub CLI, then {GH_AUTH_REMEDY}") from exc
Expand Down Expand Up @@ -1517,7 +1517,7 @@ def delete_remote_branch(repo: str, branch: str, expected_head: str) -> bool:
current = _remote_branch_head(endpoint)
if current != expected_head:
return current is None
ref = f"refs/heads/{branch}"
ref = os.fsdecode(f"refs/heads/{branch}".encode("utf-8", "surrogateescape"))
argv = ("git", "-c", "credential.helper=!gh auth git-credential",
"push", f"--force-with-lease={ref}:{expected_head}",
f"https://github.com/{repo}.git", f":{ref}")
Expand Down
19 changes: 9 additions & 10 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,8 @@ def __init__(self, command: tuple[str, ...], tail: str) -> None:
super().__init__(f"{' '.join(command)} failed: {tail.strip()[-400:]}")


def _git(
cwd: Path, *args: str, timeout: float = 120,
preserve_whitespace: bool = False, preserve_newlines: bool = False,
) -> str:
def _git(cwd: Path, *args: str, timeout: float = 120,
preserve_whitespace: bool = False, preserve_newlines: bool = False) -> str:
argv = ("git", *args)
if preserve_whitespace:
done = run_git_paths(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout)
Expand Down Expand Up @@ -273,7 +271,7 @@ def _resumable_head(repo_root: Path, wt: Path, expected_branch: str) -> str | No
or not (wt / ".git").is_file()):
return None
common = _git(repo_root, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True)
if _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True) != common or branch(wt) != expected_branch:
if _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True) != common or branch(wt, native=True) != expected_branch:
return None
current_head = head(wt)
return current_head if fields[1] == f"HEAD {current_head}" and not is_dirty(wt) else None
Expand Down Expand Up @@ -303,11 +301,11 @@ def is_linked_checkout(wt: Path) -> bool:
return git_dir != common_dir


def branch(wt: Path) -> str:
def branch(wt: Path, *, native: bool = False) -> str:
name = _git(Path(wt), "branch", "--show-current", preserve_whitespace=True)
if not name:
raise WorktreeError("HEAD is detached. Switch to a branch and retry.")
return name
return name if native else os.fsencode(name).decode("utf-8", "surrogateescape")


def task_text(wt: Path) -> str:
Expand Down Expand Up @@ -354,7 +352,8 @@ def _lock_verified_ref(wt: Path, ref: str, expected_head: str) -> Iterator[None]
) as transaction:
assert transaction.stdin is not None and transaction.stdout is not None
try:
transaction.stdin.write(f"option no-deref\nverify {ref} {expected_head}\nprepare\n")
wire_ref = os.fsencode(ref).decode("utf-8", "surrogateescape")
transaction.stdin.write(f"option no-deref\nverify {wire_ref} {expected_head}\nprepare\n")
transaction.stdin.flush()
if not select([transaction.stdout], [], [], 30)[0]:
raise GitError(argv, "timed out verifying the merged branch")
Expand Down Expand Up @@ -390,11 +389,11 @@ def cleanup(wt: Path, expected_head: str) -> None:
raise WorktreeError(f"no such worktree: {wt}")
if head(wt) != expected_head:
raise WorktreeError("local HEAD differs from merged PR head")
name = branch(wt)
name = branch(wt, native=True)
gd = Path(_git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True))
ref = f"refs/heads/{name}"
with _lock_verified_ref(wt, ref, expected_head):
if branch(wt) != name:
if branch(wt, native=True) != name:
raise WorktreeError("local branch changed during merge cleanup")
if is_dirty(wt):
raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}")
Expand Down
86 changes: 31 additions & 55 deletions tests/test_candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from itertools import cycle
from os import environ
from shutil import copytree
from unittest.mock import Mock

import pytest

Expand Down Expand Up @@ -125,10 +126,8 @@ def run_attestation(
run=attest_candidate,
):
candidate_event = candidate_event or event()
reads, values = (
cycle(status_reads or [status()]),
github_payloads or payloads(candidate_event),
)
reads = cycle(status_reads or [status()])
values = github_payloads or payloads(candidate_event)
return run(
candidate_event,
github_get=github_get or (lambda path: deepcopy(values[path])),
Expand Down Expand Up @@ -158,10 +157,9 @@ def test_attests_nested_candidate_and_transitive_parent_sources() -> None:
)
def test_rejects_forged_bot_or_prefix(mutation, message: str) -> None:
candidate_event = event()
original_payloads = payloads(candidate_event)
mutation(candidate_event)
with pytest.raises(CandidateError, match=message):
run_attestation(candidate_event=candidate_event, github_payloads=original_payloads)
run_attestation(candidate_event=candidate_event, github_payloads=payloads(event()))


@pytest.mark.parametrize("case,diagnostic", [
Expand Down Expand Up @@ -243,8 +241,21 @@ def commit(name, content):
return git("rev-parse", "HEAD")

popen = subprocess.Popen
observed_transport = set()

def isolated_fetch(argv, **kwargs):
if environ.get("HTTPS_PROXY") == "http://proxy.invalid:8080" and "git" in argv:
env = kwargs["env"]
transport = {"HTTPS_PROXY", "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0"}
if "fetch" in argv:
observed_transport.add("fetch")
assert env["HTTPS_PROXY"] == environ["HTTPS_PROXY"]
assert (env["GIT_CONFIG_COUNT"], env["GIT_CONFIG_KEY_0"]) == ("1", "http.extraHeader")
header = env["GIT_CONFIG_VALUE_0"].removeprefix("Authorization: Basic ")
assert base64.b64decode(header) == b"x-access-token:secret-token"
else:
observed_transport.add("plumbing")
assert not transport & env.keys()
assert not any(arg.startswith("--as") for arg in argv) # arm64 Git exceeds RLIMIT_AS
if "fetch" in argv:
assert "https://github.com/owner/repo.git" in argv
Expand Down Expand Up @@ -294,47 +305,24 @@ def get(path):

if base_branch != "main":
run = partial(run, base_branch=base_branch)
return run_attestation(candidate_event, github_get=get, status_reads=[queue],
source_policy=policy, run=run)
sources = run_attestation(candidate_event, github_get=get, status_reads=[queue],
source_policy=policy, run=run)
if environ.get("HTTPS_PROXY") == "http://proxy.invalid:8080":
assert observed_transport == {"fetch", "plumbing"}
return sources

return attest, git, commit, base, parent, source, candidate_sha


@pytest.mark.parametrize("base_branch", ["main", "trunk"])
def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate, base_branch):
def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate, base_branch, monkeypatch):
monkeypatch.setenv("HTTPS_PROXY", "http://proxy.invalid:8080")
attest, _, _, _, _, source, _ = tree_candidate
seen = []
assert attest(base_branch=base_branch, policy=lambda n, _: seen.append(n)) == expected_sources((102, source))
assert seen == [102]


def test_candidate_transport_configuration_is_scoped_to_fetch(tree_candidate, monkeypatch):
attest, _, _, _, _, source, _ = tree_candidate
popen = subprocess.Popen
seen = set()
proxy = "http://proxy.invalid:8080"
monkeypatch.setenv("HTTPS_PROXY", proxy)

def check_environment(argv, **kwargs):
if "git" in argv:
env = kwargs["env"]
if "fetch" in argv:
seen.add("fetch")
assert env["HTTPS_PROXY"] == proxy
assert env["GIT_CONFIG_COUNT"] == "1"
assert env["GIT_CONFIG_KEY_0"] == "http.extraHeader"
header = env["GIT_CONFIG_VALUE_0"].removeprefix("Authorization: Basic ")
assert base64.b64decode(header) == b"x-access-token:secret-token"
else:
seen.add("non-fetch")
assert not {"HTTPS_PROXY", "GIT_CONFIG_COUNT", "GIT_CONFIG_KEY_0", "GIT_CONFIG_VALUE_0"} & env.keys()
return popen(argv, **kwargs)

monkeypatch.setattr(subprocess, "Popen", check_environment)
assert attest() == expected_sources((102, source))
assert seen == {"fetch", "non-fetch"}


@pytest.mark.parametrize("mutation,diagnostic", [
("replaced", "tree mismatch"), ("withdrawn", "tree mismatch"), ("extra", "tree mismatch|objects unavailable"),
("tampered", "tree mismatch"), ("missing", "objects unavailable"),
Expand Down Expand Up @@ -403,10 +391,7 @@ def run(event, *, github_get, mergify_status, source_policy):

@pytest.fixture(params=["loopzero", "intelflo"])
def candidate_policy(request):

if request.param == "intelflo":
return request.getfixturevalue("intelflo_policy")
return candidate, attest_candidate
return request.getfixturevalue("intelflo_policy") if request.param == "intelflo" else (candidate, attest_candidate)


@pytest.mark.parametrize("case", [
Expand Down Expand Up @@ -566,10 +551,7 @@ def test_nonrace_failure_does_not_retry(monkeypatch, failure, reread):
live["batches"].pop(0)
values["/repos/owner/repo/git/ref/heads/main"] = {"object": {"sha": "b" * 40}}

def mismatch(*_):
raise CandidateError("candidate tree mismatch")

monkeypatch.setattr(candidate, "_verify_tree", mismatch)
monkeypatch.setattr(candidate, "_verify_tree", Mock(side_effect=CandidateError("candidate tree mismatch")))

def get(path):
if path == "/apps/mergify":
Expand All @@ -583,10 +565,7 @@ def get(path):
return deepcopy(reread)
return result

def policy(*_):
if failure == "policy":
raise expected

policy = Mock(side_effect=expected if failure == "policy" else None)
monkeypatch.setattr(candidate, "_retry_sleep", sleeps.append)
with pytest.raises(CandidateError) as caught:
run_attestation(github_get=get, status_reads=[live], source_policy=policy)
Expand Down Expand Up @@ -651,9 +630,8 @@ def read_status(*_):
or (stop == "changed" and len(reads) >= 6)
) else ambiguous
monkeypatch.setattr(candidate, "_retry_sleep", sleep)
def run():
return run_attestation(github_payloads=values, mergify_status=read_status,
source_policy=lambda n, _: seen.append(n))
run = partial(run_attestation, github_payloads=values, mergify_status=read_status,
source_policy=lambda n, _: seen.append(n))
if stop in {"settled", "changed"}:
assert run() == expected_sources((101, "1" * 40), (102, "2" * 40))
assert seen == [101, 102] * (2 if stop == "changed" and second else 1)
Expand Down Expand Up @@ -695,10 +673,8 @@ def wait(self, timeout=None):

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:
bound = pytest.raises(CandidateError, match="Git object/size bound exceeded")
with bound if outcome == "bound" else nullcontext():
assert git("test-command") == ""

assert waits == {"bound": [0.02, None], "normal": [0.02], "fetch": []}[outcome]
Expand Down
Loading
Loading