Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(shell): configure remaining shells after an rc file error (#4583)
Worktrunk Bot7eb2f3ce5e0f
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rsindex fe8c3ea31..ba02857b7 100644--- a/src/commands/configure_shell.rs+++ b/src/commands/configure_shell.rs@@ -117,6 +117,7 @@ pub struct ScanResult {pub configured: Vec<ConfigureResult>,pub completion_results: Vec<CompletionResult>,pub skipped: Vec<(Shell, PathBuf)>, // Shell + first path that was checked+ pub failures: Vec<String>,/// Zsh was configured but compinit is missing (completions won't work without it)pub zsh_needs_compinit: bool,/// Legacy/stranded files cleaned up during install, paired with the shell@@ -359,7 +360,7 @@ pub fn handle_configure_shell(shell::validate_shell_command_name(&cmd)?;// First, do a dry-run to see what would be changed- let mut preview = scan_shell_configs(shell_filter, true, &cmd)?;+ let mut preview = scan_shell_configs_inner(shell_filter, true, &cmd, true)?;preview.completion_results = preview_shell_completions(&preview.configured, &cmd)?;// If nothing to do, return early@@ -435,7 +436,7 @@ pub(crate) fn apply_confirmed_shell_config(return Ok(preview);}- let mut result = scan_shell_configs(shell_filter, false, cmd)?;+ let mut result = scan_shell_configs_inner(shell_filter, false, cmd, true)?;result.completion_results =apply_shell_completions(preview.completion_results, &result.configured, cmd)?;@@ -563,6 +564,20 @@ pub fn scan_shell_configs(shell_filter: Option<Shell>,dry_run: bool,cmd: &str,+) -> Result<ScanResult, ShellConfigError> {+ scan_shell_configs_inner(shell_filter, dry_run, cmd, false)+}++/// Preview an install while retaining rc-file failures so other shells can be offered.+pub(crate) fn preview_shell_configs_for_install(cmd: &str) -> Result<ScanResult, ShellConfigError> {+ scan_shell_configs_inner(None, true, cmd, true)+}++fn scan_shell_configs_inner(+ shell_filter: Option<Shell>,+ dry_run: bool,+ cmd: &str,+ continue_on_error: bool,) -> Result<ScanResult, ShellConfigError> {shell::validate_shell_command_name(cmd)?;@@ -585,6 +600,7 @@ pub fn scan_shell_configs(let mut results = Vec::new();let mut skipped = Vec::new();+ let mut failures = Vec::new();for shell in shells {let paths = shell@@ -645,9 +661,11 @@ pub fn scan_shell_configs(Ok(Some(result)) => results.push(result),Ok(None) => {} // No action neededErr(e) => {- // For non-critical errors, we could continue with other shells- // but for now we'll fail fast- return Err(format!("Failed to configure {shell}: {e}").into());+ let message = format!("Failed to configure {shell}: {e}");+ if !continue_on_error {+ return Err(message.into());+ }+ failures.push(message);}}}@@ -674,6 +692,7 @@ pub fn scan_shell_configs(configured: results,completion_results: Vec::new(),skipped,+ failures,zsh_needs_compinit: false, // Caller handles compinit detectionlegacy_cleanups: Vec::new(), // Caller handles legacy cleanup})@@ -863,6 +882,12 @@ fn contains_shell_integration(shell: Shell,cmd: &str,) -> Result<bool, String> {+ if content.starts_with(&[0xff, 0xfe]) || content.starts_with(&[0xfe, 0xff]) {+ return Err(format!(+ "{} is not UTF-8 (looks like UTF-16); re-save it as UTF-8 to configure {shell}",+ format_path_for_display(path)+ ));+ }// Check for the canonical line and older/manual forms for this shell.for line in content.split(|byte| *byte == b'\n') {let line = std::str::from_utf8(line).map_err(|e| {diff --git a/src/main.rs b/src/main.rsindex e3843eb95..fa1c32c4f 100644--- a/src/main.rs+++ b/src/main.rs@@ -555,16 +555,27 @@ fn handle_config_shell_command(action: ConfigShellCommand, yes: bool) -> anyhow:// Show skipped shells first so user knows what was triedif scan_result.configured.is_empty() {crate::output::print_skipped_shells(&scan_result.skipped);+ if !scan_result.failures.is_empty() {+ return Err(anyhow::anyhow!(scan_result.failures.join("\n")));+ }return Err(worktrunk::git::GitError::Other {message: "No shell config files found".into(),}.into());}- // For --dry-run, preview was already shown by handler- if dry_run {- return Ok(());+ // For --dry-run, preview was already shown by handler.+ if !dry_run {+ crate::output::print_shell_install_result(&scan_result, &cmd);+ }+ if !scan_result.failures.is_empty() {+ for failure in &scan_result.failures {+ eprintln!("{}", warning_message(failure));+ }+ return Err(anyhow::anyhow!(+ "Could not configure {} shell(s)",+ scan_result.failures.len()+ ));}- crate::output::print_shell_install_result(&scan_result, &cmd);Ok(())})}diff --git a/src/output/shell_integration.rs b/src/output/shell_integration.rsindex 6c4570cc4..531114a07 100644--- a/src/output/shell_integration.rs+++ b/src/output/shell_integration.rs@@ -84,8 +84,8 @@ use worktrunk::styling::{use crate::commands::configure_shell::{ConfigAction, ShellConfigError, UninstallScanResult, apply_confirmed_shell_config,- collect_legacy_cleanups, format_matched_lines, preview_shell_completions, prompt_for_install,- scan_shell_configs,+ collect_legacy_cleanups, format_matched_lines, preview_shell_completions,+ preview_shell_configs_for_install, prompt_for_install, scan_shell_configs,};/// Git config key tracking how many times the shell-integration install hint@@ -522,7 +522,7 @@ pub fn prompt_shell_integration(// Scan ALL shells (same as `wt config shell install`)// Only includes shells where config files already exist- let mut scan = scan_shell_configs(None, true, binary_name)+ let mut scan = preview_shell_configs_for_install(binary_name).map_err(|e| e.context("Failed to scan shell configs"))?;// No config files exist - show install hint@@ -569,6 +569,16 @@ pub fn prompt_shell_integration(print_shell_install_result(&install_result, binary_name);+ if !install_result.failures.is_empty() {+ for failure in &install_result.failures {+ eprintln!("{}", warning_message(failure));+ }+ anyhow::bail!(+ "Could not configure {} shell(s)",+ install_result.failures.len()+ );+ }+Ok(true)}diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rsindex 22c605b91..d5f697e57 100644--- a/tests/integration_tests/configure_shell.rs+++ b/tests/integration_tests/configure_shell.rs@@ -177,6 +177,35 @@ fn test_configure_shell_bashrc_directory_fails(repo: TestRepo, temp_home: TempDiassert!(bashrc.is_dir());}+#[rstest]+fn test_configure_shell_continues_after_invalid_bashrc(repo: TestRepo, temp_home: TempDir) {+ let bashrc = temp_home.path().join(".bashrc");+ let zshrc = temp_home.path().join(".zshrc");+ let utf16_bashrc = b"\xff\xfe#\0 \0t\0e\0s\0t\0\n\0";+ fs::write(&bashrc, utf16_bashrc).unwrap();+ fs::write(&zshrc, "# zsh config\n").unwrap();++ let mut cmd = wt_command();+ repo.configure_wt_cmd(&mut cmd);+ set_temp_home_env(&mut cmd, temp_home.path());+ cmd.env("SHELL", "/bin/zsh");+ cmd.args(["config", "shell", "install", "--yes"])+ .current_dir(repo.root_path());+ let output = cmd.output().unwrap();++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(!output.status.success(), "{stderr}");+ assert!(stderr.contains("Failed to configure bash"), "{stderr}");+ assert!(stderr.contains("not UTF-8 (looks like UTF-16)"), "{stderr}");+ assert!(stderr.contains("Configured 1 shell"), "{stderr}");+ assert!(+ fs::read_to_string(&zshrc)+ .unwrap()+ .contains("config shell init zsh")+ );+ assert_eq!(fs::read(&bashrc).unwrap(), utf16_bashrc);+}+#[rstest]fn test_configure_shell_already_exists(repo: TestRepo, temp_home: TempDir) {// Create a fake .zshrc file with the line already presentdiff --git a/tests/integration_tests/shell_integration_prompt.rs b/tests/integration_tests/shell_integration_prompt.rsindex 104653cde..fb99bdc1e 100644--- a/tests/integration_tests/shell_integration_prompt.rs+++ b/tests/integration_tests/shell_integration_prompt.rs@@ -653,6 +653,71 @@ mod pty_tests {});}+ #[rstest]+ fn test_prompt_reports_shell_that_fails_after_confirmation(repo: TestRepo) {+ let temp_home = TempDir::new().unwrap();+ let bashrc = temp_home.path().join(".bashrc");+ let zshrc = temp_home.path().join(".zshrc");+ fs::write(&bashrc, "# bash config\n").unwrap();+ fs::write(&zshrc, "# zsh config\n").unwrap();++ let mut env_vars = repo.test_env_vars();+ env_vars.push(("SHELL".to_string(), "/bin/bash".to_string()));+ let cmd = build_pty_command(+ wt_bin().to_str().unwrap(),+ &["switch", "--create", "feature"],+ repo.root_path(),+ &env_vars,+ Some(temp_home.path()),+ );+ let invalid_bashrc = b"\xff\xfe#\0 \0t\0e\0s\0t\0\n\0";+ let (output, exit_code) = exec_cmd_in_pty_prompted_with(cmd, &["y\n"], "[y/N", |_| {+ fs::write(&bashrc, invalid_bashrc).unwrap();+ });++ // The installation offer is best-effort; its failure does not undo the switch.+ assert_eq!(exit_code, 0, "{output}");+ assert!(output.contains("Failed to configure bash"), "{output}");+ assert!(output.contains("Configured 1 shell"), "{output}");+ assert_eq!(fs::read(&bashrc).unwrap(), invalid_bashrc);+ assert!(+ fs::read_to_string(&zshrc)+ .unwrap()+ .contains("config shell init zsh")+ );+ }++ #[rstest]+ fn test_prompt_installs_other_shells_when_bashrc_is_invalid(repo: TestRepo) {+ let temp_home = TempDir::new().unwrap();+ let bashrc = temp_home.path().join(".bashrc");+ let zshrc = temp_home.path().join(".zshrc");+ let invalid_bashrc = b"\xff\xfe#\0 \0t\0e\0s\0t\0\n\0";+ fs::write(&bashrc, invalid_bashrc).unwrap();+ fs::write(&zshrc, "# zsh config\n").unwrap();++ let mut env_vars = repo.test_env_vars();+ env_vars.push(("SHELL".to_string(), "/bin/bash".to_string()));+ let cmd = build_pty_command(+ wt_bin().to_str().unwrap(),+ &["switch", "--create", "feature"],+ repo.root_path(),+ &env_vars,+ Some(temp_home.path()),+ );+ let (output, exit_code) = exec_cmd_in_pty_prompted_with(cmd, &["y\n"], "[y/N", |_| {});++ assert_eq!(exit_code, 0, "{output}");+ assert!(output.contains("Failed to configure bash"), "{output}");+ assert!(output.contains("Configured 1 shell"), "{output}");+ assert_eq!(fs::read(&bashrc).unwrap(), invalid_bashrc);+ assert!(+ fs::read_to_string(&zshrc)+ .unwrap()+ .contains("config shell init zsh")+ );+ }+#[rstest]#[case(false)]#[case(true)]