Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(list): read a stale worktree's rebase state from its registration (#4302)

Maximilian Roosfc4bc3ac89f0
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 72555e4e7..cae461dfd 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -24,7 +24,7 @@
//! | 1 | `git rev-parse --git-common-dir --is-inside-work-tree --show-toplevel --git-dir --symbolic-full-name HEAD` | [`Repository::prewarm`] (`prewarm_rev_parse`) | Five facts in one fork: shared `.git`, in-worktree gate, worktree root, per-worktree `.git/worktrees/<name>`, current branch. Populates process-global caches. Parallel with #2 at process startup. |
//! | 2 | `git config --list -z` (cwd = discovery path) | [`Repository::prewarm`] (`prewarm_git_config`) | Whole merged config (system + global + local) in one shot, NUL-delimited so values containing `\n` or `=` parse unambiguously. Stashed in `GIT_CONFIG_PRELOAD` keyed by discovery path; every later `config_last("…")` reads from memory. Parallel with #1. |
//! | 3 | `git config --list -z` (cwd = `git_common_dir`) | [`Repository::prewarm`] post-pass (`prewarm_git_config_from_common_dir`) | **Conditional.** [`Repository::at`] consumes #2's preload into `cache.all_config`, so `all_config()` is a memory hit on a normal repo. In `extensions.worktreeConfig=true` repos, #2's read is declined — `--list` from a linked worktree misses the main-worktree `config.worktree` overrides (most importantly `core.bare = true` for the `myproject/.git + sibling worktrees` layout) — and prewarm re-forks from the common dir after its threads join, preloading the full merged set. [`Repository::all_config`] forks the same command on demand only when prewarm never ran for the path (a non-base `Repository::at`, tests). See `prewarm_git_config` for the full reasoning. |
-//! | 4 | `git worktree list --porcelain` | [`Repository::list_worktrees`] | Path, HEAD SHA, branch, and flags per worktree — the row source for the skeleton. The picker prelude triggers this once for `num_items_estimate`; collect's rayon scope then hits the cache. **Plus one `git rev-parse --git-dir` per detached worktree**, run inside the same cache initializer (`finalize_worktrees`): git lists a mid-rebase worktree only as detached, so each detached worktree's git dir is resolved and its `rebase-{merge,apply}/head-name` read to recover the branch. These are the one O(N) fork group before the skeleton — O(detached worktrees), forked together through `Cmd::run_concurrently`. |
+//! | 4 | `git worktree list --porcelain` | [`Repository::list_worktrees`] | Path, HEAD SHA, branch, and flags per worktree — the row source for the skeleton. The picker prelude triggers this once for `num_items_estimate`; collect's rayon scope then hits the cache. **Plus one `git rev-parse --git-dir` per live detached worktree**, run inside the same cache initializer (`finalize_worktrees`): git lists a mid-rebase worktree only as detached, so each detached worktree's git dir is resolved (a stale one's is its registration, read without a fork) and its `rebase-{merge,apply}/head-name` read to recover the branch. These are the one O(N) fork group before the skeleton — O(detached worktrees), forked together through `Cmd::run_concurrently`. |
//! | 5 | `git for-each-ref --format=… refs/heads/` | [`Repository::local_branches`] inside collect's `rayon::scope` | Local branch tips (name, SHA, committer date, upstream) for branch-only rows (`branches=true`), the stale-default-branch check, and the post-skeleton ref snapshot. `remotes=true` adds a sibling `refs/remotes/` fork; otherwise the snapshot runs that scan after the skeleton. Runs beside #4, which is the longer of the two on a repo with many worktrees. |
//! | 6 | `git log --no-walk --no-show-signature --format=… SHA₁ … SHA_N` | collect, after the scope | Batched commit metadata for every worktree HEAD + branch tip. See breakdown below. |
//!
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 774173253..55275ca00 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -893,11 +893,22 @@ fn rebase_branch(git_dir: &Path) -> Option<String> {
/// processes rather than on a thread pool: this runs inside the
/// `list_worktrees` cache initializer, and a pool thread waiting there would
/// run other pool jobs, one of which could wait on the same cache.
+///
+/// A stale (prunable) entry's rebase state is read from its registration
+/// instead. With its `.git` gone, a `rev-parse` from its path finds nothing
+/// there and walks up to whatever repository encloses the directory — for a
+/// worktree nested in the main one, the main worktree's git dir — and would
+/// name the entry after a rebase that is not its own.
pub(crate) fn finalize_worktrees(repo: &Repository, worktrees: &mut [WorktreeInfo]) {
- let mut detached: Vec<&mut WorktreeInfo> = worktrees
+ let (stale, mut detached): (Vec<&mut WorktreeInfo>, Vec<&mut WorktreeInfo>) = worktrees
.iter_mut()
.filter(|wt| wt.detached && wt.branch.is_none())
- .collect();
+ .partition(|wt| wt.is_prunable());
+ for wt in stale {
+ if let Ok((registration, _)) = repo.registration_at(&wt.path) {
+ wt.branch = rebase_branch(&registration);
+ }
+ }
if detached.is_empty() {
return;
}
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index b73656b93..e91f2ffe7 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -160,6 +160,54 @@ fn test_finalize_worktree_linked_mid_rebase() {
assert_eq!(wt.branch.as_deref(), Some("feature"));
}
+#[test]
+fn test_finalize_worktree_stale_reads_its_own_rebase() {
+ // A stale entry's rebase state is in its registration. A lookup from its
+ // path would walk up past the missing `.git`: `nested` sits inside the main
+ // worktree, which is itself rebasing `main-work`, so that lookup would
+ // name `nested` after a rebase that is not its own — and `wt step prune`
+ // would then judge the entry by `main-work`, not by its own detached HEAD.
+ let test = TestRepo::with_initial_commit();
+ let root = test.root_path().to_path_buf();
+ let rebase_stopped = |dir: &std::path::Path, branch: &str| {
+ test.run_git_in(dir, &["switch", "-c", branch]);
+ std::fs::write(dir.join(format!("{branch}.txt")), "work\n").unwrap();
+ test.run_git_in(dir, &["add", "."]);
+ test.run_git_in(dir, &["commit", "-m", branch]);
+ // `--exec` stops the rebase after replaying the commit, leaving it open.
+ let _ = test
+ .git_command()
+ .current_dir(dir)
+ .args(["rebase", "--exec", "false", "HEAD~1"])
+ .run();
+ };
+
+ let nested = root.join(".worktrees").join("nested");
+ test.run_git(&["worktree", "add", "--detach", nested.to_str().unwrap()]);
+ let rebasing = root.parent().unwrap().join("stale-rebase");
+ test.run_git(&["worktree", "add", "--detach", rebasing.to_str().unwrap()]);
+ rebase_stopped(&rebasing, "feature");
+ rebase_stopped(&root, "main-work");
+ std::fs::remove_file(nested.join(".git")).unwrap();
+ std::fs::remove_file(rebasing.join(".git")).unwrap();
+
+ let repo = Repository::at(&root).unwrap();
+ let worktrees = repo.list_worktrees().unwrap();
+ let find = |path: &std::path::Path| {
+ let path = dunce::canonicalize(path).unwrap();
+ worktrees
+ .iter()
+ .find(|wt| dunce::canonicalize(&wt.path).unwrap() == path)
+ .unwrap()
+ };
+ let (main, nested, rebasing) = (find(&root), find(&nested), find(&rebasing));
+ assert_eq!(main.branch.as_deref(), Some("main-work"));
+ assert!(nested.is_prunable() && rebasing.is_prunable());
+ assert!(nested.detached && rebasing.detached);
+ assert_eq!(nested.branch, None);
+ assert_eq!(rebasing.branch.as_deref(), Some("feature"));
+}
+
#[test]
fn test_parse_locked_worktree() {
let output = "worktree /path/to/locked
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index 72fa5bf76..80439960f 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -335,7 +335,7 @@ impl Repository {
///
/// Unreadable siblings (an entry another process is deleting) are not
/// this one, so they are passed over rather than failing the lookup.
- fn registration_at(&self, path: &Path) -> anyhow::Result<(PathBuf, PathBuf)> {
+ pub(crate) fn registration_at(&self, path: &Path) -> anyhow::Result<(PathBuf, PathBuf)> {
let registrations = self.git_common_dir().join("worktrees");
std::fs::read_dir(&registrations)
.with_context(|| format!("Failed to read {}", format_path_for_display(&registrations)))?