Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(git): resolve repo_path through the separate-git-dir backlink (#4236)
Worktrunk Bota56e6d991bbb
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 5cec93e23..23cf29428 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -173,6 +173,7 @@ pub use diff::{CommitMessageDetail, PreparedDiff};pub use integration::{BranchDiffSpec, IntegrationTargets, select_comparison_base};pub use ref_snapshot::RefSnapshot;pub(super) use working_tree::path_to_logging_context;+use working_tree::registration_worktree_path;pub use working_tree::{InProgressOperation, TempIndex, WorkingTree};pub use worktrees::{StaleWorktreeWork, duplicated_branches};@@ -1470,9 +1471,11 @@ impl Repository {/// the reason that gate uses it rather than the `GIT_DIRS`-cached/// [`WorkingTree::git_dir`].///- /// Two callers, with opposite readings of `None`:+ /// Three callers, with different readings of `None`:/// [`Self::prime_worktree_path_caches`] declines to seed a cache entry and- /// leaves the answer to the subprocess, while the removal gate refuses.+ /// leaves the answer to the subprocess, `separate_git_dir_work_tree`+ /// declines the backlink it was confirming and falls back to+ /// `parent(git_common_dir)`, and the removal gate refuses.fn git_dir_at(dir: &Path) -> Option<PathBuf> {let dot_git = dir.join(".git");// Follows a symlinked `.git`, as git and the subprocess fallback do.@@ -1598,7 +1601,8 @@ impl Repository {/// |----------------------------|----------------------------|-------------------------------|/// | Bare `.git` | `core.bare = true` | `git_common_dir` is the repo |/// | Submodule `.git/modules/X` | `core.worktree` set by git | `rev-parse --show-toplevel` |- /// | Normal `.git` | neither set | `parent(git_common_dir)` |+ /// | Separate git dir | `<common>/gitdir` backlink | `parent(backlink)` |+ /// | Normal `.git` | none of the above | `parent(git_common_dir)` |////// Submodules need `core.worktree` because their git data lives in the/// parent's `.git/modules/` — the `parent(.git)` rule would point at@@ -1614,6 +1618,12 @@ impl Repository {/// to the normal-repo path. The common case — no `core.worktree`/// anywhere — skips the subprocess, which is the point.///+ /// A repository whose git directory lives outside its work tree+ /// (`--separate-git-dir`) has neither signal, and `parent(git_common_dir)`+ /// names the store's parent rather than the work tree. The backlink git+ /// writes there covers it where it exists; see+ /// `separate_git_dir_work_tree` for when that is.+ ////// # Errors////// Returns an error if the bulk config read fails (e.g., git timeout). This@@ -1641,6 +1651,10 @@ impl Repository {return Ok(PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()));}+ if let Some(work_tree) = self.separate_git_dir_work_tree() {+ return Ok(work_tree);+ }+Ok(self.git_common_dir.parent()@@ -1650,6 +1664,42 @@ impl Repository {.map(|p| p.as_path())}+ /// The work tree a `--separate-git-dir` repository records in its `gitdir`+ /// backlink, if it has one.+ ///+ /// When the git directory lives outside the work tree, the work tree's+ /// `.git` is a *file* pointing at the store and `parent(git_common_dir)`+ /// names the store's parent — the wrong answer, and the one+ /// `git worktree list` gives too, since git derives its main-worktree+ /// entry by stripping a trailing `/.git` that isn't there (see the+ /// submodule correction in [`Self::list_worktrees`], which this layout+ /// trips the same way).+ ///+ /// Git's own record of the other direction is `<git-common-dir>/gitdir`,+ /// holding the path of the work tree's `.git` file — the same format as a+ /// linked worktree's `.git/worktrees/<name>/gitdir`, down to the relative+ /// form git writes under `worktree.useRelativePaths`, so+ /// [`registration_worktree_path`] reads it. Only+ /// `git worktree repair` writes it; `git init --separate-git-dir` and+ /// `git clone --separate-git-dir` leave the store with no backlink, so a+ /// repository that has never been repaired records its work tree nowhere+ /// and still falls through to `parent(git_common_dir)`. Running+ /// `git worktree repair` from the work tree is what materializes it.+ ///+ /// The backlink is one-way, so it is confirmed rather than trusted:+ /// [`Self::git_dir_at`] reads the `.git` entry sitting at the work tree it+ /// names, and only a work tree that points back at this common dir is+ /// accepted. A backlink left behind by a work tree that has since moved,+ /// been deleted, or been re-pointed at another repository resolves to+ /// something else and falls through to `parent(git_common_dir)` — the+ /// same answer as before, rather than a path that no longer holds this+ /// repository. That round trip is also why a normal repository or a+ /// submodule can't misfire here on a stray `gitdir` file.+ fn separate_git_dir_work_tree(&self) -> Option<PathBuf> {+ let work_tree = registration_worktree_path(&self.git_common_dir)?;+ (Self::git_dir_at(&work_tree)? == self.git_common_dir).then_some(work_tree)+ }+/// Access the bulk git config map, populating on first call.////// Reads every key from the merged git config (system + global + repo)diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex 11ca9d5d6..dd6332e0b 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -2514,3 +2514,172 @@ fn worktree_path_not_ours_names_a_normalized_path() {"the refusal must name where the occupant belongs:\n{refusal}");}++/// Build a `git init --separate-git-dir` layout: the work tree's `.git` is a+/// *file* pointing at a store directory outside it. Returns the tempdir, the+/// store (which is the repository's git common dir) and the work tree.+///+/// `git worktree repair` runs last so the store carries git's `gitdir`+/// backlink. Neither `git init --separate-git-dir` nor `git clone+/// --separate-git-dir` writes one, so an unrepaired repository of this shape+/// records its work tree nowhere.+///+/// `relative_backlink` sets `worktree.useRelativePaths` before the repair, so+/// git writes the backlink as a path relative to the store rather than an+/// absolute one. Git honors the setting from 2.48; below that it keeps writing+/// the absolute form, which the tests accept the same way+/// `test_switch_with_relative_worktree_paths` does.+fn build_separate_git_dir_layout() -> (tempfile::TempDir, PathBuf, PathBuf) {+ build_separate_git_dir_layout_with(false)+}++fn build_separate_git_dir_layout_with(+ relative_backlink: bool,+) -> (tempfile::TempDir, PathBuf, PathBuf) {+ use super::canonicalize;+ use crate::shell_exec::Cmd;++ let tmp = tempfile::tempdir().unwrap();+ let root = canonicalize(tmp.path()).unwrap();+ let store = root.join("store").join("repo.gitdir");+ let work_tree = root.join("work");+ std::fs::create_dir_all(root.join("store")).unwrap();++ let git = || crate::testing::configure_git_env(Cmd::new("git"));+ let path_str = |p: &std::path::Path| p.to_str().unwrap().to_owned();++ let out = git()+ .args([+ "init",+ "-b",+ "main",+ "--separate-git-dir",+ &path_str(&store),+ &path_str(&work_tree),+ ])+ .run()+ .unwrap();+ assert!(out.status.success(), "git init --separate-git-dir failed");++ let out = git()+ .current_dir(&work_tree)+ .args(["commit", "--allow-empty", "-m", "init"])+ .run()+ .unwrap();+ assert!(out.status.success(), "git commit failed");++ if relative_backlink {+ let out = git()+ .current_dir(&work_tree)+ .args(["config", "worktree.useRelativePaths", "true"])+ .run()+ .unwrap();+ assert!(out.status.success(), "git config failed");+ }++ let out = git()+ .current_dir(&work_tree)+ .args(["worktree", "repair"])+ .run()+ .unwrap();+ assert!(out.status.success(), "git worktree repair failed");++ (tmp, store, work_tree)+}++#[test]+fn repo_path_follows_the_separate_git_dir_backlink() {+ // Regression test for #4235. With the git dir outside the work tree, the+ // `parent(git_common_dir)` fallback names the store's *parent* — so+ // `{{ repo_path }}.{{ branch }}` placed new worktrees beside the store+ // rather than beside the work tree.+ use super::{Repository, canonicalize};++ let (_tmp, store, work_tree) = build_separate_git_dir_layout();++ let repo = Repository::at(&work_tree).unwrap();+ assert_eq!(+ canonicalize(repo.git_common_dir()).unwrap(),+ canonicalize(&store).unwrap(),+ "the store is the git common dir in this layout"+ );+ assert_eq!(+ canonicalize(repo.repo_path().unwrap()).unwrap(),+ work_tree,+ "repo_path must name the work tree, not the store's parent"+ );+}++#[test]+fn list_worktrees_names_the_work_tree_of_a_separate_git_dir_repo() {+ // Companion to the above: `git worktree list` reports the git common dir+ // as the main worktree entry here, the same shape `list_worktrees`+ // already corrects for submodules. Pin the corrected path, which is what+ // `wt list` renders.+ use super::{Repository, canonicalize};++ let (_tmp, _store, work_tree) = build_separate_git_dir_layout();++ let repo = Repository::at(&work_tree).unwrap();+ let worktrees = repo.list_worktrees().unwrap();+ assert_eq!(+ canonicalize(&worktrees[0].path).unwrap(),+ work_tree,+ "the main worktree entry must be the work tree"+ );+}++#[test]+fn repo_path_declines_a_stale_separate_git_dir_backlink() {+ // The backlink is one-way, so `repo_path` confirms it: a work tree that+ // has moved away leaves a `gitdir` file naming a path that no longer+ // points back. Falling through to `parent(git_common_dir)` returns the+ // pre-#4235 answer rather than a path that doesn't hold this repository.+ use super::{Repository, canonicalize};++ let (_tmp, store, work_tree) = build_separate_git_dir_layout();+ let moved = work_tree.with_file_name("moved");+ std::fs::rename(&work_tree, &moved).unwrap();+ // Plant an unrelated repository where the work tree used to be, so the+ // backlink still resolves to a directory and the `.git` entry there is+ // what rejects it — not the path simply being gone.+ let out = crate::testing::configure_git_env(crate::shell_exec::Cmd::new("git"))+ .args(["init", "-b", "main", work_tree.to_str().unwrap()])+ .run()+ .unwrap();+ assert!(out.status.success(), "git init failed");++ let repo = Repository::at(&store).unwrap();+ assert_eq!(+ canonicalize(repo.repo_path().unwrap()).unwrap(),+ canonicalize(store.parent().unwrap()).unwrap(),+ "a backlink whose work tree no longer points back must not be used"+ );+}++#[test]+fn repo_path_follows_a_relative_separate_git_dir_backlink() {+ // Under `worktree.useRelativePaths` git writes the backlink relative to+ // the store — `../../work/.git` — the same form it uses for a linked+ // worktree's registration, and it resolves it against the directory the+ // file sits in. Declining that form, or resolving it against the process+ // cwd, would leave #4235 unfixed for anyone with the setting on.+ use std::path::Path;++ use super::{Repository, canonicalize};++ let (_tmp, store, work_tree) = build_separate_git_dir_layout_with(true);++ let backlink = std::fs::read_to_string(store.join("gitdir")).unwrap();+ assert!(+ backlink.starts_with("../") || Path::new(backlink.trim()).is_absolute(),+ "expected a relative or (pre-2.48) absolute backlink: {backlink}"+ );++ let repo = Repository::at(&work_tree).unwrap();+ assert_eq!(+ canonicalize(repo.repo_path().unwrap()).unwrap(),+ work_tree,+ "a relative backlink must resolve against the store, not the cwd"+ );+}diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 16dea9e10..8615f678f 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -162,15 +162,19 @@ fn sequencer_operation(git_dir: &Path) -> Option<InProgressOperation> {}}-/// The working tree a `<common>/worktrees/<id>` registration records, read from-/// its `gitdir` file.+/// The working tree a `gitdir` file records, read from the directory holding it.////// The file holds the path of that working tree's `.git`, absolute or relative to-/// the registration directory — git writes the relative form under+/// the directory it sits in — git writes the relative form under/// `worktree.useRelativePaths` and resolves either, so both are ordinary. Its/// parent is the working tree, which is the half of git's `validate_worktree`/// that reads from the registration side.///+/// Two directories hold one: a `<common>/worktrees/<id>` registration, and the+/// common dir itself when `git worktree repair` has written the main worktree's+/// backlink there (`Repository::separate_git_dir_work_tree`). The format is the+/// same, so one reader answers for both.+////// Resolved through [`canonicalize_with_parents`], which normalizes the `..`/// chain a relative entry leaves behind even though the directory it names may/// no longer exist — the case the caller is usually asking about, and the path itdiff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rsindex aa0b4b5de..d3d3493e7 100644--- a/src/git/repository/worktrees.rs+++ b/src/git/repository/worktrees.rs@@ -48,18 +48,21 @@ impl Repository {let mut worktrees: Vec<_> =raw_worktrees.into_iter().filter(|wt| !wt.bare).collect();- // Submodule path correction.+ // Main-worktree path correction.//// Git's `get_main_worktree()` computes the main worktree path by stripping- // a trailing `/.git` from the common dir. For submodules, the common dir is- // `.git/modules/sub` (no trailing `/.git`), so git leaves it unchanged —- // reporting the git data directory as the "main worktree" path. Git does not- // consult `core.worktree` in this code path.+ // a trailing `/.git` from the common dir. Two layouts have no such suffix,+ // so git leaves the path unchanged and reports the git data directory as+ // the "main worktree": submodules, whose common dir is `.git/modules/sub`,+ // and `--separate-git-dir` repositories, whose common dir is wherever the+ // user put the store. Git consults neither `core.worktree` nor its own+ // `gitdir` backlink in this code path.//// We detect this by checking whether the first worktree's path equals// git_common_dir (which never holds for normal repos, where git_common_dir// is `.git` inside the worktree). When matched, we correct it using- // repo_path(), which reads `core.worktree` from the bulk config map.+ // repo_path(), which resolves both layouts from the signals git does+ // record.//// We fix this here rather than at each call site because list_worktrees()// is the single point where worktree paths enter the system — all consumers