diff --git a/src/loopzero/_proc.py b/src/loopzero/_proc.py index a3a81567..1f850468 100644 --- a/src/loopzero/_proc.py +++ b/src/loopzero/_proc.py @@ -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 @@ -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], *, diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index abbbcad7..e6012622 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -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() @@ -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: @@ -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 @@ -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: diff --git a/src/loopzero/config.py b/src/loopzero/config.py index a6f72af2..2db069b3 100644 --- a/src/loopzero/config.py +++ b/src/loopzero/config.py @@ -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 diff --git a/src/loopzero/runners.py b/src/loopzero/runners.py index 833e97e9..ff8f8ae1 100644 --- a/src/loopzero/runners.py +++ b/src/loopzero/runners.py @@ -318,12 +318,12 @@ 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 @@ -331,12 +331,10 @@ def _review_git(cwd: Path, allowlist: tuple[str, ...], label: str, *args: str) - 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) diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index 64ab10f1..945c17c9 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -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: @@ -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: diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index 87a5c368..fe421d6d 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -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") @@ -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: @@ -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: @@ -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 @@ -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: diff --git a/tests/test_cli.py b/tests/test_cli.py index 1cc17eba..a44ef2d3 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -725,10 +725,10 @@ def dispatch(_config, _wt, _head, _base, command, _timeout): raise KeyboardInterrupt return CheckResult(command, 0, 0.0, "") - def check_git(config, path, *args): + def check_git(config, path, *args, **kwargs): if interrupt and len(calls) == 2 and args == ("rev-parse", "HEAD"): raise KeyboardInterrupt - return original_git(config, path, *args) + return original_git(config, path, *args, **kwargs) monkeypatch.setattr(cli, "_context", context) monkeypatch.setattr(cli.sandbox, "_dispatch_one", dispatch) diff --git a/tests/test_runners.py b/tests/test_runners.py index bd6754d3..00b93e57 100644 --- a/tests/test_runners.py +++ b/tests/test_runners.py @@ -612,7 +612,7 @@ def test_reviewer_does_not_bind_missing_auth_paths(repo, fake_bin, tmp_path, fak assert all(destination == SANDBOX_HOME for _, destination in _pairs(_bwrap_argv(fake_bwrap), "--bind")) -@pytest.mark.parametrize("repo_name", ["repo", "repo\ncommon"], ids=["ordinary", "newline"]) +@pytest.mark.parametrize("repo_name", ["repo", "repo\ncommon", "repo\rcommon"], ids=["ordinary", "newline", "carriage-return"]) def test_linked_worktree_and_git_directory_are_read_only( git_repo: Path, tmp_path: Path, fake_bin: Path, monkeypatch, repo_name: str, ) -> None: @@ -626,6 +626,7 @@ def test_linked_worktree_and_git_directory_are_read_only( def record(config, cwd, home, common_dir, git_dir, **kwargs): assert (common_dir, git_dir) == (common, common / "worktrees" / linked.name) + assert sandbox._git_dir(config, cwd, "--git-common-dir") == common argv = bwrap_argv(config, cwd, home, common_dir, git_dir, **kwargs) captured.extend(argv) return argv @@ -634,8 +635,7 @@ def record(config, cwd, home, common_dir, git_dir, **kwargs): _fake_review(fake_bin, "claude") assert _review("claude", linked).verdict == "approve" binds = _pairs(captured, "--ro-bind") - assert (str(linked.resolve()),) * 2 in binds - assert (str(common),) * 2 in binds + assert all((str(path),) * 2 in binds for path in (linked.resolve(), common)) @pytest.mark.parametrize("family", ["claude", "codex"]) diff --git a/tests/test_worktree.py b/tests/test_worktree.py index 14e0ca42..5592750e 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -98,6 +98,7 @@ def interleave(path, *args, **kwargs): @pytest.mark.parametrize("state", ["same-base", "dirty", "moved-base"]) def test_start_retries_after_git_creates_worktree(repo, monkeypatch, state): + repo = repo.rename(repo.with_name("repo\rreturn")) base = commit_on_origin(repo, "base-change") wt = repo / ".worktrees" / "my-task" run_git = worktree._git @@ -127,8 +128,7 @@ def interrupt_after_add(cwd, *args, **kwargs): worktree.start(repo, "my-task", "main") for detail in (base, "origin/main", current_base, "new slug"): assert detail in str(error.value) - assert worktree.branch(wt) == "lz/my-task" - assert worktree.head(wt) == base + assert (worktree.branch(wt), worktree.head(wt)) == ("lz/my-task", base) assert not task.exists() return