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
11 changes: 10 additions & 1 deletion src/loopzero/_proc.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,12 @@
import selectors
import signal
import subprocess
import sys
import threading
import time
from collections.abc import Mapping, Sequence
from contextlib import contextmanager, suppress
from dataclasses import dataclass
from dataclasses import dataclass, replace
from pathlib import Path

from .types import LoopZeroError
Expand Down Expand Up @@ -146,6 +147,14 @@ def append(chunk: str) -> None:
return suffix


def run_git_paths(argv: Sequence[str], *, cwd: Path, env_allowlist: Sequence[str], timeout: float,
extra_env: Mapping[str, str] | None = None) -> Completed:
"""Read Git path records, removing the final LF from line-terminated output."""
done = run(argv, cwd=cwd, env_allowlist=env_allowlist, timeout=timeout, extra_env=extra_env,
preserve_newlines=True, encoding=sys.getfilesystemencoding())
return replace(done, stdout=done.stdout.removesuffix("\n"))


def run(
argv: Sequence[str],
*,
Expand Down
13 changes: 5 additions & 8 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,8 @@ def review_marker(head: str, kind: str, source: str = "model") -> str:

def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT, paths: bool = False,
extra_env: dict[str, str] | None = None) -> str:
done = _proc.run(
["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout, extra_env=extra_env,
preserve_newlines=paths, encoding=sys.getfilesystemencoding() if paths else None,
)
run = _proc.run_git_paths if paths else _proc.run
done = run(["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout, extra_env=extra_env)
if done.exit_code != 0:
raise CliError(f"git {' '.join(args)} failed: {_proc.tail(done.stderr, 1)}")
return done.stdout if paths else done.stdout.strip()
Expand Down Expand Up @@ -109,7 +107,7 @@ def _git_push(wt: Path, args: list[str], *, force_lease: bool) -> None:


def _toplevel() -> Path:
return Path(_git(Path.cwd(), "rev-parse", "--show-toplevel", paths=True).removesuffix("\n"))
return Path(_git(Path.cwd(), "rev-parse", "--show-toplevel", paths=True))


def _repo_root(wt: Path) -> Path:
Expand All @@ -118,8 +116,7 @@ def _repo_root(wt: Path) -> Path:
if not first.startswith("worktree "):
raise CliError("Git did not identify the primary worktree; refusing cleanup")
root = Path(first.removeprefix("worktree "))
common = _git(wt, "rev-parse", "--path-format=absolute", "--git-common-dir", paths=True)
common = Path(common.removesuffix("\n")).resolve()
common = Path(_git(wt, "rev-parse", "--path-format=absolute", "--git-common-dir", paths=True)).resolve()
if root.resolve() == wt.resolve() or common not in (root.resolve(), (root / ".git").resolve()):
raise CliError("primary repository does not own this linked worktree; refusing cleanup")
return root
Expand Down Expand Up @@ -784,7 +781,7 @@ def _lock_review(run_review: Callable[[argparse.Namespace, Path, Config], int]):
@wraps(run_review)
def locked(args: argparse.Namespace) -> int:
wt, config = _context(args, pin_checks=True)
git_dir = _git(wt, "rev-parse", "--absolute-git-dir")
git_dir = _git(wt, "rev-parse", "--absolute-git-dir", paths=True)
fd = os.open(git_dir, os.O_RDONLY | os.O_DIRECTORY)
try:
try:
Expand Down
4 changes: 2 additions & 2 deletions src/loopzero/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,13 +121,13 @@ def _remote_workflow(worktree: Path, branch: str, previous: Config | None, *, re
if fetched.exit_code != 0:
raise ConfigError(f"could not refresh origin/{branch}. {hint}")
directory_args = ["--path-format=absolute", "--git-common-dir"] if previous is not None else []
resolved = _proc.run(
resolved = _proc.run_git_paths(
["git", "rev-parse", *directory_args, "--verify", f"{ref}^{{commit}}"],
cwd=worktree, env_allowlist=worktree_mod.GIT_ENV, timeout=60,
)
if resolved.exit_code != 0:
raise ConfigError(f"{source} has no remote-tracking base commit. {hint}")
common_dir, _, revision = resolved.stdout.rstrip("\n").rpartition("\n")
common_dir, _, revision = resolved.stdout.rpartition("\n")
if (previous is not None and previous.base_branch == branch and previous.trusted_base_revision == revision
and common_dir and not _has_replacement_refs(Path(common_dir))):
return previous, revision
Expand Down
18 changes: 8 additions & 10 deletions src/loopzero/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,25 +318,23 @@ def _review_config(family: str, binary: Path, ro_paths: tuple[str, ...]) -> Conf


def _git_dir(cwd: Path, flag: str, env_allowlist: tuple[str, ...]) -> Path:
raw = _review_git(cwd, env_allowlist, f"rev-parse {flag}", "rev-parse", flag)
return (cwd / raw.strip()).resolve()
return (cwd / _review_git(cwd, env_allowlist, f"rev-parse {flag}", "rev-parse", flag, paths=True)).resolve()


def _review_git(cwd: Path, allowlist: tuple[str, ...], label: str, *args: str) -> str:
done = _proc.run(["git", *args], cwd=cwd, env_allowlist=allowlist, timeout=30)
def _review_git(cwd: Path, allowlist: tuple[str, ...], label: str, *args: str, paths: bool = False) -> str:
run = _proc.run_git_paths if paths else _proc.run
done = run(["git", *args], cwd=cwd, env_allowlist=allowlist, timeout=30)
if done.exit_code != 0:
raise RunnerBadOutput(f"git {label} exited {done.exit_code}", _tail(done.stderr))
return done.stdout


def _git_dirs(cwd: Path, env_allowlist: tuple[str, ...]) -> tuple[Path, Path]:
argv = ["git", "rev-parse", "--path-format=absolute", "--git-common-dir", "--git-dir"]
done = _proc.run(argv, cwd=cwd, env_allowlist=env_allowlist, timeout=30)
paths = done.stdout.removesuffix("\n").split("\n")
if done.exit_code == 0 and len(paths) == 2:
common_dir, git_dir = map(Path, paths)
if common_dir.is_absolute() and git_dir.is_absolute():
return common_dir.resolve(), git_dir.resolve()
done = _proc.run_git_paths(argv, cwd=cwd, env_allowlist=env_allowlist, timeout=30)
paths = [Path(path) for path in done.stdout.split("\n")]
if done.exit_code == 0 and len(paths) == 2 and all(path.is_absolute() for path in paths):
return paths[0].resolve(), paths[1].resolve()
# A path may contain a newline, which makes the combined output ambiguous.
return _git_dir(cwd, "--git-common-dir", env_allowlist), _git_dir(cwd, "--git-dir", env_allowlist)

Expand Down
8 changes: 4 additions & 4 deletions src/loopzero/sandbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -550,8 +550,9 @@ def bwrap_argv(
return argv


def _git(config: Config, worktree: Path, *args: str) -> str:
done = _proc.run(
def _git(config: Config, worktree: Path, *args: str, paths: bool = False) -> str:
run = _proc.run_git_paths if paths else _proc.run
done = run(
["git", *args], cwd=worktree, env_allowlist=config.env_allowlist, timeout=GIT_TIMEOUT
)
if done.exit_code != 0:
Expand All @@ -562,8 +563,7 @@ def _git(config: Config, worktree: Path, *args: str) -> str:


def _git_dir(config: Config, worktree: Path, flag: str) -> Path:
raw = Path(_git(config, worktree, "rev-parse", flag).strip())
return (raw if raw.is_absolute() else worktree / raw).resolve()
return (worktree / _git(config, worktree, "rev-parse", flag, paths=True)).resolve()


def _stage_unchanged(config: Config, worktree: Path, head: str) -> bool:
Expand Down
34 changes: 15 additions & 19 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,13 @@
import os
import re
import subprocess
import sys
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager, suppress
from pathlib import Path
from select import select

from loopzero._proc import build_env, run
from loopzero._proc import build_env, run, run_git_paths

GIT_ENV = ("PATH", "HOME", "LANG", "LC_ALL", "TERM", "GIT_SSH_COMMAND", "SSH_AUTH_SOCK")
_ABSOLUTE_COMMON_DIR = ("rev-parse", "--path-format=absolute", "--git-common-dir")
Expand Down Expand Up @@ -62,14 +61,13 @@ def _git(
preserve_whitespace: bool = False, preserve_newlines: bool = False,
) -> str:
argv = ("git", *args)
done = run(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout,
preserve_newlines=preserve_newlines or preserve_whitespace,
encoding=sys.getfilesystemencoding() if preserve_whitespace else None)
if preserve_whitespace:
done = run_git_paths(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout)
else:
done = run(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout, preserve_newlines=preserve_newlines)
if done.exit_code != 0:
raise GitError(argv, done.stderr or done.stdout)
if preserve_newlines and not preserve_whitespace:
return done.stdout
return done.stdout.removesuffix("\n") if preserve_whitespace else done.stdout.strip()
return done.stdout if preserve_newlines or preserve_whitespace else done.stdout.strip()


def branch_name(repo_root: Path, slug: str) -> str:
Expand Down Expand Up @@ -177,19 +175,17 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path:


def _resumable_head(repo_root: Path, wt: Path, expected_branch: str) -> str | None:
registered = _git(repo_root, "worktree", "list", "--porcelain", "-z").split("\0\0")
path_field = f"worktree {wt.resolve()}"
entry = next((item for item in registered if item.startswith(f"{path_field}\0")), "")
fields = entry.split("\0")
registered = _git(repo_root, "worktree", "list", "--porcelain", "-z", preserve_whitespace=True).split("\0\0")
path_field = f"worktree {wt.resolve()}\0"
fields = next((item for item in registered if item.startswith(path_field)), "").split("\0")
if (len(fields) != 3 or fields[2] != f"branch refs/heads/{expected_branch}"
or not (wt / ".git").is_file()):
return None
if _git(wt, *_ABSOLUTE_COMMON_DIR) != _git(repo_root, *_ABSOLUTE_COMMON_DIR) or branch(wt) != expected_branch:
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:
return None
current_head = head(wt)
if fields[1] != f"HEAD {current_head}" or is_dirty(wt):
return None
return current_head
return current_head if fields[1] == f"HEAD {current_head}" and not is_dirty(wt) else None


def _initialize_task(task: Path, text: str) -> None:
Expand Down Expand Up @@ -224,8 +220,8 @@ def head(wt: Path) -> str:


def is_linked_checkout(wt: Path) -> bool:
git_dir = _git(wt, "rev-parse", "--absolute-git-dir")
common_dir = _git(wt, *_ABSOLUTE_COMMON_DIR)
git_dir = _git(wt, "rev-parse", "--absolute-git-dir", preserve_whitespace=True)
common_dir = _git(wt, *_ABSOLUTE_COMMON_DIR, preserve_whitespace=True)
return git_dir != common_dir


Expand Down Expand Up @@ -326,7 +322,7 @@ def cleanup(wt: Path, expected_head: str) -> None:
raise WorktreeError(f"worktree is dirty, refusing to remove: {wt}")
_require_no_ignored_user_files(wt)
_git(gd, f"--git-dir={gd}", "worktree", "remove", str(wt)) # never the primary checkout
worktrees = _git(gd, f"--git-dir={gd}", "worktree", "list", "--porcelain", "-z")
worktrees = _git(gd, f"--git-dir={gd}", "worktree", "list", "--porcelain", "-z", preserve_whitespace=True)
if f"branch {ref}" in worktrees.split("\0"):
raise WorktreeError(f"local branch {name!r} is checked out in another worktree")
try:
Expand Down
62 changes: 27 additions & 35 deletions tests/test_candidate.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ def no_retry_delay(monkeypatch):
monkeypatch.setattr("loopzero.candidate._retry_sleep", lambda delay: clock.__setitem__(0, clock[0] + delay))


def event() -> dict:
def event(head: str = "c" * 40) -> dict:
repo = {"id": 7, "full_name": "owner/repo"}
bot = {
"id": 37929162,
Expand All @@ -49,7 +49,7 @@ def event() -> dict:
"state": "open",
"draft": True,
"user": bot,
"head": {"sha": "c" * 40, "ref": "mergify/merge-queue/batch", "repo": deepcopy(repo)},
"head": {"sha": head, "ref": "mergify/merge-queue/batch", "repo": deepcopy(repo)},
"base": {"sha": "b" * 40, "ref": "main", "repo": deepcopy(repo)},
},
}
Expand Down Expand Up @@ -80,6 +80,15 @@ def pull(number: int, sha: str) -> dict:
}


def expected_sources(*sources):
return [{"number": number, "head_sha": sha} for number, sha in sources]


def tree_commit(git, tree, *parents, subject):
parent_args = [arg for parent in parents for arg in ("-p", parent)]
return git("commit-tree", f"{tree}^{{tree}}", *parent_args, "-m", subject)


def source_payloads(values, head, *sources):
for number, sha in sources:
values[f"/repos/owner/repo/pulls/{number}"] = pull(number, sha)
Expand Down Expand Up @@ -129,10 +138,8 @@ def run_attestation(

def test_attests_nested_candidate_and_transitive_parent_sources() -> None:
seen: list[int] = []
assert run_attestation(source_policy=lambda number, _source: seen.append(number)) == [
{"number": 101, "head_sha": "1" * 40},
{"number": 102, "head_sha": "2" * 40},
]
sources = run_attestation(source_policy=lambda number, _: seen.append(number))
assert sources == expected_sources((101, "1" * 40), (102, "2" * 40))
assert seen == [101, 102]


Expand Down Expand Up @@ -259,8 +266,7 @@ def attest(
main_after=None, extra_source=None, lineage="vanished", run=attest_candidate,
held_source=None,
):
candidate_event = event()
candidate_event["pull_request"]["head"]["sha"] = head
candidate_event = event(head)
values = payloads(candidate_event)
source_payloads(values, head, (102, source))
queue = status()
Expand Down Expand Up @@ -296,7 +302,7 @@ def get(path):
def test_vanished_squash_parent_passes_real_tree_attestation(tree_candidate):
attest, _, _, _, _, source, _ = tree_candidate
seen = []
assert attest(policy=lambda n, _: seen.append(n)) == [{"number": 102, "head_sha": source}]
assert attest(policy=lambda n, _: seen.append(n)) == expected_sources((102, source))
assert seen == [102]


Expand All @@ -323,7 +329,7 @@ def check_environment(argv, **kwargs):
return popen(argv, **kwargs)

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


Expand All @@ -343,8 +349,7 @@ def test_vanished_parent_rejects_unauthorized_trees(tree_candidate, mutation):
if mutation == "tampered":
# A forged resolution retains the exact original merge parents.
parents = git("show", "-s", "--format=%P", candidate_sha).split()
changed = git("commit-tree", git("rev-parse", f"{changed}^{{tree}}"),
"-p", parents[0], "-p", parents[1], "-m", "forged merge")
changed = tree_commit(git, changed, *parents, subject="forged merge")
kwargs["head"] = changed
with pytest.raises(CandidateError, match=r"Missing Mergify parent batches parent:.*"
r"(tree mismatch|objects unavailable)"):
Expand All @@ -367,8 +372,7 @@ def test_vanished_parent_rejects_main_change(tree_candidate):

def test_vanished_parent_rejects_ambiguous_topology(tree_candidate):
attest, git, _, base, parent, source, candidate_sha = tree_candidate
head = git("commit-tree", git("rev-parse", f"{candidate_sha}^{{tree}}"),
"-p", base, "-p", parent, "-p", source, "-m", "octopus")
head = tree_commit(git, candidate_sha, base, parent, source, subject="octopus")
with pytest.raises(CandidateError, match="parent: ambiguous"):
attest(head=head)

Expand Down Expand Up @@ -410,17 +414,11 @@ def test_intelflo_candidate_policy_parity(tree_candidate, candidate_policy, monk
attest, git, commit, base, parent, source, candidate_sha = tree_candidate
implementation, run = candidate_policy
if case == "single":
head = git("commit-tree", f"{source}^{{tree}}", "-p", base, "-p", source,
"-m", "single source integration")
assert attest(run=run, lineage="single", head=head, main_head=base) == [
{"number": 102, "head_sha": source},
]
head = tree_commit(git, source, base, source, subject="single source integration")
assert attest(run=run, lineage="single", head=head, main_head=base) == expected_sources((102, source))
return
if case == "stacked":
assert attest(run=run, lineage="stacked", main_head=base) == [
{"number": 101, "head_sha": parent},
{"number": 102, "head_sha": source},
]
assert attest(run=run, lineage="stacked", main_head=base) == expected_sources((101, parent), (102, source))
return

# The earlier batch has landed by squash. Both live source heads still need
Expand All @@ -431,18 +429,14 @@ def test_intelflo_candidate_policy_parity(tree_candidate, candidate_policy, monk
git("merge", "--no-ff", second, "-m", "second integration")
head = git("rev-parse", "HEAD")
if case == "combined":
assert attest(run=run, head=head, extra_source=second) == [
{"number": 101, "head_sha": second},
{"number": 102, "head_sha": source},
]
assert attest(run=run, head=head, extra_source=second) == expected_sources((101, second), (102, source))
return

kwargs = {}
if case == "mismatch":
changed = commit("injected", "unreviewed\n")
parents = git("show", "-s", "--format=%P", head).split()
head = git("commit-tree", f"{changed}^{{tree}}", "-p", parents[0], "-p", parents[1],
"-m", "forged merge")
head = tree_commit(git, changed, *parents, subject="forged merge")
diagnostic = "tree mismatch"
elif case == "incomplete":
kwargs["main_head"] = ""
Expand All @@ -451,8 +445,7 @@ def test_intelflo_candidate_policy_parity(tree_candidate, candidate_policy, monk
kwargs["main_after"] = base
diagnostic = "main changed"
elif case == "ambiguous":
head = git("commit-tree", f"{head}^{{tree}}", "-p", candidate_sha, "-p", second,
"-p", parent, "-m", "octopus")
head = tree_commit(git, head, candidate_sha, second, parent, subject="octopus")
diagnostic = "ambiguous"
else:
monkeypatch.setattr(implementation, "_TREE_OBJECTS", 1)
Expand All @@ -478,8 +471,7 @@ def test_vanished_parent_rejects_conflicting_current_main(tree_candidate):
@pytest.mark.parametrize("timing", ["metadata", "policy", "initial", TypeError, AttributeError, KeyError])
def test_predecessor_landing_restarts_complete_attestation(tree_candidate, monkeypatch, timing):
_, git, _, _, parent, source, head = tree_candidate
candidate_event = event()
candidate_event["pull_request"]["head"]["sha"] = head
candidate_event = event(head)
values = payloads(candidate_event)
source_payloads(values, head, (101, parent), (102, source))
main, vanished = git("rev-parse", "main"), status()
Expand Down Expand Up @@ -529,7 +521,7 @@ def verify_tree(repo, main_sha, candidate_sha, sources):
assert seen == [101] and source_reads == 1 and not sleeps
return
assert run_attestation(candidate_event, github_get=get, mergify_status=lineage,
source_policy=policy) == [{"number": 102, "head_sha": source}]
source_policy=policy) == expected_sources((102, source))
assert seen == {"metadata": [101, 102, 102], "policy": [101, 102], "initial": [102]}[timing]
assert candidate_reads == (4 if timing == "metadata" else 3)
assert verified == [(main, head, [source])] and sleeps == [2]
Expand Down Expand Up @@ -670,7 +662,7 @@ def run():
return run_attestation(github_payloads=values, mergify_status=read_status,
source_policy=lambda n, _: seen.append(n))
if stop in {"settled", "changed"}:
assert run() == [{"number": 101, "head_sha": "1" * 40}, {"number": 102, "head_sha": "2" * 40}]
assert run() == expected_sources((101, "1" * 40), (102, "2" * 40))
assert seen == [101, 102] * (2 if stop == "changed" and second else 1)
else:
with pytest.raises(CandidateError, match="superseded" if stop == "closed" else "not exactly one live"):
Expand Down
Loading
Loading