Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(shell): preview and confirm legacy-file removal on `shell install` (#3648)

Worktrunk Bot13bc27e70ae3
diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rs
index 649d7aebc..bde49546d 100644
--- a/src/commands/configure_shell.rs
+++ b/src/commands/configure_shell.rs
@@ -179,8 +179,16 @@ fn is_worktrunk_managed_content(content: &str) -> bool {
/// {cmd}` defined there is already loaded by the time fish would autoload
/// `functions/{cmd}.fish`, and the stale wrapper wins every time.
///
+/// With `dry_run`, the same detection runs but nothing is removed — the returned
+/// paths are what a real run *would* delete, so a preview and the confirmation
+/// prompt can name them before the user consents (issue #3644).
+///
/// Returns the paths of files that were cleaned up, each paired with `Shell::Fish`.
-fn cleanup_legacy_fish_conf_d(configured: &[ConfigureResult], cmd: &str) -> Vec<(Shell, PathBuf)> {
+fn cleanup_legacy_fish_conf_d(
+ configured: &[ConfigureResult],
+ cmd: &str,
+ dry_run: bool,
+) -> Vec<(Shell, PathBuf)> {
let mut cleaned = Vec::new();
// Clean up if fish was part of the install (regardless of whether it already existed)
@@ -201,6 +209,11 @@ fn cleanup_legacy_fish_conf_d(configured: &[ConfigureResult], cmd: &str) -> Vec<
return cleaned;
}
+ if dry_run {
+ cleaned.push((Shell::Fish, legacy_path));
+ return cleaned;
+ }
+
match fs::remove_file(&legacy_path) {
Ok(()) => {
cleaned.push((Shell::Fish, legacy_path));
@@ -232,8 +245,16 @@ fn cleanup_legacy_fish_conf_d(configured: &[ConfigureResult], cmd: &str) -> Vec<
/// (`config_paths`), so — as with the fish `conf.d` cleanup — the path settles
/// ownership and the file is removed whole, unread.
///
+/// With `dry_run`, the same detection runs but nothing is removed — the returned
+/// paths are what a real run *would* delete, so a preview and the confirmation
+/// prompt can name them before the user consents (issue #3644).
+///
/// Returns the paths removed, each paired with `Shell::Nushell`.
-fn cleanup_stranded_nushell(configured: &[ConfigureResult], cmd: &str) -> Vec<(Shell, PathBuf)> {
+fn cleanup_stranded_nushell(
+ configured: &[ConfigureResult],
+ cmd: &str,
+ dry_run: bool,
+) -> Vec<(Shell, PathBuf)> {
let mut cleaned = Vec::new();
// Only act if nushell was part of this install.
@@ -251,6 +272,10 @@ fn cleanup_stranded_nushell(configured: &[ConfigureResult], cmd: &str) -> Vec<(S
if &path == canonical || !path.exists() {
continue;
}
+ if dry_run {
+ cleaned.push((Shell::Nushell, path));
+ continue;
+ }
match fs::remove_file(&path) {
Ok(()) => cleaned.push((Shell::Nushell, path)),
Err(e) => {
@@ -269,6 +294,22 @@ fn cleanup_stranded_nushell(configured: &[ConfigureResult], cmd: &str) -> Vec<(S
cleaned
}
+/// Both legacy-location cleanups for one install, as one list.
+///
+/// With `dry_run`, detects the files a real install would remove without
+/// removing them, so a `--dry-run` preview and the install confirmation can name
+/// the deletions before they happen (issue #3644). With `dry_run` false, removes
+/// them and returns what was removed.
+fn collect_legacy_cleanups(
+ configured: &[ConfigureResult],
+ cmd: &str,
+ dry_run: bool,
+) -> Vec<(Shell, PathBuf)> {
+ let mut cleanups = cleanup_legacy_fish_conf_d(configured, cmd, dry_run);
+ cleanups.extend(cleanup_stranded_nushell(configured, cmd, dry_run));
+ cleanups
+}
+
pub fn handle_configure_shell(
shell_filter: Option<Shell>,
skip_confirmation: bool,
@@ -304,9 +345,20 @@ pub fn handle_configure_shell(
.iter()
.any(|r| !matches!(r.action, ConfigAction::AlreadyExists));
+ // Detect (without removing) the legacy files a real install would delete, so
+ // both the --dry-run preview and the confirmation prompt can name them before
+ // the user consents — the removal is destructive and used to happen unpreviewed
+ // (issue #3644).
+ let legacy_preview = collect_legacy_cleanups(&preview.configured, &cmd, true);
+
// For --dry-run, show preview and return without modifying anything
if dry_run {
- let preview_text = show_install_preview(&preview.configured, &completion_preview, &cmd);
+ let preview_text = show_install_preview(
+ &preview.configured,
+ &completion_preview,
+ &legacy_preview,
+ &cmd,
+ );
if !preview_text.is_empty() {
println!("{preview_text}");
}
@@ -315,15 +367,38 @@ pub fn handle_configure_shell(
completion_results: completion_preview,
skipped: preview.skipped,
zsh_needs_compinit: false,
- legacy_cleanups: Vec::new(),
+ legacy_cleanups: legacy_preview,
});
}
- // If nothing needs to be changed, still clean up legacy fish conf.d files
- // A user might have upgraded and have both functions/wt.fish and conf.d/wt.fish
+ // If nothing needs to be changed, there may still be legacy files to clean up
+ // (a user who upgraded and has both functions/wt.fish and conf.d/wt.fish). That
+ // removal is destructive, so gate it behind the same confirmation as an install
+ // — never delete a hand-written file as a silent side effect (issue #3644).
if !needs_shell_changes && !needs_completion_changes {
- let mut legacy_cleanups = cleanup_legacy_fish_conf_d(&preview.configured, &cmd);
- legacy_cleanups.extend(cleanup_stranded_nushell(&preview.configured, &cmd));
+ if legacy_preview.is_empty() {
+ return Ok(ScanResult {
+ configured: preview.configured,
+ completion_results: completion_preview,
+ skipped: preview.skipped,
+ zsh_needs_compinit: false,
+ legacy_cleanups: Vec::new(),
+ });
+ }
+
+ if !skip_confirmation
+ && !prompt_for_install(
+ &preview.configured,
+ &completion_preview,
+ &legacy_preview,
+ &cmd,
+ "Remove deprecated shell integration files?",
+ )?
+ {
+ return Err("Cancelled by user".to_string());
+ }
+
+ let legacy_cleanups = collect_legacy_cleanups(&preview.configured, &cmd, false);
return Ok(ScanResult {
configured: preview.configured,
completion_results: completion_preview,
@@ -338,6 +413,7 @@ pub fn handle_configure_shell(
&& !prompt_for_install(
&preview.configured,
&completion_preview,
+ &legacy_preview,
&cmd,
"Install shell integration?",
)?
@@ -382,9 +458,9 @@ pub fn handle_configure_shell(
// Clean up legacy fish conf.d file if we just installed to functions/
// (issue #566), plus any nushell wrapper stranded at a legacy autoload
- // location (issue #2878).
- let mut legacy_cleanups = cleanup_legacy_fish_conf_d(&result.configured, &cmd);
- legacy_cleanups.extend(cleanup_stranded_nushell(&result.configured, &cmd));
+ // location (issue #2878). The confirmation above listed these removals
+ // (issue #3644).
+ let legacy_cleanups = collect_legacy_cleanups(&result.configured, &cmd, false);
Ok(ScanResult {
configured: result.configured,
@@ -766,18 +842,26 @@ fn configure_wrapper_file(
}))
}
-/// Format what will be installed (shell extensions and completions).
+/// Format what will be installed (shell extensions and completions) and what
+/// legacy files will be removed to make way for them.
///
/// Returns the preview as a string (no trailing newline); the caller picks the
/// sink. `--dry-run` is the command's answer, so it prints to stdout; the
/// interactive `?` re-preview during the install prompt is mid-prompt narration,
/// so it prints to stderr. See /writing-user-outputs.
///
+/// `legacy_cleanups` are the deprecated wrapper files a real install would
+/// delete (fish `conf.d`, stranded nushell autoload). Listing them here is what
+/// makes the removal consented rather than a silent side effect (issue #3644);
+/// the message mirrors the after-the-fact "Removed … (deprecated; now using …)"
+/// line, in the future tense.
+///
/// Note: I/O errors are intentionally ignored - preview is best-effort
/// and shouldn't block the prompt flow.
pub fn show_install_preview(
results: &[ConfigureResult],
completion_results: &[CompletionResult],
+ legacy_cleanups: &[(Shell, PathBuf)],
cmd: &str,
) -> String {
let bold = Style::new().bold();
@@ -837,6 +921,21 @@ pub fn show_install_preview(
));
}
+ // Show legacy files that will be removed. The canonical replacement is the
+ // path this shell is being configured at (found in `results`), matching the
+ // "now using <new>" the after-the-fact removal message shows.
+ for (shell, legacy_path) in legacy_cleanups {
+ let old_path = format_path_for_display(legacy_path);
+ let new_path = results
+ .iter()
+ .find(|r| r.shell == *shell)
+ .map(|r| format_path_for_display(&r.path))
+ .unwrap_or_default();
+ blocks.push(format!(
+ "{INFO_SYMBOL} Will remove {bold}{old_path}{bold:#} (deprecated; now using {bold}{new_path}{bold:#})",
+ ));
+ }
+
blocks.join("\n\n")
}
@@ -909,6 +1008,7 @@ pub(crate) fn format_matched_lines(matched_lines: &[String]) -> String {
pub fn prompt_for_install(
results: &[ConfigureResult],
completion_results: &[CompletionResult],
+ legacy_cleanups: &[(Shell, PathBuf)],
cmd: &str,
prompt_text: &str,
) -> Result<bool, String> {
@@ -917,7 +1017,7 @@ pub fn prompt_for_install(
// blank separates it from the re-prompt). See /writing-user-outputs.
eprintln!(
"{}\n",
- show_install_preview(results, completion_results, cmd)
+ show_install_preview(results, completion_results, legacy_cleanups, cmd)
);
})
.map_err(|e| e.to_string())?;
diff --git a/src/output/shell_integration.rs b/src/output/shell_integration.rs
index 7ae7405b3..50e2c5a5b 100644
--- a/src/output/shell_integration.rs
+++ b/src/output/shell_integration.rs
@@ -468,9 +468,13 @@ pub fn prompt_shell_integration(
// TTY + first time: Show interactive prompt
// Accepting installs for all shells with config files (same as `wt config shell install`)
+ // This first-run offer installs but resolves no legacy cleanups of its own;
+ // the subsequent handle_configure_shell reports any deprecated-file removal
+ // after the fact, as before.
let confirmed = prompt_for_install(
&scan.configured,
&scan.completion_results,
+ &[],
binary_name,
"Install shell integration?",
)
diff --git a/tests/integration_tests/configure_shell.rs b/tests/integration_tests/configure_shell.rs
index abf18f47c..449359331 100644
--- a/tests/integration_tests/configure_shell.rs
+++ b/tests/integration_tests/configure_shell.rs
@@ -711,6 +711,158 @@ fn test_configure_shell_fish_dry_run_does_not_delete_legacy(repo: TestRepo, temp
);
}
+/// `--dry-run` must *preview* the legacy files it would remove (issue #3644).
+///
+/// The cleanup takes back the legacy fish `conf.d/{cmd}.fish`; a preview run has
+/// to name that removal, not just the files it would add. Regression guard for
+/// the gap where `--dry-run` returned an empty `legacy_cleanups`, so the deletion
+/// never appeared before it happened.
+#[rstest]
+fn test_configure_shell_fish_dry_run_previews_legacy_removal(repo: TestRepo, temp_home: TempDir) {
+ // Bootstrap the canonical location with an actual install so functions/ and
+ // completions/ hold the exact content install writes (i.e. "already
+ // configured"), leaving only the legacy file as a pending change.
+ let mut bootstrap = wt_command();
+ repo.configure_wt_cmd(&mut bootstrap);
+ set_temp_home_env(&mut bootstrap, temp_home.path());
+ bootstrap.env("SHELL", "/bin/fish");
+ bootstrap
+ .args(["config", "shell", "install", "fish", "--yes"])
+ .current_dir(repo.root_path());
+ assert!(bootstrap.output().unwrap().status.success());
+
+ // A stale legacy conf.d file the cleanup would take back.
+ let conf_d = temp_home.path().join(".config/fish/conf.d");
+ fs::create_dir_all(&conf_d).unwrap();
+ let legacy_file = conf_d.join("wt.fish");
+ fs::write(&legacy_file, "wt config shell init fish | source").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/fish");
+ cmd.args(["config", "shell", "install", "fish", "--dry-run"])
+ .current_dir(repo.root_path());
+ let output = cmd.output().unwrap();
+ assert!(output.status.success(), "dry-run failed: {output:?}");
+
+ // The preview (stdout) must name the legacy removal.
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ assert!(
+ stdout.contains("deprecated") && stdout.contains("conf.d"),
+ "--dry-run should preview the legacy conf.d removal:\n{stdout}"
+ );
+
+ // ...and must not actually remove anything.
+ assert!(
+ legacy_file.exists(),
+ "--dry-run must not delete legacy conf.d/wt.fish: {legacy_file:?}"
+ );
+}
+
+/// When everything is already configured, removing the legacy file needs the
+/// user's consent — declining the prompt preserves it (issue #3644).
+///
+/// The already-configured branch used to run the cleanup and return without
+/// prompting at all, deleting a hand-written `conf.d/wt.fish` as a silent side
+/// effect. Now it prompts; declining must leave the file in place.
+#[rstest]
+fn test_configure_shell_fish_legacy_removal_declined_when_already_configured(
+ repo: TestRepo,
+ temp_home: TempDir,
+) {
+ // Bootstrap the canonical location so a second install is a pure no-op except
+ // for the legacy cleanup.
+ let mut bootstrap = wt_command();
+ repo.configure_wt_cmd(&mut bootstrap);
+ set_temp_home_env(&mut bootstrap, temp_home.path());
+ bootstrap.env("SHELL", "/bin/fish");
+ bootstrap
+ .args(["config", "shell", "install", "fish", "--yes"])
+ .current_dir(repo.root_path());
+ assert!(bootstrap.output().unwrap().status.success());
+
+ let conf_d = temp_home.path().join(".config/fish/conf.d");
+ fs::create_dir_all(&conf_d).unwrap();
+ let legacy_file = conf_d.join("wt.fish");
+ fs::write(&legacy_file, "wt config shell init fish | source").unwrap();
+
+ // Run without --yes and decline the prompt.
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.env("SHELL", "/bin/fish");
+ cmd.args(["config", "shell", "install", "fish"])
+ .current_dir(repo.root_path())
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped());
+ let mut child = cmd.spawn().unwrap();
+ use std::io::Write as _;
+ child.stdin.take().unwrap().write_all(b"n\n").unwrap();
+ let output = child.wait_with_output().unwrap();
+
+ // Declining is a non-zero exit ("Cancelled by user"), and the file survives.
+ assert!(
+ !output.status.success(),
+ "declining should exit non-zero: {output:?}"
+ );
+ assert!(
+ legacy_file.exists(),
+ "declining must preserve legacy conf.d/wt.fish: {legacy_file:?}"
+ );
+}
+
+/// Accepting the prompt in the already-configured branch removes the legacy file
+/// (issue #3644).
+///
+/// The complement of the decline test: confirming the `Remove deprecated shell
+/// integration files?` prompt proceeds with the cleanup that used to run
+/// unprompted.
+#[rstest]
+fn test_configure_shell_fish_legacy_removal_accepted_when_already_configured(
+ repo: TestRepo,
+ temp_home: TempDir,
+) {
+ let mut bootstrap = wt_command();
+ repo.configure_wt_cmd(&mut bootstrap);
+ set_temp_home_env(&mut bootstrap, temp_home.path());
+ bootstrap.env("SHELL", "/bin/fish");
+ bootstrap
+ .args(["config", "shell", "install", "fish", "--yes"])
+ .current_dir(repo.root_path());
+ assert!(bootstrap.output().unwrap().status.success());
+
+ let conf_d = temp_home.path().join(".config/fish/conf.d");
+ fs::create_dir_all(&conf_d).unwrap();
+ let legacy_file = conf_d.join("wt.fish");
+ fs::write(&legacy_file, "wt config shell init fish | source").unwrap();
+
+ // Run without --yes and accept the prompt.
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.env("SHELL", "/bin/fish");
+ cmd.args(["config", "shell", "install", "fish"])
+ .current_dir(repo.root_path())
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .stderr(std::process::Stdio::piped());
+ let mut child = cmd.spawn().unwrap();
+ use std::io::Write as _;
+ child.stdin.take().unwrap().write_all(b"y\n").unwrap();
+ let output = child.wait_with_output().unwrap();
+
+ assert!(
+ output.status.success(),
+ "accepting should succeed: {output:?}"
+ );
+ assert!(
+ !legacy_file.exists(),
+ "accepting must remove legacy conf.d/wt.fish: {legacy_file:?}"
+ );
+}
+
/// Test that detection finds fish integration in legacy conf.d location
///
/// `wt config show` should detect shell integration whether it's in the
diff --git a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish_dry_run_does_not_delete_legacy.snap b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish_dry_run_does_not_delete_legacy.snap
index 89c15ec3d..09d8ccde0 100644
--- a/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish_dry_run_does_not_delete_legacy.snap
+++ b/tests/snapshots/integration__integration_tests__configure_shell__configure_shell_fish_dry_run_does_not_delete_legacy.snap
@@ -10,8 +10,10 @@ info:
- "--dry-run"
env:
APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
CLICOLOR_FORCE: "1"
COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
@@ -39,6 +41,7 @@ info:
WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
@@ -52,4 +55,6 @@ exit_code: 0
  # worktrunk completions for fish
  complete --keep-order --exclusive --command wt --arguments "(test -n /"/$WORKTRUNK_BIN/"; or set -l WORKTRUNK_BIN (type -P wt 2>/dev/null); and COMPLETE=fish /$WORKTRUNK_BIN -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"
+○ Will remove ~/.config/fish/conf.d/wt.fish (deprecated; now using ~/.config/fish/functions/wt.fish)
+
----- stderr -----