Skip to content

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

refactor(repo): return &[WorktreeInfo] from list_worktrees (#2383)

Maximilian Roosb9a5db74e25d
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 8f6527ee8..248efc193 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -46,8 +46,9 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
// Filter out prunable worktrees (directory deleted) - can't run commands there
let worktrees: Vec<_> = repo
.list_worktrees()?
- .into_iter()
+ .iter()
.filter(|wt| !wt.is_prunable())
+ .cloned()
.collect();
let config = UserConfig::load()?;
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index c3eb304f3..f880fef93 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -518,13 +518,14 @@ pub fn collect(
// on `RepoCache`)
//
// After this scope completes, we have all raw data and can do CPU-only work.
- let worktrees_cell: OnceCell<anyhow::Result<Vec<WorktreeInfo>>> = OnceCell::new();
let default_branch_cell: OnceCell<Option<String>> = OnceCell::new();
let url_template_cell: OnceCell<Option<String>> = OnceCell::new();
rayon::scope(|s| {
s.spawn(|_| {
- let _ = worktrees_cell.set(repo.list_worktrees());
+ // Prime the worktree list on `RepoCache`; consumers below read it
+ // through `repo.list_worktrees()`.
+ let _ = repo.list_worktrees();
});
s.spawn(|_| {
let _ = default_branch_cell.set(repo.default_branch());
@@ -558,10 +559,7 @@ pub fn collect(
});
// Extract results
- let worktrees = worktrees_cell
- .into_inner()
- .unwrap()
- .context("Failed to list worktrees")?;
+ let worktrees: &[WorktreeInfo] = repo.list_worktrees().context("Failed to list worktrees")?;
if worktrees.is_empty() {
return Ok(None);
}
@@ -644,7 +642,7 @@ pub fn collect(
// so the warning fires on plain `wt list` too — otherwise downstream
// tasks resolve against the stale ref and emit a cascade of "ambiguous
// argument" noise instead of one clean warning.
- let worktree_branches = worktree_branch_set(&worktrees);
+ let worktree_branches = worktree_branch_set(worktrees);
let needs_stale_check = default_branch
.as_deref()
.is_some_and(|b| !worktree_branches.contains(b));
@@ -764,7 +762,7 @@ pub fn collect(
// Sort worktrees: current first, main second, then by timestamp descending
let sorted_worktrees = sort_worktrees_with_cache(
- worktrees.clone(),
+ worktrees.to_vec(),
&main_worktree,
current_worktree_path.as_ref(),
&timestamps,
diff --git a/src/commands/relocate.rs b/src/commands/relocate.rs
index a89a9db11..6daf4605b 100644
--- a/src/commands/relocate.rs
+++ b/src/commands/relocate.rs
@@ -119,8 +119,9 @@ pub fn gather_candidates(
// Get all worktrees, excluding prunable ones
let worktrees: Vec<_> = repo
.list_worktrees()?
- .into_iter()
+ .iter()
.filter(|wt| wt.prunable.is_none())
+ .cloned()
.collect();
// Filter to requested branches if any were specified
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 975d59a02..2ca8a7624 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -89,13 +89,9 @@ impl RepositoryCliExt for Repository {
worktrees: Option<&[WorktreeInfo]>,
) -> anyhow::Result<RemoveResult> {
let current_path = current_path.map_or_else(|| self.current_worktree().root(), Ok)?;
- let owned_worktrees;
let worktrees = match worktrees {
Some(wts) => wts,
- None => {
- owned_worktrees = self.list_worktrees()?;
- &owned_worktrees
- }
+ None => self.list_worktrees()?,
};
// Primary worktree path: prefer default branch's worktree, fall back to first
// worktree, then repo base for bare repos with no worktrees.
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index be4d8890f..0e139f1e4 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -760,8 +760,8 @@ pub fn step_copy_ignored(
let worktree_paths: Vec<PathBuf> = repo
.list_worktrees()?
- .into_iter()
- .map(|wt| wt.path)
+ .iter()
+ .map(|wt| wt.path.clone())
.collect();
let entries_to_copy = list_and_filter_ignored_entries(
&source_path,
@@ -1616,9 +1616,7 @@ pub fn step_prune(
dry_run_info.push((candidate, info));
} else if is_current {
deferred_current = Some(candidate);
- } else if try_remove(
- &candidate, &repo, &config, foreground, run_hooks, &worktrees,
- )? {
+ } else if try_remove(&candidate, &repo, &config, foreground, run_hooks, worktrees)? {
removed.push(candidate);
}
continue;
@@ -1669,9 +1667,7 @@ pub fn step_prune(
suffix,
};
dry_run_info.push((candidate, info));
- } else if try_remove(
- &candidate, &repo, &config, foreground, run_hooks, &worktrees,
- )? {
+ } else if try_remove(&candidate, &repo, &config, foreground, run_hooks, worktrees)? {
removed.push(candidate);
}
}
@@ -1742,7 +1738,7 @@ pub fn step_prune(
// Remove deferred current worktree last (cd-to-primary happens here)
if let Some(current) = deferred_current
- && try_remove(&current, &repo, &config, foreground, run_hooks, &worktrees)?
+ && try_remove(&current, &repo, &config, foreground, run_hooks, worktrees)?
{
removed.push(current);
}
diff --git a/src/git/repository/worktrees.rs b/src/git/repository/worktrees.rs
index 2593e679e..b1e1d1027 100644
--- a/src/git/repository/worktrees.rs
+++ b/src/git/repository/worktrees.rs
@@ -18,12 +18,12 @@ impl Repository {
/// the main worktree. For bare repos, the bare entry is filtered out, so `[0]`
/// is the first linked worktree (no semantic "main" exists).
///
- /// Returns an empty vec for bare repos with no linked worktrees.
+ /// Returns an empty slice for bare repos with no linked worktrees.
///
- /// Cached on `RepoCache` after the first successful call; subsequent
- /// calls clone from the cache. See the module-level `# Caching` docs for
- /// the "no post-mutation reads through the cache" invariant.
- pub fn list_worktrees(&self) -> anyhow::Result<Vec<WorktreeInfo>> {
+ /// Cached on `RepoCache` after the first successful call; subsequent calls
+ /// return a reference into the cache. See the module-level `# Caching` docs
+ /// for the "no post-mutation reads through the cache" invariant.
+ pub fn list_worktrees(&self) -> anyhow::Result<&[WorktreeInfo]> {
self.cache
.worktrees
.get_or_try_init(|| {
@@ -47,9 +47,9 @@ impl Repository {
//
// 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
- // (worktree_for_branch, current_worktree_info, resolve_worktree, etc.)
- // depend on paths being working directories. If git fixes this upstream,
- // the condition stops triggering.
+ // (worktree_for_branch, resolve_worktree, etc.) depend on paths being
+ // working directories. If git fixes this upstream, the condition stops
+ // triggering.
if let Some(first) = worktrees.first_mut()
&& canonicalize(&first.path).ok().as_deref() == Some(self.git_common_dir())
{
@@ -58,28 +58,7 @@ impl Repository {
Ok(worktrees)
})
- .cloned()
- }
-
- /// Get the WorktreeInfo struct for the current worktree, if we're inside one.
- ///
- /// Returns `None` if not in a worktree (e.g., in bare repo directory).
- ///
- /// Note: For worktree-specific operations, use [`current_worktree()`](Self::current_worktree)
- /// to get a [`WorkingTree`](super::WorkingTree) instead.
- pub fn current_worktree_info(&self) -> anyhow::Result<Option<WorktreeInfo>> {
- // root() returns canonicalized path, so canonicalize worktree paths for comparison
- // to handle symlinks (e.g., macOS /var -> /private/var)
- let current_path = match self.current_worktree().root() {
- Ok(p) => p,
- Err(_) => return Ok(None),
- };
- let worktrees = self.list_worktrees()?;
- Ok(worktrees.into_iter().find(|wt| {
- canonicalize(&wt.path)
- .map(|p| p == current_path)
- .unwrap_or(false)
- }))
+ .map(Vec::as_slice)
}
/// Find the worktree path for a given branch, if one exists.
diff --git a/src/main.rs b/src/main.rs
index cc663f05f..d0726156f 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -653,7 +653,7 @@ fn validate_remove_targets(
force,
config,
None,
- worktrees.as_deref(),
+ worktrees,
) {
Ok(result) => plans.current = Some(result),
Err(e) => plans.record_error(e),
@@ -674,7 +674,7 @@ fn validate_remove_targets(
force,
config,
None,
- worktrees.as_deref(),
+ worktrees,
) {
Ok(result) => plans.others.push(result),
Err(e) => plans.record_error(e),
@@ -687,7 +687,7 @@ fn validate_remove_targets(
force,
config,
None,
- worktrees.as_deref(),
+ worktrees,
) {
Ok(result) => plans.branch_only.push(result),
Err(e) => plans.record_error(e),