Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor remove command to always require a name
Maximilian Roos7f25ac4d1746
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex f5f99a177..0c0b5fa7d 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -32,11 +32,10 @@ pub trait RepositoryCliExt {check_conflicts: bool,) -> Result<Option<ListData>, GitError>;- /// Remove the currently checked-out worktree or switch back to the default branch if invoked- /// from the primary repo root.- fn remove_current_worktree(&self, no_delete_branch: bool) -> Result<RemoveResult, GitError>;-/// Remove a worktree identified by branch name.+ ///+ /// When removing the current worktree from the main repo, automatically checks if+ /// already on default branch or switches to it first.fn remove_worktree_by_name(&self,branch_name: &str,@@ -167,47 +166,6 @@ impl RepositoryCliExt for Repository {}))}- fn remove_current_worktree(&self, no_delete_branch: bool) -> Result<RemoveResult, GitError> {- self.ensure_clean_working_tree()?;-- if self.is_in_worktree()? {- let worktree_root = self.worktree_root()?;- let current_branch = self- .current_branch()?- .ok_or_else(|| GitError::message("Not on a branch"))?;- let worktrees = self.list_worktrees()?;- let primary_worktree_dir = worktrees.worktrees[0].path.clone();-- return Ok(RemoveResult::RemovedWorktree {- primary_path: primary_worktree_dir,- worktree_path: worktree_root,- changed_directory: true,- branch_name: current_branch,- no_delete_branch,- target_branch: None,- });- }-- let current_branch = self.current_branch()?;- let default_branch = self.default_branch()?;-- if current_branch.as_deref() == Some(&default_branch) {- return Ok(RemoveResult::AlreadyOnDefault(default_branch));- }-- if let Err(err) = self.run_command(&["switch", &default_branch]) {- return Err(match err {- GitError::CommandFailed(msg) => GitError::SwitchFailed {- branch: default_branch.clone(),- error: msg,- },- other => other,- });- }-- Ok(RemoveResult::SwitchedToDefault(default_branch))- }-fn remove_worktree_by_name(&self,branch_name: &str,@@ -234,6 +192,11 @@ impl RepositoryCliExt for Repository {let current_worktree = self.worktree_root()?;let removing_current = current_worktree == worktree_path;+ // Error if trying to remove main worktree (align with git behavior)+ if removing_current && !self.is_in_worktree()? {+ return Err(GitError::CannotRemoveMainWorktree);+ }+let (primary_path, changed_directory) = if removing_current {let worktrees = self.list_worktrees()?;(worktrees.worktrees[0].path.clone(), true)diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex b4b158293..a2e738ce0 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -143,8 +143,6 @@ impl SwitchResult {/// Result of a worktree remove operationpub enum RemoveResult {- /// Already on default branch, no action taken- AlreadyOnDefault(String),/// Removed worktree and returned to primary (if needed)RemovedWorktree {primary_path: PathBuf,@@ -154,8 +152,6 @@ pub enum RemoveResult {no_delete_branch: bool,target_branch: Option<String>,},- /// Switched to default branch in main repo- SwitchedToDefault(String),}pub fn handle_switch(@@ -370,34 +366,21 @@ pub fn handle_switch(}pub fn handle_remove(- worktree_name: Option<&str>,+ worktree_name: &str,no_delete_branch: bool,background: bool,) -> Result<RemoveResult, GitError> {let repo = Repository::current();- // Resolve "@" to current branch early so progress message shows resolved name- let resolved_name = if let Some(name) = worktree_name {- Some(repo.resolve_worktree_name(name)?)- } else {- None- };-- // Show progress with resolved name (unless running in background - output handler will show command)+ // Show progress (unless running in background - output handler will show command)if !background {- let progress_msg = if let Some(ref b) = resolved_name {- format!("{CYAN}Removing worktree for {CYAN_BOLD}{b}{CYAN_BOLD:#}...{CYAN:#}")- } else {- format!("{CYAN}Removing worktree...{CYAN:#}")- };+ let progress_msg = format!(+ "{CYAN}Removing worktree for {CYAN_BOLD}{worktree_name}{CYAN_BOLD:#}...{CYAN:#}"+ );crate::output::progress(progress_msg)?;}- // Two modes: remove current worktree vs. remove by name- match resolved_name.as_deref() {- None => repo.remove_current_worktree(no_delete_branch),- Some(name) => repo.remove_worktree_by_name(name, no_delete_branch),- }+ repo.remove_worktree_by_name(worktree_name, no_delete_branch)}impl<'a> CommandContext<'a> {diff --git a/src/git/error.rs b/src/git/error.rsindex 8813e1cbc..e0c310e03 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -74,6 +74,8 @@ pub enum GitError {},/// Deleting a branch failedBranchDeletionFailed { branch: String, error: String },+ /// Cannot remove main worktree+ CannotRemoveMainWorktree,}impl GitError {@@ -331,6 +333,13 @@ impl std::fmt::Display for GitError {);write!(f, "{}", format_error_block(header, error))}++ GitError::CannotRemoveMainWorktree => {+ write!(+ f,+ "{ERROR_EMOJI} {ERROR}Cannot remove main worktree{ERROR:#}\n\n{HINT_EMOJI} {HINT}Use 'wt remove' from a secondary worktree, or 'wt switch' to change branches{HINT:#}"+ )+ }}}}diff --git a/src/main.rs b/src/main.rsindex c2500c3b6..a7e2863ef 100644--- a/src/main.rs+++ b/src/main.rs@@ -265,66 +265,56 @@ fn main() {worktrees,no_delete_branch,background,- } => {+ } => (|| -> Result<(), GitError> {+ let repo = Repository::current();+if worktrees.is_empty() {// No worktrees specified, remove current worktree- handle_remove(None, no_delete_branch, background)- .and_then(|result| handle_remove_output(&result, None, false, background))+ let current_branch = repo.resolve_worktree_name("@")?;+ let result = handle_remove(¤t_branch, no_delete_branch, background)?;+ handle_remove_output(&result, None, false, background)} else {// When removing multiple worktrees, we need to handle the current worktree last// to avoid deleting the directory we're currently in- (|| -> Result<(), GitError> {- let repo = Repository::current();- let current_worktree = repo.worktree_root().ok();-- // Partition worktrees into current and others- let mut others = Vec::new();- let mut current = None;-- for worktree_name in &worktrees {- // Resolve "@" to current branch (fail fast on errors like detached HEAD)- let resolved = repo.resolve_worktree_name(worktree_name)?;-- // Check if this is the current worktree by comparing branch names- if let Ok(Some(worktree_path)) = repo.worktree_for_branch(&resolved) {- if Some(&worktree_path) == current_worktree.as_ref() {- current = Some(worktree_name);- } else {- others.push(worktree_name);- }+ let current_worktree = repo.worktree_root().ok();++ // Partition worktrees into current and others, storing resolved names+ let mut others = Vec::new();+ let mut current = None;++ for worktree_name in &worktrees {+ // Resolve "@" to current branch (fail fast on errors like detached HEAD)+ let resolved = repo.resolve_worktree_name(worktree_name)?;++ // Check if this is the current worktree by comparing branch names+ if let Ok(Some(worktree_path)) = repo.worktree_for_branch(&resolved) {+ if Some(&worktree_path) == current_worktree.as_ref() {+ current = Some(resolved);} else {- // Worktree doesn't exist or branch not found, will error when we try to remove- others.push(worktree_name);+ others.push(resolved);}+ } else {+ // Worktree doesn't exist or branch not found, will error when we try to remove+ others.push(resolved);}+ }- // Remove others first, then current last- // Progress messages shown by handle_remove_output for all cases- for worktree in others.iter() {- let result =- handle_remove(Some(worktree.as_str()), no_delete_branch, background)?;- handle_remove_output(&result, Some(worktree.as_str()), false, background)?;- }+ // Remove others first, then current last+ // Progress messages shown by handle_remove_output for all cases+ for resolved in &others {+ let result = handle_remove(resolved, no_delete_branch, background)?;+ handle_remove_output(&result, Some(resolved), false, background)?;+ }- // Remove current worktree last (if it was in the list)- if let Some(current_name) = current {- let result = handle_remove(- Some(current_name.as_str()),- no_delete_branch,- background,- )?;- handle_remove_output(- &result,- Some(current_name.as_str()),- false,- background,- )?;- }+ // Remove current worktree last (if it was in the list)+ if let Some(resolved) = current {+ let result = handle_remove(&resolved, no_delete_branch, background)?;+ handle_remove_output(&result, Some(&resolved), false, background)?;+ }- Ok(())- })()+ Ok(())}- }+ })(),Commands::Merge {target,no_squash,diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 70e851b26..cbbb63628 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -48,48 +48,40 @@ fn format_remove_message(branch: Option<&str>,branch_deleted: bool,) -> String {- match result {- RemoveResult::AlreadyOnDefault(branch) => {- format!("{GREEN}Already on default branch {GREEN_BOLD}{branch}{GREEN_BOLD:#}{GREEN:#}")- }- RemoveResult::RemovedWorktree {- primary_path,- changed_directory,- branch_name,- no_delete_branch,- ..- } => {- // Build the action description based on actual outcome- let action = if *no_delete_branch || !branch_deleted {- "Removed worktree"- } else {- "Removed worktree & branch"- };+ let RemoveResult::RemovedWorktree {+ primary_path,+ changed_directory,+ branch_name,+ no_delete_branch,+ ..+ } = result;- let branch_display = branch.or(Some(branch_name));-- if *changed_directory {- if let Some(b) = branch_display {- // Re-establish GREEN after each green_bold reset to prevent color leak- format!(- "{GREEN}{action} for {GREEN_BOLD}{b}{GREEN_BOLD:#}{GREEN}, changed directory to {GREEN_BOLD}{}{GREEN_BOLD:#}{GREEN:#}",- primary_path.display()- )- } else {- format!(- "{GREEN}{action}, changed directory to {GREEN_BOLD}{}{GREEN_BOLD:#}{GREEN:#}",- primary_path.display()- )- }- } else if let Some(b) = branch_display {- format!("{GREEN}{action} for {GREEN_BOLD}{b}{GREEN_BOLD:#}{GREEN:#}")- } else {- format!("{GREEN}{action}{GREEN:#}")- }- }- RemoveResult::SwitchedToDefault(branch) => {- format!("{GREEN}Switched to default branch {GREEN_BOLD}{branch}{GREEN_BOLD:#}{GREEN:#}")+ // Build the action description based on actual outcome+ let action = if *no_delete_branch || !branch_deleted {+ "Removed worktree"+ } else {+ "Removed worktree & branch"+ };++ let branch_display = branch.or(Some(branch_name));++ if *changed_directory {+ if let Some(b) = branch_display {+ // Re-establish GREEN after each green_bold reset to prevent color leak+ format!(+ "{GREEN}{action} for {GREEN_BOLD}{b}{GREEN_BOLD:#}{GREEN}, changed directory to {GREEN_BOLD}{}{GREEN_BOLD:#}{GREEN:#}",+ primary_path.display()+ )+ } else {+ format!(+ "{GREEN}{action}, changed directory to {GREEN_BOLD}{}{GREEN_BOLD:#}{GREEN:#}",+ primary_path.display()+ )}+ } else if let Some(b) = branch_display {+ format!("{GREEN}{action} for {GREEN_BOLD}{b}{GREEN_BOLD:#}{GREEN:#}")+ } else {+ format!("{GREEN}{action}{GREEN:#}")}}@@ -182,13 +174,6 @@ pub fn handle_remove_output(strict_branch_deletion: bool,background: bool,) -> Result<(), GitError> {- // For non-worktree removals, show message immediately- if !matches!(result, RemoveResult::RemovedWorktree { .. }) {- super::success(format_remove_message(result, branch, false))?;- super::flush()?;- return Ok(());- }-let RemoveResult::RemovedWorktree {primary_path,worktree_path,@@ -196,10 +181,7 @@ pub fn handle_remove_output(branch_name,no_delete_branch,target_branch,- } = result- else {- unreachable!("Already handled non-RemovedWorktree cases above")- };+ } = result;// 1. Emit cd directive if needed - shell will execute this immediatelyif *changed_directory {diff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rsindex bbefd76d4..c6f19c55b 100644--- a/tests/integration_tests/directives.rs+++ b/tests/integration_tests/directives.rs@@ -85,13 +85,15 @@ fn test_remove_internal_directive() {.current_dir(repo.root_path());assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0+ success: false+ exit_code: 1----- stdout -----+ β [31mCannot remove main worktree[0m++ π‘ [2mUse 'wt remove' from a secondary worktree, or 'wt switch' to change branches[0m----- stderr ------ π [36mRemoving worktree...[0m- β [32mAlready on default branch [1m[32mmain[0m[0m+ π [36mRemoving worktree for [1m[36mmain[0m...[0m");});}@@ -111,11 +113,13 @@ fn test_remove_without_internal() {cmd.arg("remove").current_dir(repo.root_path());assert_cmd_snapshot!(cmd, @r"- success: true- exit_code: 0+ success: false+ exit_code: 1----- stdout ------ π [36mRemoving worktree...[0m- β [32mAlready on default branch [1m[32mmain[0m[0m+ π [36mRemoving worktree for [1m[36mmain[0m...[0m+ β [31mCannot remove main worktree[0m++ π‘ [2mUse 'wt remove' from a secondary worktree, or 'wt switch' to change branches[0m----- stderr -----");diff --git a/tests/snapshots/integration__integration_tests__remove__remove_already_on_default.snap b/tests/snapshots/integration__integration_tests__remove__remove_already_on_default.snapindex b4317b59d..1587e3b9d 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_already_on_default.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_already_on_default.snap@@ -15,12 +15,14 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp3lNiqW/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmptjyi3G/test-config.toml----success: true-exit_code: 0+success: false+exit_code: 1----- stdout ------π [36mRemoving worktree...[0m-β [32mAlready on default branch [1m[32mmain[0m[0m+π [36mRemoving worktree for [1m[36mmain[0m...[0m+β [31mCannot remove main worktree[0m++π‘ [2mUse 'wt remove' from a secondary worktree, or 'wt switch' to change branches[0m----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__remove__remove_dirty_working_tree.snap b/tests/snapshots/integration__integration_tests__remove__remove_dirty_working_tree.snapindex 8aaf4beab..349a656cb 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_dirty_working_tree.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_dirty_working_tree.snap@@ -15,12 +15,12 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpJ04hhT/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp9ZJ31J/test-config.toml---success: falseexit_code: 1----- stdout ------π [36mRemoving worktree...[0m+π [36mRemoving worktree for [1m[36mmain[0m...[0mβ [31mWorking tree has uncommitted changes[0mπ‘ [2mCommit or stash them first[0mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_from_worktree.snap b/tests/snapshots/integration__integration_tests__remove__remove_from_worktree.snapindex 3515ca320..c370cd339 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_from_worktree.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_from_worktree.snap@@ -15,12 +15,12 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpOZr488/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmprbP5WE/test-config.toml---success: trueexit_code: 0----- stdout ------π [36mRemoving worktree...[0m+π [36mRemoving worktree for [1m[36mfeature-wt[0m...[0mβ [32mRemoved worktree & branch for [1m[32mfeature-wt[0m[32m, changed directory to [1m[32m[REPO][0m[0m----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap b/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snapindex 8da5ff120..8717bc8ea 100644Binary files a/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap and b/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap differdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_switch_to_default.snap b/tests/snapshots/integration__integration_tests__remove__remove_switch_to_default.snapindex 4320fad9a..c00f9c771 100644--- a/tests/snapshots/integration__integration_tests__remove__remove_switch_to_default.snap+++ b/tests/snapshots/integration__integration_tests__remove__remove_switch_to_default.snap@@ -15,12 +15,14 @@ info:LANG: CLC_ALL: CSOURCE_DATE_EPOCH: "1761609600"- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpuKKDMf/test-config.toml+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpDxn7qo/test-config.toml----success: true-exit_code: 0+success: false+exit_code: 1----- stdout ------π [36mRemoving worktree...[0m-β [32mSwitched to default branch [1m[32mmain[0m[0m+π [36mRemoving worktree for [1m[36mfeature[0m...[0m+β [31mCannot remove main worktree[0m++π‘ [2mUse 'wt remove' from a secondary worktree, or 'wt switch' to change branches[0m----- stderr -----