Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/clean-multishell-on-exit.md
Original file line number Diff line number Diff line change
@@ -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`).
12 changes: 12 additions & 0 deletions .ci/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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 ''
Expand All @@ -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 ''
Expand All @@ -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 ''
Expand Down
53 changes: 53 additions & 0 deletions e2e/__snapshots__/multishell-cleanup.test.ts.snap
Original file line number Diff line number Diff line change
@@ -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"
`;
47 changes: 47 additions & 0 deletions e2e/multishell-cleanup.test.ts
Original file line number Diff line number Diff line change
@@ -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)
})
})
}
3 changes: 3 additions & 0 deletions src/commands/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}
Expand Down
40 changes: 40 additions & 0 deletions src/shell/bash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,4 +58,44 @@ impl Shell for Bash {
autoload_hook = autoload_hook
))
}

fn cleanup_on_exit(&self, multishell_path: &Path) -> Option<String> {
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"));
}
}
38 changes: 38 additions & 0 deletions src/shell/fish.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,4 +52,42 @@ impl Shell for Fish {
autoload_hook = autoload_hook
))
}

fn cleanup_on_exit(&self, multishell_path: &Path) -> Option<String> {
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"));
}
}
40 changes: 40 additions & 0 deletions src/shell/powershell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,47 @@ impl Shell for PowerShell {
autoload_hook = autoload_hook
))
}

fn cleanup_on_exit(&self, multishell_path: &Path) -> Option<String> {
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"));
}
}
6 changes: 6 additions & 0 deletions src/shell/shell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> {
let _ = multishell_path;
None
}
fn to_clap_shell(&self) -> clap_complete::Shell;
}

Expand Down
37 changes: 37 additions & 0 deletions src/shell/zsh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,34 @@ impl Shell for Zsh {
autoload_hook = autoload_hook
))
}

fn cleanup_on_exit(&self, multishell_path: &Path) -> Option<String> {
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)]
Expand All @@ -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"));
}
}