Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat: Add `config shell uninstall` command
Maximilian Roos6d9c12ce6c5c
diff --git a/src/cli.rs b/src/cli.rsindex 0316a66f0..75958d360 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -191,7 +191,7 @@ Skip confirmation prompt:wt config shell install --force```"#)]Install {- /// Shell to install (default: auto-detect)+ /// Shell to install (default: all)#[arg(value_enum)]shell: Option<Shell>,@@ -203,6 +203,39 @@ wt config shell install --force#[arg(long, default_value = DEFAULT_COMMAND_NAME)]command_name: String,},++ /// Remove shell integration from config files+ #[command(after_long_help = r#"## Removal++Removes shell integration lines from config files:+```bash+wt config shell uninstall+```++Remove from specific shell only:+```bash+wt config shell uninstall zsh+```++Skip confirmation prompt:+```bash+wt config shell uninstall --force+```++## Version Tolerance++Detects various forms of the integration pattern regardless of:+- Command prefix (wt, worktree, etc.)+- Minor syntax variations between versions"#)]+ Uninstall {+ /// Shell to uninstall (default: all)+ #[arg(value_enum)]+ shell: Option<Shell>,++ /// Skip confirmation prompt+ #[arg(short, long)]+ force: bool,+ },}#[derive(Subcommand)]diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rsindex c444788dd..d8467eeab 100644--- a/src/commands/configure_shell.rs+++ b/src/commands/configure_shell.rs@@ -12,11 +12,45 @@ pub struct ConfigureResult {pub config_line: String,}+pub struct UninstallResult {+ pub shell: Shell,+ pub path: PathBuf,+ pub action: UninstallAction,+ pub removed_line: String,+}++pub struct UninstallScanResult {+ pub results: Vec<UninstallResult>,+ pub not_found: Vec<(Shell, PathBuf)>,+}+pub struct ScanResult {pub configured: Vec<ConfigureResult>,pub skipped: Vec<(Shell, PathBuf)>, // Shell + first path that was checked}+#[derive(Debug, PartialEq)]+pub enum UninstallAction {+ Removed,+ WouldRemove,+}++impl UninstallAction {+ pub fn description(&self) -> &str {+ match self {+ UninstallAction::Removed => "Removed from",+ UninstallAction::WouldRemove => "Will remove from",+ }+ }++ pub fn emoji(&self) -> &'static str {+ match self {+ UninstallAction::Removed => SUCCESS_EMOJI,+ UninstallAction::WouldRemove => PROGRESS_EMOJI,+ }+ }+}+#[derive(Debug, PartialEq)]pub enum ConfigAction {Added,@@ -371,8 +405,7 @@ fn configure_fish_file(fn prompt_for_confirmation(results: &[ConfigureResult]) -> Result<bool, String> {use anstyle::Style;- use std::io::Write;- use worktrunk::styling::{INFO_EMOJI, eprint, eprintln};+ use worktrunk::styling::{eprint, eprintln};// CRITICAL: Flush stdout before writing to stderr to prevent stream interleaving// In directive mode, flushes both stdout (directives) and stderr (messages)@@ -402,6 +435,15 @@ fn prompt_for_confirmation(results: &[ConfigureResult]) -> Result<bool, String>eprintln!(); // Blank line after each shell block}+ prompt_yes_no()+}++/// Prompt user for yes/no confirmation, returns true if user confirms+fn prompt_yes_no() -> Result<bool, String> {+ use anstyle::Style;+ use std::io::Write;+ use worktrunk::styling::{INFO_EMOJI, eprint, eprintln};+let bold = Style::new().bold();eprint!("{INFO_EMOJI} Proceed? {bold}[y/N]{bold:#} ");io::stderr().flush().map_err(|e| e.to_string())?;@@ -411,9 +453,202 @@ fn prompt_for_confirmation(results: &[ConfigureResult]) -> Result<bool, String>.read_line(&mut input).map_err(|e| e.to_string())?;- // Blank line after user input to separate from resultseprintln!();let response = input.trim().to_lowercase();Ok(response == "y" || response == "yes")}++// Pattern detection for shell integration+fn has_integration_pattern(content: &str) -> bool {+ let lower = content.to_lowercase();+ lower.contains("wt init") || lower.contains("wt config shell init")+}++fn is_integration_line(line: &str) -> bool {+ let trimmed = line.trim();+ !trimmed.starts_with('#')+ && has_integration_pattern(trimmed)+ && (trimmed.contains("eval") || trimmed.contains("source") || trimmed.contains("if "))+}++pub fn handle_unconfigure_shell(+ shell_filter: Option<Shell>,+ skip_confirmation: bool,+) -> Result<UninstallScanResult, String> {+ // First, do a dry-run to see what would be changed+ let preview = scan_for_uninstall(shell_filter, true)?;++ // If nothing to do, return early+ if preview.results.is_empty() {+ return Ok(preview);+ }++ // Show what will be done and ask for confirmation (unless --force flag is used)+ if !skip_confirmation && !prompt_for_uninstall_confirmation(&preview.results)? {+ return Err("Cancelled by user".to_string());+ }++ // User confirmed (or --force flag was used), now actually apply the changes+ scan_for_uninstall(shell_filter, false)+}++fn scan_for_uninstall(+ shell_filter: Option<Shell>,+ dry_run: bool,+) -> Result<UninstallScanResult, String> {+ let shells = if let Some(shell) = shell_filter {+ vec![shell]+ } else {+ vec![Shell::Bash, Shell::Zsh, Shell::Fish]+ };++ let mut results = Vec::new();+ let mut not_found = Vec::new();++ for shell in shells {+ let paths = shell+ .config_paths("wt")+ .map_err(|e| format!("Failed to get config paths for {}: {}", shell, e))?;++ // For Fish, check for wt.fish specifically (delete entire file)+ if matches!(shell, Shell::Fish) {+ if let Some(fish_path) = paths.first() {+ if fish_path.exists() {+ if dry_run {+ results.push(UninstallResult {+ shell,+ path: fish_path.clone(),+ action: UninstallAction::WouldRemove,+ removed_line: "wt.fish".to_string(),+ });+ } else {+ fs::remove_file(fish_path).map_err(|e| {+ format!(+ "Failed to remove {}: {}",+ format_path_for_display(fish_path),+ e+ )+ })?;+ results.push(UninstallResult {+ shell,+ path: fish_path.clone(),+ action: UninstallAction::Removed,+ removed_line: "wt.fish".to_string(),+ });+ }+ } else {+ not_found.push((shell, fish_path.clone()));+ }+ }+ continue;+ }++ // For Bash/Zsh, scan config files+ let mut found = false;++ for path in &paths {+ if !path.exists() {+ continue;+ }++ match uninstall_from_file(shell, path, dry_run) {+ Ok(Some(result)) => {+ results.push(result);+ found = true;+ break; // Only process first matching file per shell+ }+ Ok(None) => {} // No integration found in this file+ Err(e) => return Err(e),+ }+ }++ if !found && let Some(first_path) = paths.first() {+ not_found.push((shell, first_path.clone()));+ }+ }++ Ok(UninstallScanResult { results, not_found })+}++fn uninstall_from_file(+ shell: Shell,+ path: &Path,+ dry_run: bool,+) -> Result<Option<UninstallResult>, String> {+ let content = fs::read_to_string(path)+ .map_err(|e| format!("Failed to read {}: {}", format_path_for_display(path), e))?;++ let lines: Vec<&str> = content.lines().collect();+ let integration_lines: Vec<(usize, &str)> = lines+ .iter()+ .enumerate()+ .filter(|(_, line)| is_integration_line(line))+ .map(|(i, line)| (i, *line))+ .collect();++ if integration_lines.is_empty() {+ return Ok(None);+ }++ // Use the first matching line for display+ let removed_line = integration_lines[0].1.trim().to_string();++ if dry_run {+ return Ok(Some(UninstallResult {+ shell,+ path: path.to_path_buf(),+ action: UninstallAction::WouldRemove,+ removed_line,+ }));+ }++ // Remove matching lines+ let indices_to_remove: std::collections::HashSet<usize> =+ integration_lines.iter().map(|(i, _)| *i).collect();+ let new_lines: Vec<&str> = lines+ .iter()+ .enumerate()+ .filter(|(i, _)| !indices_to_remove.contains(i))+ .map(|(_, line)| *line)+ .collect();++ let new_content = new_lines.join("\n");+ // Preserve trailing newline if original had one+ let new_content = if content.ends_with('\n') {+ format!("{}\n", new_content)+ } else {+ new_content+ };++ fs::write(path, new_content)+ .map_err(|e| format!("Failed to write {}: {}", format_path_for_display(path), e))?;++ Ok(Some(UninstallResult {+ shell,+ path: path.to_path_buf(),+ action: UninstallAction::Removed,+ removed_line,+ }))+}++fn prompt_for_uninstall_confirmation(results: &[UninstallResult]) -> Result<bool, String> {+ use anstyle::Style;+ use worktrunk::styling::eprintln;++ crate::output::flush_for_stderr_prompt().map_err(|e| e.to_string())?;++ for result in results {+ let bold = Style::new().bold();+ let shell = result.shell;+ let path = format_path_for_display(&result.path);++ eprintln!(+ "{} {} {bold}{shell}{bold:#} {bold}{path}{bold:#}",+ result.action.emoji(),+ result.action.description(),+ );+ }++ prompt_yes_no()+}diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 2d7b1796a..0908e758b 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -20,7 +20,7 @@ pub use config::{handle_config_create, handle_config_list, handle_config_refresh_cache,handle_config_status_set, handle_config_status_unset,};-pub use configure_shell::{ConfigAction, handle_configure_shell};+pub use configure_shell::{ConfigAction, handle_configure_shell, handle_unconfigure_shell};pub use init::handle_init;pub use list::handle_list;pub use merge::handle_merge;diff --git a/src/main.rs b/src/main.rsindex e0d09db26..800478d5d 100644--- a/src/main.rs+++ b/src/main.rs@@ -28,7 +28,7 @@ use commands::{handle_config_refresh_cache, handle_config_status_set, handle_config_status_unset,handle_configure_shell, handle_init, handle_list, handle_merge, handle_rebase, handle_remove,handle_squash, handle_standalone_ask_approvals, handle_standalone_clear_approvals,- handle_standalone_commit, handle_standalone_run_hook, handle_switch,+ handle_standalone_commit, handle_standalone_run_hook, handle_switch, handle_unconfigure_shell,};use output::{execute_user_command, handle_remove_output, handle_switch_output};@@ -300,7 +300,7 @@ fn main() {if let Some(path) = current_shell_path {crate::output::hint(format!(- "Restart your shell or run: source {path}"+ "Restart shell or run: source {path}"))?;}} else {@@ -309,6 +309,73 @@ fn main() {Ok(())})}+ ConfigShellCommand::Uninstall { shell, force } => {+ let explicit_shell = shell.is_some();+ handle_unconfigure_shell(shell, force)+ .map_err(|e| anyhow::anyhow!("{}", e))+ .and_then(|scan_result| {+ use worktrunk::styling::format_bash_with_gutter;++ let changes_count = scan_result.results.len();++ // Show results+ for result in &scan_result.results {+ let bold = Style::new().bold();+ let shell = result.shell;+ let path = format_path_for_display(&result.path);++ crate::output::success(format!(+ "{} {bold}{shell}{bold:#} {path}",+ result.action.description(),+ ))?;+ crate::output::gutter(format_bash_with_gutter(+ &result.removed_line,+ "",+ ))?;+ }++ // Show not found - warning if explicit shell, hint if auto-scan+ for (shell, path) in &scan_result.not_found {+ let path = format_path_for_display(path);+ if explicit_shell {+ crate::output::warning(format!(+ "No shell integration found in {path}"+ ))?;+ } else {+ crate::output::hint(format!(+ "No {shell} integration in {path}"+ ))?;+ }+ }++ // Exit with info if nothing was found+ if changes_count == 0 {+ if scan_result.not_found.is_empty() {+ crate::output::blank()?;+ crate::output::hint("No shell integration found to remove")?;+ }+ return Ok(());+ }++ // Summary+ crate::output::blank()?;+ let plural = if changes_count == 1 { "" } else { "s" };+ crate::output::success(format!(+ "Removed shell integration from {changes_count} shell{plural}"+ ))?;+ crate::output::blank()?;++ // Hint about restarting shell+ let current_shell = std::env::var("SHELL")+ .ok()+ .and_then(|s| s.rsplit('/').next().map(String::from));++ if current_shell.is_some() {+ crate::output::hint("Restart shell to complete uninstall")?;+ }+ Ok(())+ })+ }},ConfigCommand::Create => handle_config_create(),ConfigCommand::List => handle_config_list(),diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rsindex 960bef368..68a581525 100644--- a/tests/integration_tests/configure_shell.rs+++ b/tests/integration_tests/configure_shell.rs@@ -36,7 +36,7 @@ fn test_configure_shell_with_yes() {π‘ [2mfish ~/.config/fish/conf.d (not found)[0mβ Configured 1 shell- π‘ [2mRestart your shell or run: source ~/.zshrc[0m+ π‘ [2mRestart shell or run: source ~/.zshrc[0m----- stderr -----"#);@@ -79,7 +79,7 @@ fn test_configure_shell_specific_shell() {β Configured 1 shell- π‘ [2mRestart your shell or run: source ~/.zshrc[0m+ π‘ [2mRestart shell or run: source ~/.zshrc[0m----- stderr -----"#);@@ -162,7 +162,7 @@ fn test_configure_shell_fish() {β Configured 1 shell- π‘ [2mRestart your shell or run: source ~/.config/fish/conf.d/wt.fish[0m+ π‘ [2mRestart shell or run: source ~/.config/fish/conf.d/wt.fish[0m----- stderr -----");@@ -249,7 +249,7 @@ fn test_configure_shell_multiple_configs() {π‘ [2mfish ~/.config/fish/conf.d (not found)[0mβ Configured 2 shells- π‘ [2mRestart your shell or run: source ~/.zshrc[0m+ π‘ [2mRestart shell or run: source ~/.zshrc[0m----- stderr -----"#);@@ -312,7 +312,7 @@ fn test_configure_shell_mixed_states() {π‘ [2mfish ~/.config/fish/conf.d (not found)[0mβ Configured 1 shell- π‘ [2mRestart your shell or run: source ~/.zshrc[0m+ π‘ [2mRestart shell or run: source ~/.zshrc[0m----- stderr -----"#);@@ -333,3 +333,272 @@ fn test_configure_shell_mixed_states() {"Zsh config should be updated");}++/// Test `wt config shell uninstall` removes shell integration+#[test]+fn test_uninstall_shell() {+ let repo = TestRepo::new();+ let temp_home = TempDir::new().unwrap();++ // Create a fake .zshrc file with wt integration+ let zshrc_path = temp_home.path().join(".zshrc");+ fs::write(+ &zshrc_path,+ "# Existing config\nif command -v wt >/dev/null 2>&1; then eval \"$(command wt config shell init zsh)\"; fi\n",+ )+ .unwrap();++ let settings = setup_home_snapshot_settings(&temp_home);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.clean_cli_env(&mut cmd);+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("SHELL", "/bin/zsh");+ cmd.arg("config")+ .arg("shell")+ .arg("uninstall")+ .arg("--force")+ .current_dir(repo.root_path());++ assert_cmd_snapshot!(cmd, @r#"+ success: true+ exit_code: 0+ ----- stdout -----+ β Removed from [1mzsh[0m ~/.zshrc+ [107m [0m [1m[2m[35mif[0m [1m[2m[34mcommand[0m [2m[36m-v[0m wt [2m[36m>[0m/dev/null [2m[33m2[0m>&1; [1m[2m[35mthen[0m [1m[2m[34meval[0m [2m[32m"$([1m[2m[34mcommand[0m wt config shell init zsh)"[0m; [1m[2m[35mfi[0m[0m+ π‘ [2mNo bash integration in ~/.bashrc[0m+ π‘ [2mNo fish integration in ~/.config/fish/conf.d/wt.fish[0m++ β Removed shell integration from 1 shell++ π‘ [2mRestart shell to complete uninstall[0m++ ----- stderr -----+ "#);+ });++ // Verify the file no longer contains the integration+ let content = fs::read_to_string(&zshrc_path).unwrap();+ assert!(+ !content.contains("wt config shell init"),+ "Integration should be removed"+ );+ assert!(+ content.contains("# Existing config"),+ "Other content should be preserved"+ );+}++/// Test `wt config shell uninstall` with multiple shells+#[test]+fn test_uninstall_shell_multiple() {+ let repo = TestRepo::new();+ let temp_home = TempDir::new().unwrap();++ // Create multiple shell configs with wt integration+ let bash_config_path = temp_home.path().join(".bashrc");+ let zshrc_path = temp_home.path().join(".zshrc");+ fs::write(+ &bash_config_path,+ "# Bash config\nif command -v wt >/dev/null 2>&1; then eval \"$(command wt config shell init bash)\"; fi\n",+ )+ .unwrap();+ fs::write(+ &zshrc_path,+ "# Zsh config\nif command -v wt >/dev/null 2>&1; then eval \"$(command wt config shell init zsh)\"; fi\n",+ )+ .unwrap();++ let settings = setup_home_snapshot_settings(&temp_home);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.clean_cli_env(&mut cmd);+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("SHELL", "/bin/zsh");+ cmd.arg("config")+ .arg("shell")+ .arg("uninstall")+ .arg("--force")+ .current_dir(repo.root_path());++ assert_cmd_snapshot!(cmd, @r#"+ success: true+ exit_code: 0+ ----- stdout -----+ β Removed from [1mbash[0m ~/.bashrc+ [107m [0m [1m[2m[35mif[0m [1m[2m[34mcommand[0m [2m[36m-v[0m wt [2m[36m>[0m/dev/null [2m[33m2[0m>&1; [1m[2m[35mthen[0m [1m[2m[34meval[0m [2m[32m"$([1m[2m[34mcommand[0m wt config shell init bash)"[0m; [1m[2m[35mfi[0m[0m+ β Removed from [1mzsh[0m ~/.zshrc+ [107m [0m [1m[2m[35mif[0m [1m[2m[34mcommand[0m [2m[36m-v[0m wt [2m[36m>[0m/dev/null [2m[33m2[0m>&1; [1m[2m[35mthen[0m [1m[2m[34meval[0m [2m[32m"$([1m[2m[34mcommand[0m wt config shell init zsh)"[0m; [1m[2m[35mfi[0m[0m+ π‘ [2mNo fish integration in ~/.config/fish/conf.d/wt.fish[0m++ β Removed shell integration from 2 shells++ π‘ [2mRestart shell to complete uninstall[0m++ ----- stderr -----+ "#);+ });++ // Verify both files no longer contain the integration+ let bash_content = fs::read_to_string(&bash_config_path).unwrap();+ assert!(+ !bash_content.contains("wt config shell init"),+ "Bash integration should be removed"+ );++ let zsh_content = fs::read_to_string(&zshrc_path).unwrap();+ assert!(+ !zsh_content.contains("wt config shell init"),+ "Zsh integration should be removed"+ );+}++/// Test `wt config shell uninstall` when not installed+#[test]+fn test_uninstall_shell_not_found() {+ let repo = TestRepo::new();+ let temp_home = TempDir::new().unwrap();++ // Create a fake .zshrc file without wt integration+ let zshrc_path = temp_home.path().join(".zshrc");+ fs::write(&zshrc_path, "# Existing config\n").unwrap();++ let settings = setup_home_snapshot_settings(&temp_home);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.clean_cli_env(&mut cmd);+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("SHELL", "/bin/zsh");+ cmd.arg("config")+ .arg("shell")+ .arg("uninstall")+ .arg("zsh")+ .arg("--force")+ .current_dir(repo.root_path());++ assert_cmd_snapshot!(cmd, @r"+ success: true+ exit_code: 0+ ----- stdout -----+ π‘ No shell integration found in ~/.zshrc++ ----- stderr -----+ ");+ });+}++/// Test `wt config shell uninstall` for Fish (deletes file)+#[test]+fn test_uninstall_shell_fish() {+ let repo = TestRepo::new();+ let temp_home = TempDir::new().unwrap();++ // Create fish conf.d directory with wt.fish+ let conf_d = temp_home.path().join(".config/fish/conf.d");+ fs::create_dir_all(&conf_d).unwrap();+ let fish_config = conf_d.join("wt.fish");+ fs::write(+ &fish_config,+ "if type -q wt; command wt config shell init fish | source; end\n",+ )+ .unwrap();++ let settings = setup_home_snapshot_settings(&temp_home);+ settings.bind(|| {+ let mut cmd = wt_command();+ repo.clean_cli_env(&mut cmd);+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("SHELL", "/bin/fish");+ cmd.arg("config")+ .arg("shell")+ .arg("uninstall")+ .arg("fish")+ .arg("--force")+ .current_dir(repo.root_path());++ assert_cmd_snapshot!(cmd, @r"+ success: true+ exit_code: 0+ ----- stdout -----+ β Removed from [1mfish[0m ~/.config/fish/conf.d/wt.fish+ [107m [0m [1m[2m[34mwt.fish[0m[0m++ β Removed shell integration from 1 shell++ π‘ [2mRestart shell to complete uninstall[0m++ ----- stderr -----+ ");+ });++ // Verify the fish config file was deleted+ assert!(!fish_config.exists(), "Fish config file should be deleted");+}++/// Test install and then uninstall roundtrip+#[test]+fn test_install_uninstall_roundtrip() {+ let repo = TestRepo::new();+ let temp_home = TempDir::new().unwrap();++ // Create initial config file+ let zshrc_path = temp_home.path().join(".zshrc");+ fs::write(+ &zshrc_path,+ "# Existing config\nexport PATH=$HOME/bin:$PATH\n",+ )+ .unwrap();++ // First install+ {+ let mut cmd = wt_command();+ repo.clean_cli_env(&mut cmd);+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("SHELL", "/bin/zsh");+ cmd.arg("config")+ .arg("shell")+ .arg("install")+ .arg("zsh")+ .arg("--force")+ .current_dir(repo.root_path());++ let output = cmd.output().expect("Failed to execute command");+ assert!(output.status.success(), "Install should succeed");+ }++ // Verify installed+ let content = fs::read_to_string(&zshrc_path).unwrap();+ assert!(content.contains("wt config shell init zsh"));++ // Then uninstall+ {+ let mut cmd = wt_command();+ repo.clean_cli_env(&mut cmd);+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("SHELL", "/bin/zsh");+ cmd.arg("config")+ .arg("shell")+ .arg("uninstall")+ .arg("zsh")+ .arg("--force")+ .current_dir(repo.root_path());++ let output = cmd.output().expect("Failed to execute command");+ assert!(output.status.success(), "Uninstall should succeed");+ }++ // Verify uninstalled but other content preserved+ let content = fs::read_to_string(&zshrc_path).unwrap();+ assert!(+ !content.contains("wt config shell init"),+ "Integration should be removed"+ );+ assert!(+ content.contains("# Existing config"),+ "Comment should be preserved"+ );+ assert!(+ content.contains("export PATH=$HOME/bin:$PATH"),+ "PATH export should be preserved"+ );+}diff --git a/tests/snapshots/integration__integration_tests__help__help_config_shell.snap b/tests/snapshots/integration__integration_tests__help__help_config_shell.snapindex 9e038f6e6..cf79514de 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_shell.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_shell.snap@@ -19,8 +19,9 @@ wt config shell - Shell integration setupUsage: wt config shell [OPTIONS] <COMMAND>Commands:- init Generate shell integration code- install Write shell integration to config files+ init Generate shell integration code+ install Write shell integration to config files+ uninstall Remove shell integration from config filesOptions:-h, --help