diff --git a/.changeset/clean-multishell-on-exit.md b/.changeset/clean-multishell-on-exit.md new file mode 100644 index 000000000..ace26b76b --- /dev/null +++ b/.changeset/clean-multishell-on-exit.md @@ -0,0 +1,8 @@ +--- +"fnm": minor +--- + +Automatically clean up multishell directories when the shell session exits + +Registers an exit hook/trap in the shell profile evaluation (`fnm env`) that removes the session's multishell symlink directory when the terminal tab or shell session exits. +Supported across Bash (`trap EXIT`), Zsh (`add-zsh-hook zshexit`), Fish (`--on-event fish_exit`), and PowerShell (`Register-EngineEvent PowerShell.Exiting`). diff --git a/.ci/install.sh b/.ci/install.sh index 9a9647748..480a9c51b 100755 --- a/.ci/install.sh +++ b/.ci/install.sh @@ -168,6 +168,10 @@ setup_shell() { if [ "$CURRENT_SHELL" = "zsh" ]; then CONF_FILE=${ZDOTDIR:-$HOME}/.zshrc ensure_containing_dir_exists "$CONF_FILE" + if [ -f "$CONF_FILE" ] && grep -q "fnm env" "$CONF_FILE" 2>/dev/null; then + echo "fnm is already configured in $CONF_FILE" + return + fi echo "Installing for Zsh. Appending the following to $CONF_FILE:" { echo '' @@ -184,6 +188,10 @@ setup_shell() { elif [ "$CURRENT_SHELL" = "fish" ]; then CONF_FILE=$HOME/.config/fish/conf.d/fnm.fish ensure_containing_dir_exists "$CONF_FILE" + if [ -f "$CONF_FILE" ] && grep -q "fnm env" "$CONF_FILE" 2>/dev/null; then + echo "fnm is already configured in $CONF_FILE" + return + fi echo "Installing for Fish. Appending the following to $CONF_FILE:" { echo '' @@ -204,6 +212,10 @@ setup_shell() { CONF_FILE=$HOME/.bashrc fi ensure_containing_dir_exists "$CONF_FILE" + if [ -f "$CONF_FILE" ] && grep -q "fnm env" "$CONF_FILE" 2>/dev/null; then + echo "fnm is already configured in $CONF_FILE" + return + fi echo "Installing for Bash. Appending the following to $CONF_FILE:" { echo '' diff --git a/e2e/__snapshots__/multishell-cleanup.test.ts.snap b/e2e/__snapshots__/multishell-cleanup.test.ts.snap new file mode 100644 index 000000000..0563ea088 --- /dev/null +++ b/e2e/__snapshots__/multishell-cleanup.test.ts.snap @@ -0,0 +1,53 @@ +// Jest Snapshot v1, https://goo.gl/fbAQLP + +exports[`Bash multishell is cleaned up after subshell exits: Bash 1`] = ` +"set -e +eval "$(fnm env)" +fnm install v11.9.0 +fnm use v11.9.0 +echo 'set -e +eval "$(fnm env)" +node record.cjs' | bash +if [ "$(node verify.cjs)" != "CLEANED_UP" ]; then + echo "Expected multishell directory to be cleaned up on exit to be CLEANED_UP. Got $(node verify.cjs)" + exit 1 +fi" +`; + +exports[`Fish multishell is cleaned up after subshell exits: Fish 1`] = ` +"fnm env | source +fnm install v11.9.0 +fnm use v11.9.0 +fish -c 'fnm env | source +node record.cjs' +set ____test____ (node verify.cjs) +if test "$____test____" != "CLEANED_UP" + echo "Expected multishell directory to be cleaned up on exit to be CLEANED_UP. Got $____test____" + exit 1 +end" +`; + +exports[`PowerShell multishell is cleaned up after subshell exits: PowerShell 1`] = ` +"$ErrorActionPreference = "Stop" +fnm env | Out-String | Invoke-Expression +fnm install v11.9.0 +fnm use v11.9.0 +echo '$ErrorActionPreference = "Stop" +fnm env | Out-String | Invoke-Expression +node record.cjs' | pwsh -NoProfile +if ( "$(node verify.cjs)" -ne "CLEANED_UP" ) { echo "Expected multishell directory to be cleaned up on exit to be CLEANED_UP. Got $(node verify.cjs)"; exit 1 }" +`; + +exports[`Zsh multishell is cleaned up after subshell exits: Zsh 1`] = ` +"set -e +eval "$(fnm env)" +fnm install v11.9.0 +fnm use v11.9.0 +echo 'set -e +eval "$(fnm env)" +node record.cjs' | zsh +if [ "$(node verify.cjs)" != "CLEANED_UP" ]; then + echo "Expected multishell directory to be cleaned up on exit to be CLEANED_UP. Got $(node verify.cjs)" + exit 1 +fi" +`; diff --git a/e2e/multishell-cleanup.test.ts b/e2e/multishell-cleanup.test.ts new file mode 100644 index 000000000..8a84a04b8 --- /dev/null +++ b/e2e/multishell-cleanup.test.ts @@ -0,0 +1,47 @@ +import { script } from "./shellcode/script.js" +import { Bash, Fish, PowerShell, Zsh } from "./shellcode/shells.js" +import testCwd from "./shellcode/test-cwd.js" +import fs from "node:fs/promises" +import path from "node:path" +import describe from "./describe.js" + +for (const shell of [Bash, Zsh, Fish, PowerShell]) { + describe(shell, () => { + test("multishell is cleaned up after subshell exits", async () => { + await fs.writeFile( + path.join(testCwd(), "record.cjs"), + `const fs = require('fs'); fs.writeFileSync('subshell-multishell.txt', process.env.FNM_MULTISHELL_PATH || '');` + ) + await fs.writeFile( + path.join(testCwd(), "verify.cjs"), + `const fs = require('fs'); +const msPath = fs.readFileSync('subshell-multishell.txt', 'utf8').trim(); +if (!msPath) { console.log('NO_PATH'); process.exit(1); } +if (fs.existsSync(msPath)) { console.log('STILL_EXISTS'); process.exit(1); } +console.log('CLEANED_UP');` + ) + + await script(shell) + .then(shell.env({})) + .then(shell.call("fnm", ["install", "v11.9.0"])) + .then(shell.call("fnm", ["use", "v11.9.0"])) + .then( + shell.inSubShell( + script(shell) + .then(shell.env({})) + .then(shell.call("node", ["record.cjs"])) + .asLine() + ) + ) + .then( + shell.hasCommandOutput( + shell.call("node", ["verify.cjs"]), + "CLEANED_UP", + "multishell directory to be cleaned up on exit" + ) + ) + .takeSnapshot(shell) + .execute(shell) + }) + }) +} diff --git a/src/commands/env.rs b/src/commands/env.rs index 55d8e5bf2..59917f8ed 100644 --- a/src/commands/env.rs +++ b/src/commands/env.rs @@ -166,6 +166,9 @@ impl Command for Env { if let Some(v) = shell.rehash() { println!("{v}"); } + if let Some(cleanup) = shell.cleanup_on_exit(&multishell_path) { + println!("{cleanup}"); + } Ok(()) } diff --git a/src/shell/bash.rs b/src/shell/bash.rs index 667c96b8b..6c67dcb39 100644 --- a/src/shell/bash.rs +++ b/src/shell/bash.rs @@ -58,4 +58,44 @@ impl Shell for Bash { autoload_hook = autoload_hook )) } + + fn cleanup_on_exit(&self, multishell_path: &Path) -> Option { + let path = multishell_path.to_str()?; + let path = + super::windows_compat::maybe_fix_windows_path(path).unwrap_or_else(|| path.to_string()); + Some(formatdoc!( + r#" + if [ -z "${{__fnm_cleanup_multishell_paths+x}}" ]; then + __fnm_cleanup_multishell_paths=() + __fnm_cleanup() {{ + for p in "${{__fnm_cleanup_multishell_paths[@]}}"; do + \rm -rf "$p" + done + }} + trap __fnm_cleanup EXIT HUP INT TERM + else + for p in "${{__fnm_cleanup_multishell_paths[@]}}"; do + \rm -rf "$p" + done + __fnm_cleanup_multishell_paths=() + fi + __fnm_cleanup_multishell_paths+=({path:?}) + "#, + path = path + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cleanup_on_exit_registers_trap() { + let output = Bash + .cleanup_on_exit(Path::new("/tmp/fnm_multishells/123_456")) + .unwrap(); + assert!(output.contains("trap __fnm_cleanup EXIT")); + assert!(output.contains("/tmp/fnm_multishells/123_456")); + } } diff --git a/src/shell/fish.rs b/src/shell/fish.rs index 90078aab2..51c0461de 100644 --- a/src/shell/fish.rs +++ b/src/shell/fish.rs @@ -52,4 +52,42 @@ impl Shell for Fish { autoload_hook = autoload_hook )) } + + fn cleanup_on_exit(&self, multishell_path: &Path) -> Option { + let path = multishell_path.to_str()?; + let path = + super::windows_compat::maybe_fix_windows_path(path).unwrap_or_else(|| path.to_string()); + Some(formatdoc!( + r" + if not set -q __fnm_cleanup_multishell_paths + function __fnm_cleanup --on-event fish_exit + for p in $__fnm_cleanup_multishell_paths + rm -rf $p + end + end + else + for p in $__fnm_cleanup_multishell_paths + rm -rf $p + end + set -e __fnm_cleanup_multishell_paths + end + set -g -a __fnm_cleanup_multishell_paths {path:?} + ", + path = path + )) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cleanup_on_exit_registers_fish_exit_event() { + let output = Fish + .cleanup_on_exit(Path::new("/tmp/fnm_multishells/123_456")) + .unwrap(); + assert!(output.contains("function __fnm_cleanup --on-event fish_exit")); + assert!(output.contains("/tmp/fnm_multishells/123_456")); + } } diff --git a/src/shell/powershell.rs b/src/shell/powershell.rs index e45621bb7..946c7bae8 100644 --- a/src/shell/powershell.rs +++ b/src/shell/powershell.rs @@ -50,7 +50,47 @@ impl Shell for PowerShell { autoload_hook = autoload_hook )) } + + fn cleanup_on_exit(&self, multishell_path: &Path) -> Option { + let path = multishell_path.to_str()?.replace('\'', "''"); + Some(formatdoc!( + r" + if (-not (Test-Path 'variable:global:__fnm_cleanup_multishell_paths')) {{ + $global:__fnm_cleanup_multishell_paths = [System.Collections.Generic.List[string]]::new() + Register-EngineEvent -SourceIdentifier PowerShell.Exiting -Action {{ + foreach ($p in $global:__fnm_cleanup_multishell_paths) {{ + Remove-Item -Path $p -Recurse -Force -ErrorAction SilentlyContinue + }} + }} -SupportEvent -ErrorAction SilentlyContinue | Out-Null + }} else {{ + foreach ($p in $global:__fnm_cleanup_multishell_paths) {{ + Remove-Item -Path $p -Recurse -Force -ErrorAction SilentlyContinue + }} + $global:__fnm_cleanup_multishell_paths.Clear() + }} + [void]$global:__fnm_cleanup_multishell_paths.Add('{path}') + ", + path = path + )) + } + fn to_clap_shell(&self) -> clap_complete::Shell { clap_complete::Shell::PowerShell } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cleanup_on_exit_registers_engine_event() { + let output = PowerShell + .cleanup_on_exit(Path::new( + r"C:\Users\user\AppData\Local\fnm_multishells\123_456", + )) + .unwrap(); + assert!(output.contains("Register-EngineEvent -SourceIdentifier PowerShell.Exiting")); + assert!(output.contains(r"C:\Users\user\AppData\Local\fnm_multishells\123_456")); + } +} diff --git a/src/shell/shell.rs b/src/shell/shell.rs index 481b5e04d..df9ff383d 100644 --- a/src/shell/shell.rs +++ b/src/shell/shell.rs @@ -10,6 +10,12 @@ pub trait Shell: Debug { fn rehash(&self) -> Option<&'static str> { None } + /// Returns shell-specific code to clean up the multishell directory when the + /// shell session exits. Returns `None` if the shell has no exit trap mechanism. + fn cleanup_on_exit(&self, multishell_path: &Path) -> Option { + let _ = multishell_path; + None + } fn to_clap_shell(&self) -> clap_complete::Shell; } diff --git a/src/shell/zsh.rs b/src/shell/zsh.rs index 401ca2eb8..8469f08cc 100644 --- a/src/shell/zsh.rs +++ b/src/shell/zsh.rs @@ -59,6 +59,34 @@ impl Shell for Zsh { autoload_hook = autoload_hook )) } + + fn cleanup_on_exit(&self, multishell_path: &Path) -> Option { + let path = multishell_path.to_str()?; + let path = + super::windows_compat::maybe_fix_windows_path(path).unwrap_or_else(|| path.to_string()); + Some(formatdoc!( + r#" + if (( ! $+__fnm_cleanup_multishell_paths )); then + typeset -ga __fnm_cleanup_multishell_paths + autoload -U add-zsh-hook + _fnm_cleanup() {{ + for p in "${{__fnm_cleanup_multishell_paths[@]}}"; do + \rm -rf "$p" + done + }} + add-zsh-hook zshexit _fnm_cleanup + trap _fnm_cleanup HUP INT TERM + else + for p in "${{__fnm_cleanup_multishell_paths[@]}}"; do + \rm -rf "$p" + done + __fnm_cleanup_multishell_paths=() + fi + __fnm_cleanup_multishell_paths+=({path:?}) + "#, + path = path + )) + } } #[cfg(test)] @@ -70,4 +98,13 @@ mod tests { let output = Zsh.use_on_cd(&crate::config::FnmConfig::default()).unwrap(); assert!(output.contains("add-zsh-hook -D chpwd _fnm_autoload_hook")); } + + #[test] + fn cleanup_on_exit_registers_zshexit_hook() { + let output = Zsh + .cleanup_on_exit(Path::new("/tmp/fnm_multishells/123_456")) + .unwrap(); + assert!(output.contains("add-zsh-hook zshexit _fnm_cleanup")); + assert!(output.contains("/tmp/fnm_multishells/123_456")); + } }