Skip to content
Merged
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
16 changes: 10 additions & 6 deletions src/loopzero/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,14 @@ def review_marker(head: str, kind: str, source: str = "model") -> str:
# --------------------------------------------------------------------------- git / context


def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT) -> str:
done = _proc.run(["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout)
def _git(cwd: Path, *args: str, timeout: float = GIT_TIMEOUT, paths: bool = False) -> str:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: cli._git(paths=True) copies the existing whitespace-preserving mode in worktree._git

worktree._git(..., preserve_whitespace=True) already decodes with the filesystem encoding and surrogateescape, and removes only the final newline. The new paths=True flag in cli._git repeats that decoding. It then makes each caller strip the newline itself: _toplevel and the --git-common-dir call both use .removesuffix("\n"). This leaves two policies to keep in sync, and a future caller that forgets removesuffix gets a path ending in a newline. Smallest fix: make paths=True return done.stdout.removesuffix("\n"), the same as preserve_whitespace, and drop the per-caller removesuffix. The -z porcelain call isn't affected because it splits on NUL. Or route these calls through the shared worktree helper.

done = _proc.run(
["git", *args], cwd=cwd, env_allowlist=worktree.GIT_ENV, timeout=timeout,
preserve_newlines=paths, encoding=sys.getfilesystemencoding() if paths else None,
)
if done.exit_code != 0:
raise CliError(f"git {' '.join(args)} failed: {_proc.tail(done.stderr, 1)}")
return done.stdout.strip()
return done.stdout if paths else done.stdout.strip()


def _require_push_target(wt: Path, repo: str) -> None:
Expand All @@ -104,16 +107,17 @@ def _git_push(wt: Path, args: list[str], *, force_lease: bool) -> None:


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


def _repo_root(wt: Path) -> Path:
"""The verified primary checkout or bare repository owning this linked worktree."""
first = _git(wt, "worktree", "list", "--porcelain", "-z").split("\0", 1)[0]
first = _git(wt, "worktree", "list", "--porcelain", "-z", paths=True).split("\0", 1)[0]
if not first.startswith("worktree "):
raise CliError("Git did not identify the primary worktree; refusing cleanup")
root = Path(first.removeprefix("worktree "))
common = Path(_git(wt, "rev-parse", "--path-format=absolute", "--git-common-dir")).resolve()
common = _git(wt, "rev-parse", "--path-format=absolute", "--git-common-dir", paths=True)
common = Path(common.removesuffix("\n")).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
6 changes: 4 additions & 2 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import re
import stat
import subprocess
import sys
import tempfile
from collections.abc import Iterator
from contextlib import contextmanager
Expand Down Expand Up @@ -62,10 +63,11 @@ def _git(
) -> str:
argv = ("git", *args)
done = run(argv, cwd=cwd, env_allowlist=GIT_ENV, timeout=timeout,
preserve_newlines=preserve_newlines)
preserve_newlines=preserve_newlines or preserve_whitespace,
encoding=sys.getfilesystemencoding() if preserve_whitespace else None)
if done.exit_code != 0:
raise GitError(argv, done.stderr or done.stdout)
if preserve_newlines:
if preserve_newlines and not preserve_whitespace:
return done.stdout
return done.stdout.removesuffix("\n") if preserve_whitespace else done.stdout.strip()

Expand Down
28 changes: 14 additions & 14 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -3281,9 +3281,9 @@ def test_merged_bare_primary_cleans_only_clean_linked_worktree(
if state == "dirty":
(linked / "README.md").write_text("uncommitted work\n")
original, cwds = cli._git, [] # #439: no cleanup git in a primary checkout
monkeypatch.setattr(cli, "_git", lambda cwd, *args: cwds.append(Path(cwd).resolve()) or (
monkeypatch.setattr(cli, "_git", lambda cwd, *args, **kwargs: cwds.append(Path(cwd).resolve()) or (
f"worktree {repo}\0" if state == "wrong_primary" and args == ("worktree", "list", "--porcelain", "-z")
else original(cwd, *args)))
else original(cwd, *args, **kwargs)))

code, out, err = run(capsys, "merge")
assert {primary.resolve(), repo.resolve()}.isdisjoint(cwds)
Expand Down Expand Up @@ -3869,21 +3869,21 @@ def test_review_and_ready_refuse_closed_pr(wt: Path, gh: FakeGh, capsys) -> None

@pytest.mark.parametrize("changed", [False, True])
def test_merge_of_externally_merged_pr_verifies_sha_and_cleans_up(
wt: Path, repo: Path, gh: FakeGh, capsys, changed
wt: Path, repo: Path, gh: FakeGh, capsys, changed, monkeypatch
) -> None:
arm_pr(gh, head_of(wt), state="MERGED", isDraft=False)
gh.append(f"api repos/{REPO}/pulls/7", merge_json(state='MERGED', head='f' * 40 if changed else head_of(wt), sha='e' * 40))
gh.respond("api -X", "")
collision, wt = wt, wt.with_name(wt.name + " ")
git(repo, "worktree", "move", str(collision), str(wt))
git(repo, "worktree", "add", "-qb", "lz/other", str(collision), "lz/t1")
monkeypatch.chdir(wt)
for branch, number in (("lz/t1", 7), ("lz/other", 8)):
arm_pr(gh, head_of(wt), branch=branch, number=number, state="MERGED", isDraft=False)
gh.append(f"api repos/{REPO}/pulls/{number}", merge_json(state='MERGED', head='f' * 40 if changed else head_of(wt), sha='e' * 40))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Rewritten test drops checks that no merge or deletion is attempted

The old test asserted that no pr merge call was made for an already-merged PR. For the head-changed case, it also asserted that no api -X call was made. The rewrite drops both checks and the gh.respond("api -X", "") fixture. The test still checks that the checkouts exist. However, a regression that calls gh pr merge on an already-merged PR, or starts remote branch deletion before refusing a moved head, would now pass. Consider restoring assert all(c["argv"][:2] != ["pr", "merge"] for c in gh.calls). Also consider asserting that no remote-ref deletion call happens when changed is true.

code, out, err = run(capsys, "merge")
assert (code, collision.exists(), wt.exists()) == (int(changed), True, changed)
if changed:
assert code == 1 and "head changed" in err and wt.exists()
assert all(c["argv"][:2] != ["api", "-X"] for c in gh.calls)
return
assert (code, err) == (0, "")
assert out.splitlines()[-1] == "e" * 40
assert f"PR #7 was already merged as {'e' * 12}" in out and "e" * 40 in out
assert not wt.exists()
assert all(c["argv"][:2] != ["pr", "merge"] for c in gh.calls)
assert "head changed" in err
else:
assert not err and f"PR #7 was already merged as {'e' * 12}" in out and out.endswith("e" * 40 + "\n")


def test_merge_queued_prints_and_keeps_worktree(wt: Path, gh: FakeGh, capsys, head) -> None:
Expand Down
Loading