Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Refactor shell integration detection to be command-aware
Maximilian Roos64ffa8b6e626
diff --git a/src/commands/config.rs b/src/commands/config.rsindex 95131e63a..ac0dcf935 100644--- a/src/commands/config.rs+++ b/src/commands/config.rs@@ -344,7 +344,8 @@ fn render_shell_status(out: &mut String) -> anyhow::Result<()> {writeln!(out, "{}", format_heading("SHELL INTEGRATION", None))?;// Use the same detection logic as `wt config shell install`- let scan_result = match scan_shell_configs(None, true, "wt") {+ let cmd = crate::binary_name();+ let scan_result = match scan_shell_configs(None, true, &cmd) {Ok(r) => r,Err(e) => {writeln!(@@ -399,7 +400,7 @@ fn render_shell_status(out: &mut String) -> anyhow::Result<()> {// For fish, check completions file separatelyif matches!(shell, Shell::Fish)- && let Ok(completion_path) = shell.completion_path()+ && let Ok(completion_path) = shell.completion_path_with_prefix(&cmd){let completion_display = format_path_for_display(&completion_path);if completion_path.exists() {diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rsindex 22daf3b1b..8ca6bff27 100644--- a/src/commands/configure_shell.rs+++ b/src/commands/configure_shell.rs@@ -664,25 +664,13 @@ pub fn process_shell_completions(Ok(results)}-// 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,+ cmd: &str,) -> Result<UninstallScanResult, String> {// First, do a dry-run to see what would be changed- let preview = scan_for_uninstall(shell_filter, true)?;+ let preview = scan_for_uninstall(shell_filter, true, cmd)?;// If nothing to do, return earlyif preview.results.is_empty() && preview.completion_results.is_empty() {@@ -697,12 +685,13 @@ pub fn handle_unconfigure_shell(}// User confirmed (or --force flag was used), now actually apply the changes- scan_for_uninstall(shell_filter, false)+ scan_for_uninstall(shell_filter, false, cmd)}fn scan_for_uninstall(shell_filter: Option<Shell>,dry_run: bool,+ cmd: &str,) -> Result<UninstallScanResult, String> {#[cfg(windows)]let default_shells = vec![Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell];@@ -716,10 +705,10 @@ fn scan_for_uninstall(for &shell in &shells {let paths = shell- .config_paths()+ .config_paths_with_prefix(cmd).map_err(|e| format!("Failed to get config paths for {}: {}", shell, e))?;- // For Fish, check for wt.fish specifically (delete entire file)+ // For Fish, delete entire {cmd}.fish fileif matches!(shell, Shell::Fish) {if let Some(fish_path) = paths.first() {if fish_path.exists() {@@ -758,7 +747,7 @@ fn scan_for_uninstall(continue;}- match uninstall_from_file(shell, path, dry_run) {+ match uninstall_from_file(shell, path, dry_run, cmd) {Ok(Some(result)) => {results.push(result);found = true;@@ -784,7 +773,7 @@ fn scan_for_uninstall(}let completion_path = shell- .completion_path()+ .completion_path_with_prefix(cmd).map_err(|e| format!("Failed to get completion path for {}: {}", shell, e))?;if completion_path.exists() {@@ -821,6 +810,7 @@ fn uninstall_from_file(shell: Shell,path: &Path,dry_run: bool,+ cmd: &str,) -> Result<Option<UninstallResult>, String> {let content = fs::read_to_string(path).map_err(|e| format!("Failed to read {}: {}", format_path_for_display(path), e))?;@@ -829,7 +819,7 @@ fn uninstall_from_file(let integration_lines: Vec<(usize, &str)> = lines.iter().enumerate()- .filter(|(_, line)| is_integration_line(line))+ .filter(|(_, line)| shell::is_shell_integration_line(line, cmd)).map(|(i, line)| (i, *line)).collect();@@ -1024,31 +1014,50 @@ mod tests {}#[test]- fn test_has_integration_pattern() {- assert!(has_integration_pattern("wt init bash"));- assert!(has_integration_pattern("WT INIT zsh")); // Case insensitive- assert!(has_integration_pattern("wt config shell init"));- assert!(!has_integration_pattern("echo hello"));- assert!(!has_integration_pattern("wt merge"));- }+ fn test_is_shell_integration_line() {+ // Valid integration lines for "wt"+ assert!(shell::is_shell_integration_line(+ "eval \"$(wt config shell init bash)\"",+ "wt"+ ));+ assert!(shell::is_shell_integration_line(+ " eval \"$(wt config shell init zsh)\" ",+ "wt"+ ));+ assert!(shell::is_shell_integration_line(+ "if command -v wt; then eval \"$(wt config shell init bash)\"; fi",+ "wt"+ ));+ assert!(shell::is_shell_integration_line(+ "source <(wt config shell init fish)",+ "wt"+ ));- #[test]- fn test_is_integration_line() {- // Valid integration lines- assert!(is_integration_line("eval \"$(wt init bash)\""));- assert!(is_integration_line(" eval \"$(wt init zsh)\" "));- assert!(is_integration_line(- "if [ -n \"$BASH_VERSION\" ]; then eval \"$(wt init bash)\"; fi"+ // Valid integration lines for "git-wt"+ assert!(shell::is_shell_integration_line(+ "eval \"$(git-wt config shell init bash)\"",+ "git-wt"+ ));+ assert!(!shell::is_shell_integration_line(+ "eval \"$(wt config shell init bash)\"",+ "git-wt"));- assert!(is_integration_line("source <(wt init fish)"));// Not integration lines (comments)- assert!(!is_integration_line("# eval \"$(wt init bash)\""));- assert!(!is_integration_line(" # wt init zsh"));+ assert!(!shell::is_shell_integration_line(+ "# eval \"$(wt config shell init bash)\"",+ "wt"+ ));// Not integration lines (no eval/source/if)- assert!(!is_integration_line("wt init bash"));- assert!(!is_integration_line("echo wt init bash"));+ assert!(!shell::is_shell_integration_line(+ "wt config shell init bash",+ "wt"+ ));+ assert!(!shell::is_shell_integration_line(+ "echo wt config shell init bash",+ "wt"+ ));}#[test]diff --git a/src/main.rs b/src/main.rsindex 6941b6e35..63e14ee59 100644--- a/src/main.rs+++ b/src/main.rs@@ -826,7 +826,7 @@ fn main() {}ConfigShellCommand::Uninstall { shell, force } => {let explicit_shell = shell.is_some();- handle_unconfigure_shell(shell, force)+ handle_unconfigure_shell(shell, force, &binary_name()).map_err(|e| anyhow::anyhow!("{}", e)).and_then(|scan_result| {let shell_count = scan_result.results.len();diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex b68ca8d8d..2fbcdafa8 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -314,7 +314,11 @@ pub fn handle_switch_output(if let Some(warning) = path_mismatch_warning {super::print(warning)?;}- } else if Shell::is_integration_configured().ok().flatten().is_some() {+ } else if Shell::is_integration_configured(&crate::binary_name())+ .ok()+ .flatten()+ .is_some()+ {// Shell wrapper is configured but user ran binary directlysuper::print(warning_message(cformat!("Worktree for <bold>{branch}</> @ <bold>{path_display}</>, but cannot change directory — shell integration not active"diff --git a/src/shell.rs b/src/shell.rsindex c098f874b..856df0cde 100644--- a/src/shell.rs+++ b/src/shell.rs@@ -41,6 +41,36 @@ fn home_dir_required() -> Result<PathBuf, std::io::Error> {})}+/// Check if a line contains shell integration for the given command.+///+/// Returns true if the line:+/// - Is not a comment (doesn't start with #)+/// - Contains `{cmd} config shell init`+/// - Contains an execution context (eval, source, Invoke-Expression, or conditional)+///+/// Used by both detection (is shell integration configured?) and+/// uninstall (which lines to remove?).+pub fn is_shell_integration_line(line: &str, cmd: &str) -> bool {+ let trimmed = line.trim();++ // Skip comments (# for POSIX shells, <# #> for PowerShell)+ if trimmed.starts_with('#') {+ return false;+ }++ // Must contain the init pattern for this command+ let init_pattern = format!("{cmd} config shell init");+ if !trimmed.contains(&init_pattern) {+ return false;+ }++ // Must be in an execution context+ trimmed.contains("eval")+ || trimmed.contains("source")+ || trimmed.contains("Invoke-Expression")+ || trimmed.contains("if ")+}+/// Supported shells////// Currently supported: bash, fish, zsh, powershell@@ -182,14 +212,15 @@ impl Shell {}}- /// Check if shell integration is configured in any shell's config file+ /// Check if shell integration is configured for the given command name.////// Returns the path to the first config file with integration if found./// This helps detect the "configured but not restarted shell" state.///- /// This function is prefix-agnostic - it detects integration patterns regardless- /// of what cmd was used during configuration (wt, worktree, etc).- pub fn is_integration_configured() -> Result<Option<PathBuf>, std::io::Error> {+ /// The `cmd` parameter specifies the command name to look for (e.g., "wt" or "git-wt").+ /// This ensures we only consider integration "configured" if it uses the same binary+ /// we're running as - prevents confusion when users have multiple installs.+ pub fn is_integration_configured(cmd: &str) -> Result<Option<PathBuf>, std::io::Error> {use std::fs;use std::io::{BufRead, BufReader};@@ -209,7 +240,6 @@ impl Shell {.join(".zshrc"),];- // Check standard config files for eval pattern (any prefix)for path in config_files {if !path.exists() {continue;@@ -218,54 +248,39 @@ impl Shell {if let Ok(file) = fs::File::open(&path) {let reader = BufReader::new(file);for line in reader.lines().map_while(Result::ok) {- let trimmed = line.trim();- // Skip comments- if trimmed.starts_with('#') {- continue;- }- // Match lines containing: eval "$(... init ...)" or eval '$(... init ...)'- // This catches both the direct pattern and the guarded pattern:- // eval "$(wt config shell init bash)"- // if command -v wt ...; then eval "$(command wt config shell init zsh)"; fi- if (trimmed.contains("eval \"$(") || trimmed.contains("eval '$("))- && trimmed.contains(" init ")- {+ if is_shell_integration_line(&line, cmd) {return Ok(Some(path));}}}}- // Check Fish conf.d directory for any .fish files (Fish integration)+ // Check Fish conf.d directory - look for {cmd}.fish file specificallylet fish_conf_d = home.join(".config/fish/conf.d");- if fish_conf_d.exists()- && let Ok(entries) = fs::read_dir(&fish_conf_d)+ let fish_config = fish_conf_d.join(format!("{cmd}.fish"));+ if fish_config.exists()+ && let Ok(file) = fs::File::open(&fish_config){- for entry in entries.flatten() {- let path = entry.path();- if path.extension().and_then(|s| s.to_str()) == Some("fish")- && let Ok(content) = fs::read_to_string(&path)- {- // Look for wt shell integration (new protocol uses wt_exec + eval)- if content.contains("function wt_exec")- && content.contains("--internal")- && content.contains("eval")- {- return Ok(Some(path));- }+ let reader = BufReader::new(file);+ for line in reader.lines().map_while(Result::ok) {+ if is_shell_integration_line(&line, cmd) {+ return Ok(Some(fish_config));}}}// Check PowerShell profiles for integration (both Core and 5.1)for profile_path in powershell_profile_paths(&home) {- if profile_path.exists()- && let Ok(content) = fs::read_to_string(&profile_path)- {- // Look for PowerShell integration pattern:- // Invoke-Expression (& wt config shell init powershell)- if content.contains("Invoke-Expression") && content.contains("shell init") {- return Ok(Some(profile_path));+ if !profile_path.exists() {+ continue;+ }++ if let Ok(file) = fs::File::open(&profile_path) {+ let reader = BufReader::new(file);+ for line in reader.lines().map_while(Result::ok) {+ if is_shell_integration_line(&line, cmd) {+ return Ok(Some(profile_path));+ }}}}@@ -454,6 +469,7 @@ pub fn is_current_shell_zsh() -> bool {#[cfg(test)]mod tests {use super::*;+ use rstest::rstest;#[test]fn test_shell_from_str() {@@ -680,4 +696,20 @@ mod tests {"Output should contain custom prefix");}++ /// Verify that `config_line_with_prefix()` generates lines that+ /// `is_shell_integration_line()` can detect.+ ///+ /// This prevents install and detection from drifting out of sync.+ #[rstest]+ fn test_config_line_detected_by_is_shell_integration_line(+ #[values(Shell::Bash, Shell::Zsh, Shell::Fish, Shell::PowerShell)] shell: Shell,+ #[values("wt", "git-wt")] prefix: &str,+ ) {+ let line = shell.config_line_with_prefix(prefix);+ assert!(+ is_shell_integration_line(&line, prefix),+ "{shell} config_line_with_prefix({prefix:?}) not detected:\n {line}"+ );+ }}