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
49 changes: 32 additions & 17 deletions src/loopzero/worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,6 +216,37 @@ def _ensure_excludes(repo_root: Path) -> None:
return


def _fetch_base(repo_root: Path, base_branch: str) -> str:
remote_ref, tracking = f"refs/heads/{base_branch}", f"refs/remotes/origin/{base_branch}"
try:
valid = run(("git", "check-ref-format", remote_ref), cwd=repo_root, env_allowlist=GIT_ENV, timeout=30)
symbolic = run(("git", "symbolic-ref", "-q", tracking), cwd=repo_root, env_allowlist=GIT_ENV, timeout=30)
modules = repo_root / _git(repo_root, "rev-parse", "--git-path", "modules", preserve_whitespace=True)
if valid.exit_code == 0 and symbolic.exit_code == 1 and not modules.exists():
fetch = ("git", "fetch", "--porcelain", "--verbose", "--no-tags", "--no-prune",
"--no-write-fetch-head", "--refmap=", "origin", f"+{remote_ref}:{tracking}")
result = run(fetch, cwd=repo_root, env_allowlist=GIT_ENV, timeout=120)
if result.exit_code != 129: # Older Git does not accept --porcelain.
row = result.stdout.removesuffix("\n").rsplit(" ", 2)
if result.exit_code or len(row) != 3 or row[-1] != tracking:
raise GitError(fetch, result.stderr or result.stdout or f"origin did not report {remote_ref}")
return row[1]
lookup = ("ls-remote", "--refs", "origin", remote_ref)
base, _, ref = _git(repo_root, *lookup).partition("\t")
if ref != remote_ref:
raise GitError(("git", *lookup), f"origin did not report a unique {remote_ref}")
_git(repo_root, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--refmap=", "origin", base)
_git(repo_root, "update-ref", "--no-deref", tracking, base)
return base
except GitError:
if "origin" in _git(repo_root, "remote").splitlines():
raise
raise WorktreeError(
"no Git remote named 'origin'. Add it with `git remote add origin <url>` using the URL for the "
"repository in `[repo] name`, or rename that remote with `git remote rename <name> origin`."
) from None


def start(repo_root: Path, slug: str, base_branch: str) -> Path:
"""Create a task worktree or finish initializing an interrupted start."""
repo_root = Path(repo_root)
Expand All @@ -228,23 +259,7 @@ 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}")
remote_ref = f"refs/heads/{base_branch}"
lookup = ("ls-remote", "--refs", "origin", remote_ref)
try:
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}")
_git(repo_root, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", "--refmap=", "origin", base)
except GitError:
if "origin" not in _git(repo_root, "remote").splitlines():
raise WorktreeError(
"no Git remote named 'origin'. Add it with `git remote add origin <url>` "
"using the URL for the repository in `[repo] name`, or rename that remote "
"with `git remote rename <name> origin`."
) from None
raise
_git(repo_root, "update-ref", "--no-deref", f"refs/remotes/origin/{base_branch}", base)
base = _fetch_base(repo_root, base_branch)
if existing:
existing_head = _resumable_head(repo_root, wt, branch)
if existing_head is None:
Expand Down
21 changes: 12 additions & 9 deletions tests/test_worktree.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,27 +51,29 @@ def test_branch_reads_valid_names_and_rejects_detached_head(repo: Path, slug: st
worktree.branch(repo)


@pytest.mark.parametrize("branch", [None, "feature/ci+release", "symbolic"])
@pytest.mark.parametrize("branch", [None, "feature/ci+release", "symbolic", "legacy"])

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: No tests for the initialized-submodule and invalid-ref-name fallbacks

The acceptance criteria say three cases must keep using the existing ls-remote + exact-SHA fetch path: initialized submodules, invalid base ref names and symbolic tracking refs. The parametrized test covers symbolic tracking refs and the legacy-Git 129 fallback, but nothing exercises modules.exists() (the point of commit 3684a7d) or a check-ref-format failure. A later refactor could drop either guard without any test failing. Smallest fix: add a submodule case that creates $(git rev-parse --git-path modules) before start, and assert through the existing run monkeypatch that no git fetch --porcelain call was made and that ls-remote ran. Optionally, add a case that passes a base name check-ref-format rejects and assert the command reported in the GitError is ls-remote.

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 == "symbolic":
git(repo, "symbolic-ref", "refs/remotes/origin/main", "refs/heads/main")
elif branch:
elif branch and branch != "legacy":
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, local_head = worktree._git, worktree.head(repo)
def interleave(path, *args, **kwargs):
result = invoke(path, *args, **kwargs)
if args[0] == "fetch":
git(path, "fetch", "-q", "origin", f"refs/heads/{side}")
invoke, local_head = worktree.run, worktree.head(repo)
def interleave(argv, **kwargs):
if branch == "legacy" and argv[:3] == ("git", "fetch", "--porcelain"):
return invoke(("git", "fetch", "--loopzero-unsupported"), **kwargs)
result = invoke(argv, **kwargs)
if argv[1] == "fetch" and result.exit_code == 0:
git(kwargs["cwd"], "fetch", "-q", "origin", f"refs/heads/{side}")
return result

monkeypatch.setattr(worktree, "_git", interleave)
monkeypatch.setattr(worktree, "run", interleave)
wt = worktree.start(repo, "my-task", "main")
assert wt == repo / ".worktrees" / "my-task"
assert (wt / "feature.txt").exists(), "fetched origin/main before branching"
Expand Down Expand Up @@ -200,7 +202,8 @@ 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", "ls-remote")
assert info.value.command[0] == "git"

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: Failure-command assertion was loosened to accept either path

test_start_reports_git_failure_with_command now accepts either fetch or ls-remote. On the test's Git version the outcome is deterministic, so this no longer checks which path produced the error. A regression that sends a valid missing branch down the fallback path would still pass. Smallest fix: assert command[:3] == ("git", "fetch", "--porcelain") when the installed Git supports --porcelain, and ls-remote otherwise. Alternatively, parametrize the test with the existing legacy monkeypatch so both paths are pinned.

assert info.value.command[1] in {"fetch", "ls-remote"}
assert info.value.tail


Expand Down
Loading