Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Feat: Allow removing worktrees by name
Maximilian Roosb1b7737530bf
diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 12ee2261a..7e6e8b3f7 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -95,7 +95,7 @@ pub fn handle_merge(// Get primary worktree path before finishing (while we can still run git commands)let primary_worktree_dir = repo.main_worktree_root()?;- let result = handle_remove()?;+ let result = handle_remove(None)?;// Display output based on modehandle_remove_output(&result)?;diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex fa38c0106..f69df1166 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -138,6 +138,8 @@ pub enum RemoveResult {RemovedWorktree { primary_path: PathBuf },/// Switched to default branch in main repoSwitchedToDefault(String),+ /// Removed a different worktree (not the current one)+ RemovedOtherWorktree { branch: String },}pub fn handle_switch(@@ -228,10 +230,19 @@ pub fn handle_switch(})}-pub fn handle_remove() -> Result<RemoveResult, GitError> {+pub fn handle_remove(worktree_name: Option<&str>) -> Result<RemoveResult, GitError> {let repo = Repository::current();- // Check for uncommitted changes+ // Two modes: remove current worktree vs. remove by name+ match worktree_name {+ None => remove_current_worktree(&repo),+ Some(name) => remove_worktree_by_name(&repo, name),+ }+}++/// Remove the current worktree (original behavior)+fn remove_current_worktree(repo: &Repository) -> Result<RemoveResult, GitError> {+ // Check for uncommitted changes in current worktreerepo.ensure_clean_working_tree()?;// Get current state@@ -272,6 +283,68 @@ pub fn handle_remove() -> Result<RemoveResult, GitError> {}}+/// Remove a worktree by branch name+fn remove_worktree_by_name(repo: &Repository, branch_name: &str) -> Result<RemoveResult, GitError> {+ // Find the worktree for this branch+ let worktree_path = repo.worktree_for_branch(branch_name)?;++ let worktree_path = match worktree_path {+ Some(path) => path,+ None => {+ let error_bold = ERROR.bold();+ eprintln!(+ "{ERROR_EMOJI} {ERROR}No worktree found for branch {error_bold}{branch_name}{error_bold:#}{ERROR:#}"+ );+ return Err(GitError::CommandFailed(String::new()));+ }+ };++ // Check if the target worktree exists on disk+ if !worktree_path.exists() {+ let error_bold = ERROR.bold();+ eprintln!(+ "{ERROR_EMOJI} {ERROR}Worktree directory missing for {error_bold}{branch_name}{error_bold:#}{ERROR:#}"+ );+ eprintln!();+ eprintln!("{HINT_EMOJI} {HINT}Run 'git worktree prune' to clean up{HINT:#}");+ return Err(GitError::CommandFailed(String::new()));+ }++ // Check if the target worktree is clean (no uncommitted changes)+ let target_repo = Repository::at(&worktree_path);+ target_repo.ensure_clean_working_tree()?;++ // Get the current worktree root to check if we're removing ourselves+ let current_worktree = repo.worktree_root()?;+ let removing_current = current_worktree == worktree_path;++ // Get primary worktree path BEFORE removing (while we can still run git commands)+ let primary_worktree_dir = if removing_current {+ Some(repo.main_worktree_root()?)+ } else {+ None+ };++ // Remove the worktree+ if let Err(e) = repo.remove_worktree(&worktree_path) {+ eprintln!("{WARNING_EMOJI} {WARNING}Failed to remove worktree: {e}{WARNING:#}");+ eprintln!(+ "You may need to run 'git worktree remove {}' manually",+ worktree_path.display()+ );+ }++ // If we removed the current worktree, return to primary+ if let Some(primary_path) = primary_worktree_dir {+ Ok(RemoveResult::RemovedWorktree { primary_path })+ } else {+ // Stay where we are (no directory change needed)+ Ok(RemoveResult::RemovedOtherWorktree {+ branch: branch_name.to_string(),+ })+ }+}+/// Check for conflicting uncommitted changes in target worktreefn check_worktree_conflicts(repo: &Repository,diff --git a/src/main.rs b/src/main.rsindex ee88ad945..431a3efb4 100644--- a/src/main.rs+++ b/src/main.rs@@ -123,6 +123,9 @@ enum Commands {/// Finish current worktree, returning to primary if currentRemove {+ /// Worktree name or branch to remove (defaults to current worktree)+ worktree: Option<String>,+/// Use internal mode (outputs directives for shell wrapper)#[arg(long, hide = true)]internal: bool,@@ -332,7 +335,7 @@ fn main() {.and_then(|result| handle_switch_output(&result, &branch, execute.as_deref()))})}- Commands::Remove { internal } => {+ Commands::Remove { worktree, internal } => {// Initialize output context based on modelet output_mode = if internal {output::OutputMode::Directive@@ -341,7 +344,7 @@ fn main() {};output::initialize(output_mode);- handle_remove().and_then(|result| handle_remove_output(&result))+ handle_remove(worktree.as_deref()).and_then(|result| handle_remove_output(&result))}Commands::Push {target,diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex b4f89077c..23e369670 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -50,6 +50,9 @@ fn format_remove_message_plain(result: &RemoveResult) -> String {RemoveResult::SwitchedToDefault(branch) => {format!("Switched to default branch {bold}{branch}{bold:#}")}+ RemoveResult::RemovedOtherWorktree { branch } => {+ format!("Removed worktree for {bold}{branch}{bold:#}")+ }}}diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex ff58d277b..145b55cb2 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -78,3 +78,83 @@ fn test_remove_dirty_working_tree() {snapshot_remove("remove_dirty_working_tree", &repo, &[], None);}++#[test]+fn test_remove_by_name_from_main() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ // Create a worktree+ let _worktree_path = repo.add_worktree("feature-a", "feature-a");++ // Remove it by name from main repo+ snapshot_remove("remove_by_name_from_main", &repo, &["feature-a"], None);+}++#[test]+fn test_remove_by_name_from_other_worktree() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ // Create two worktrees+ let worktree_a = repo.add_worktree("feature-a", "feature-a");+ let _worktree_b = repo.add_worktree("feature-b", "feature-b");++ // From worktree A, remove worktree B by name+ snapshot_remove(+ "remove_by_name_from_other_worktree",+ &repo,+ &["feature-b"],+ Some(&worktree_a),+ );+}++#[test]+fn test_remove_current_by_name() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ let worktree_path = repo.add_worktree("feature-current", "feature-current");++ // Remove current worktree by specifying its name+ snapshot_remove(+ "remove_current_by_name",+ &repo,+ &["feature-current"],+ Some(&worktree_path),+ );+}++#[test]+fn test_remove_nonexistent_worktree() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ // Try to remove a worktree that doesn't exist+ snapshot_remove("remove_nonexistent_worktree", &repo, &["nonexistent"], None);+}++#[test]+fn test_remove_by_name_dirty_target() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");+ repo.setup_remote("main");++ let worktree_path = repo.add_worktree("feature-dirty", "feature-dirty");++ // Create a dirty file in the target worktree+ std::fs::write(worktree_path.join("dirty.txt"), "uncommitted changes")+ .expect("Failed to create file");++ // Try to remove it by name from main repo+ snapshot_remove(+ "remove_by_name_dirty_target",+ &repo,+ &["feature-dirty"],+ None,+ );+}diff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snapindex 1e67b1732..81bc3b1c5 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap@@ -343,7 +343,7 @@ _wt() {return 0;;wt__remove)- opts="-v -h --verbose --help"+ opts="-v -h --verbose --help [WORKTREE]"if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; thenCOMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )return 0diff --git a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snapindex bf6f7430c..057960a3b 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash_custom_prefix.snap@@ -345,7 +345,7 @@ _wt() {return 0;;wt__remove)- opts="-v -h --verbose --help"+ opts="-v -h --verbose --help [WORKTREE]"if [[ ${cur} == -* || ${COMP_CWORD} -eq 2 ]] ; thenCOMPREPLY=( $(compgen -W "${opts}" -- "${cur}") )return 0diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex d688c176a..c7c7c647f 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -229,6 +229,7 @@ _arguments "${_arguments_options[@]}" : \'--verbose[Enable verbose output (show git commands and debug info)]' \'-h[Print help]' \'--help[Print help]' \+'::worktree -- Worktree name or branch to remove (defaults to current worktree):_default' \&& ret=0;;(push)diff --git a/tests/snapshots/integration__integration_tests__remove__remove_by_name_dirty_target.snap b/tests/snapshots/integration__integration_tests__remove__remove_by_name_dirty_target.snapnew file mode 100644index 000000000..289a56412--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_by_name_dirty_target.snap@@ -0,0 +1,26 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - feature-dirty+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+β [31mWorking tree has uncommitted changes[0m++π‘ [2mCommit or stash them first[0mdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_by_name_from_main.snap b/tests/snapshots/integration__integration_tests__remove__remove_by_name_from_main.snapnew file mode 100644index 000000000..f18e6df38--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_by_name_from_main.snap@@ -0,0 +1,24 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - feature-a+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+β [32mRemoved worktree for [1mfeature-a[0m[0m++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__remove__remove_by_name_from_other_worktree.snap b/tests/snapshots/integration__integration_tests__remove__remove_by_name_from_other_worktree.snapnew file mode 100644index 000000000..813d35c04--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_by_name_from_other_worktree.snap@@ -0,0 +1,24 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - feature-b+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+β [32mRemoved worktree for [1mfeature-b[0m[0m++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__remove__remove_current_by_name.snap b/tests/snapshots/integration__integration_tests__remove__remove_current_by_name.snapnew file mode 100644index 000000000..780a65315--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_current_by_name.snap@@ -0,0 +1,25 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - feature-current+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: true+exit_code: 0+----- stdout -----+β [32mRemoved worktree, returned to primary+ [2mPath: [REPO][0m[0m++----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__remove__remove_nonexistent_worktree.snap b/tests/snapshots/integration__integration_tests__remove__remove_nonexistent_worktree.snapnew file mode 100644index 000000000..29c383bd8--- /dev/null+++ b/tests/snapshots/integration__integration_tests__remove__remove_nonexistent_worktree.snap@@ -0,0 +1,24 @@+---+source: tests/integration_tests/remove.rs+info:+ program: wt+ args:+ - remove+ - nonexistent+ env:+ CLICOLOR_FORCE: "1"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: /dev/null+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1704067200"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+β [31mNo worktree found for branch [1m[31mnonexistent[0m[0m