diff --git a/src/loopzero/worktree.py b/src/loopzero/worktree.py index aeaa60b2..afd93870 100644 --- a/src/loopzero/worktree.py +++ b/src/loopzero/worktree.py @@ -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 ` using the URL for the " + "repository in `[repo] name`, or rename that remote with `git remote rename 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) @@ -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 ` " - "using the URL for the repository in `[repo] name`, or rename that remote " - "with `git remote rename 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: diff --git a/tests/test_worktree.py b/tests/test_worktree.py index b180a947..f6a635d5 100644 --- a/tests/test_worktree.py +++ b/tests/test_worktree.py @@ -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"]) 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" @@ -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" + assert info.value.command[1] in {"fetch", "ls-remote"} assert info.value.tail