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
19 changes: 13 additions & 6 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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}")

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: Missing-base message says 'unique' when origin has no such branch

When the base branch does not exist on origin, ls-remote succeeds with empty output, and the user sees origin did not report a unique refs/heads/<base>. The common case is that the branch is missing, not that it is ambiguous, so 'unique' is misleading. Smallest fix: when advertised is empty, report something like origin has no branch <base>; check [repo] base_branch, and keep the 'unique' wording only when several lines match.

_git(repo_root, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--refmap=", "origin", base)

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: Fetching the ls-remote SHA can fail if origin moves between the two calls

Start now looks up the tip with ls-remote, then makes a second connection to fetch that SHA. If refs/heads/<base> moves between the two calls, the old SHA is no longer an advertised tip. A protocol-v0 server without uploadpack.allowReachableSHA1InWant (or allowAnySHA1InWant) then rejects the want ('not our ref'), and start fails with a raw fetch error. Protocol-v2 servers such as GitHub accept it, so this is an uncommon transient failure, not a correctness bug. Smallest fix: if the SHA fetch fails, redo the lookup and fetch once more, or say in the error that the base moved and start can be retried.

except GitError:
if "origin" not in _git(repo_root, "remote").splitlines():
raise WorktreeError(
Expand All @@ -145,7 +152,7 @@ def start(repo_root: Path, slug: str, base_branch: str) -> Path:
"with `git remote rename <name> 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:
Expand Down
27 changes: 18 additions & 9 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):

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: The interleaving fetch in the test is now dead weight

interleave fetches another branch after start's fetch. Its job was to overwrite FETCH_HEAD and prove start did not read it. Start now passes --no-write-fetch-head and uses the SHA from ls-remote, so this hook no longer exercises a real race. Either remove it, or make it push a new commit to origin's main between ls-remote and fetch. The second option would show that start branches from the commit it looked up and would cover the race in the first finding.

result = invoke(path, *args, **kwargs)
if args[0] == "fetch":
Expand All @@ -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")
Expand Down Expand Up @@ -131,15 +134,21 @@ 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.parent.mkdir(parents=True, exist_ok=True)
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
lines = exclude.read_text().splitlines()
assert lines == ["*.log", ".worktrees/", ".loopzero/"]
assert exclude.read_text().splitlines() == ["*.log", ".worktrees/", ".loopzero/"]
assert not worktree.is_dirty(wt), "fresh worktree with task.md is clean"
assert git(repo, "status", "--porcelain") == ""
installed = exclude.stat()
Expand Down Expand Up @@ -199,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


Expand Down
Loading