Skip to content

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

Refactor worktree removal into unified prepare_worktree_removal

Maximilian Roosa0eb3199069f
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index c4afbfa27..5bf67a5bc 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -10,6 +10,15 @@ use worktrunk::git::{GitError, IntegrationReason, Repository};
use worktrunk::path::format_path_for_display;
use worktrunk::styling::{format_with_gutter, progress_message, warning_message};
+/// Target for worktree removal.
+#[derive(Debug)]
+pub enum RemoveTarget<'a> {
+ /// Remove worktree by branch name
+ Branch(&'a str),
+ /// Remove the current worktree (supports detached HEAD)
+ Current,
+}
+
/// CLI-only helpers implemented on [`Repository`] via an extension trait so we can keep orphan
/// implementations inside the binary crate.
pub trait RepositoryCliExt {
@@ -19,22 +28,13 @@ pub trait RepositoryCliExt {
/// Warn about untracked files being auto-staged.
fn warn_if_auto_staging_untracked(&self) -> anyhow::Result<()>;
- /// Remove a worktree identified by branch name.
- fn remove_worktree_by_name(
- &self,
- branch_name: &str,
- deletion_mode: BranchDeletionMode,
- force_worktree: bool,
- ) -> anyhow::Result<RemoveResult>;
-
- /// Remove the current worktree (handles detached HEAD state).
+ /// Prepare a worktree removal by branch name or current worktree.
///
- /// This method removes the worktree we're currently in, even if HEAD is detached.
- /// It finds the branch from:
- /// 1. The worktree's metadata (if not detached)
- /// 2. The reflog (if detached from a branch)
- fn remove_current_worktree(
+ /// Returns a `RemoveResult` describing what will be removed. The actual
+ /// removal is performed by the output handler.
+ fn prepare_worktree_removal(
&self,
+ target: RemoveTarget,
deletion_mode: BranchDeletionMode,
force_worktree: bool,
) -> anyhow::Result<RemoveResult>;
@@ -73,114 +73,85 @@ impl RepositoryCliExt for Repository {
warn_about_untracked_files(&status)
}
- fn remove_worktree_by_name(
+ fn prepare_worktree_removal(
&self,
- branch_name: &str,
+ target: RemoveTarget,
deletion_mode: BranchDeletionMode,
force_worktree: bool,
) -> anyhow::Result<RemoveResult> {
- let worktree_path = match self.worktree_for_branch(branch_name)? {
- Some(path) => path,
- None => {
- // No worktree found - check if the branch exists locally
- if self.local_branch_exists(branch_name)? {
- // Branch exists but no worktree - return BranchOnly to attempt branch deletion
- return Ok(RemoveResult::BranchOnly {
- branch_name: branch_name.to_string(),
- deletion_mode,
- });
- }
- // Check if branch exists on a remote
- let remotes = self.remotes_with_branch(branch_name)?;
- if !remotes.is_empty() {
- return Err(GitError::RemoteOnlyBranch {
- branch: branch_name.into(),
- remote: remotes[0].clone(),
+ let current_path = self.worktree_root()?.to_path_buf();
+ let worktrees = self.list_worktrees()?;
+ let main_worktree_path = worktrees[0].path.clone();
+
+ // Resolve target to worktree path and branch
+ let (worktree_path, branch_name, is_current) = match target {
+ RemoveTarget::Branch(branch) => {
+ match worktrees
+ .iter()
+ .find(|wt| wt.branch.as_deref() == Some(branch))
+ {
+ Some(wt) => {
+ if !wt.path.exists() {
+ return Err(GitError::WorktreeMissing {
+ branch: branch.into(),
+ }
+ .into());
+ }
+ let is_current = current_path == wt.path;
+ (wt.path.clone(), Some(branch.to_string()), is_current)
+ }
+ None => {
+ // No worktree found - check if the branch exists locally
+ if self.local_branch_exists(branch)? {
+ return Ok(RemoveResult::BranchOnly {
+ branch_name: branch.to_string(),
+ deletion_mode,
+ });
+ }
+ // Check if branch exists on a remote
+ let remotes = self.remotes_with_branch(branch)?;
+ if !remotes.is_empty() {
+ return Err(GitError::RemoteOnlyBranch {
+ branch: branch.into(),
+ remote: remotes[0].clone(),
+ }
+ .into());
+ }
+ return Err(GitError::NoWorktreeFound {
+ branch: branch.into(),
+ }
+ .into());
}
- .into());
- }
- return Err(GitError::NoWorktreeFound {
- branch: branch_name.into(),
}
- .into());
}
- };
-
- if !worktree_path.exists() {
- return Err(GitError::WorktreeMissing {
- branch: branch_name.into(),
+ RemoveTarget::Current => {
+ let wt = worktrees
+ .iter()
+ .find(|wt| wt.path == current_path)
+ .ok_or_else(|| {
+ anyhow::anyhow!("Current worktree not found in worktree list")
+ })?;
+ (wt.path.clone(), wt.branch.clone(), true)
}
- .into());
- }
-
- let target_repo = Repository::at(&worktree_path);
- target_repo.ensure_clean_working_tree("remove worktree", Some(branch_name))?;
-
- let current_worktree = self.worktree_root()?.to_path_buf();
- let removing_current = current_worktree == worktree_path;
-
- // Cannot remove the main working tree (only linked worktrees can be removed)
- if removing_current && !self.is_in_worktree()? {
- return Err(GitError::CannotRemoveMainWorktree.into());
- }
-
- let (main_path, changed_directory) = if removing_current {
- let worktrees = self.list_worktrees()?;
- (worktrees[0].path.clone(), true)
- } else {
- (current_worktree, false)
- };
-
- // Resolve default branch for integration reason display
- // Skip if removing the default branch itself (avoids tautological "main (ancestor of main)")
- let default_branch = self.default_branch().ok();
- let target_branch = match &default_branch {
- Some(db) if db == branch_name => None,
- _ => default_branch,
};
- // Pre-compute integration reason to avoid race conditions when removing
- // multiple worktrees in background mode. Background git processes can hold
- // locks that cause subsequent integration checks to fail.
- let integration_reason = compute_integration_reason(
- &main_path,
- Some(branch_name),
- target_branch.as_deref(),
- deletion_mode,
- );
-
- Ok(RemoveResult::RemovedWorktree {
- main_path,
- worktree_path,
- changed_directory,
- branch_name: Some(branch_name.to_string()),
- deletion_mode,
- target_branch,
- integration_reason,
- force_worktree,
- })
- }
+ // Create Repository at target for validation
+ let target_repo = Repository::at(&worktree_path);
- fn remove_current_worktree(
- &self,
- deletion_mode: BranchDeletionMode,
- force_worktree: bool,
- ) -> anyhow::Result<RemoveResult> {
// Cannot remove the main working tree (only linked worktrees can be removed)
- if !self.is_in_worktree()? {
+ if !target_repo.is_in_worktree()? {
return Err(GitError::CannotRemoveMainWorktree.into());
}
- // Get current worktree path and branch
- let current_path = self.worktree_root()?.to_path_buf();
- let branch_name = self.current_branch()?.map(str::to_string);
-
// Ensure the working tree is clean
- self.ensure_clean_working_tree("remove worktree", branch_name.as_deref())?;
+ target_repo.ensure_clean_working_tree("remove worktree", branch_name.as_deref())?;
- // Get main worktree path (we're removing current, so we'll cd to main)
- let worktrees = self.list_worktrees()?;
- let main_path = worktrees[0].path.clone();
+ // Compute main_path and changed_directory based on whether we're removing current
+ let (main_path, changed_directory) = if is_current {
+ (main_worktree_path, true)
+ } else {
+ (current_path, false)
+ };
// Resolve default branch for integration reason display
// Skip if removing the default branch itself (avoids tautological "main (ancestor of main)")
@@ -190,7 +161,8 @@ impl RepositoryCliExt for Repository {
_ => default_branch,
};
- // Pre-compute integration reason (same logic as remove_worktree_by_name)
+ // Pre-compute integration reason to avoid race conditions when removing
+ // multiple worktrees in background mode.
let integration_reason = compute_integration_reason(
&main_path,
branch_name.as_deref(),
@@ -200,8 +172,8 @@ impl RepositoryCliExt for Repository {
Ok(RemoveResult::RemovedWorktree {
main_path,
- worktree_path: current_path,
- changed_directory: true,
+ worktree_path,
+ changed_directory,
branch_name,
deletion_mode,
target_branch,
diff --git a/src/commands/worktree.rs b/src/commands/worktree.rs
index 008e2b141..c6b6297b4 100644
--- a/src/commands/worktree.rs
+++ b/src/commands/worktree.rs
@@ -93,7 +93,7 @@ use worktrunk::styling::{
use super::command_executor::CommandContext;
use super::hooks::{HookFailureStrategy, HookPipeline, HookSource};
-use super::repository_ext::RepositoryCliExt;
+use super::repository_ext::{RemoveTarget, RepositoryCliExt};
/// Generate a backup path for the given path with a timestamp suffix.
///
@@ -756,8 +756,8 @@ pub fn handle_remove(
)))?;
}
- repo.remove_worktree_by_name(
- worktree_name,
+ repo.prepare_worktree_removal(
+ RemoveTarget::Branch(worktree_name),
BranchDeletionMode::from_flags(no_delete_branch, force_delete),
force_worktree,
)
@@ -780,7 +780,8 @@ pub fn handle_remove_current(
crate::output::print(progress_message("Removing current worktree..."))?;
}
- repo.remove_current_worktree(
+ repo.prepare_worktree_removal(
+ RemoveTarget::Current,
BranchDeletionMode::from_flags(no_delete_branch, force_delete),
force_worktree,
)
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index f913985cb..91c258892 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -623,7 +623,16 @@ impl Repository {
.map(PathBuf::as_path)
}
- /// Check if the path is in a worktree (vs the main repository).
+ /// Check if this is a linked worktree (vs the main worktree).
+ ///
+ /// Returns `true` for linked worktrees (created via `git worktree add`),
+ /// `false` for the main worktree (original clone location).
+ ///
+ /// Implementation: compares `git_dir` vs `common_dir`. In linked worktrees,
+ /// the `.git` file points to `.git/worktrees/NAME`, so they differ. In the
+ /// main worktree, both point to the same `.git` directory.
+ ///
+ /// For bare repos, all worktrees are "linked" (returns `true`).
pub fn is_in_worktree(&self) -> anyhow::Result<bool> {
let git_dir = self.git_dir()?;
let common_dir = self.git_common_dir()?;
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 50ee2ecbf..5983e4dfd 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -745,6 +745,23 @@ fn test_remove_main_worktree_vs_linked_worktree(mut repo: TestRepo) {
&[],
None,
);
+
+ // Part 6: Verify main worktree CANNOT be removed by name from a linked worktree
+ // Switch back to main branch in main worktree, then create a new linked worktree
+ let mut cmd = std::process::Command::new("git");
+ repo.configure_git_cmd(&mut cmd);
+ cmd.args(["switch", "main"])
+ .current_dir(repo.root_path())
+ .output()
+ .unwrap();
+
+ let linked_for_test = repo.add_worktree("test-from-linked");
+ snapshot_remove(
+ "remove_main_vs_linked__main_by_name_from_linked_fails",
+ &repo,
+ &["main"],
+ Some(&linked_for_test),
+ );
}
/// Test that removing a worktree for the default branch doesn't show tautological reason.
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_main_vs_linked__main_by_name_from_linked_fails.snap b/tests/snapshots/integration__integration_tests__remove__remove_main_vs_linked__main_by_name_from_linked_fails.snap
new file mode 100644
index 000000000..92a51282a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_main_vs_linked__main_by_name_from_linked_fails.snap
@@ -0,0 +1,33 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - main
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: false
+exit_code: 1
+----- stdout -----
+
+----- stderr -----
+✗ The main worktree cannot be removed