From ad0ecd7fff864430e072c0df2fe984ef0875324b Mon Sep 17 00:00:00 2001 From: Gal Schlezinger Date: Sun, 30 Jan 2022 10:24:44 +0200 Subject: [PATCH] Use local cache directory instead of temp directory for symlinks (#638) * Use local cache directory instead of temp directory for symlinks still with no cleanup, probably need to have --cleanup-duration=... for fnm env or another command for cleaning up old symlinks. * Introduce directories, and support XDG_ directories for cache directories * cargo clippy --fix --- src/commands/env.rs | 9 ++++++--- src/directories.rs | 26 ++++++++++++++++++++++++++ src/main.rs | 1 + 3 files changed, 33 insertions(+), 3 deletions(-) create mode 100644 src/directories.rs diff --git a/src/commands/env.rs b/src/commands/env.rs index 6fda72a..f27cff7 100644 --- a/src/commands/env.rs +++ b/src/commands/env.rs @@ -6,6 +6,7 @@ use crate::path_ext::PathExt; use crate::shell::{infer_shell, Shell, AVAILABLE_SHELLS}; use colored::Colorize; use std::fmt::Debug; +use std::path::PathBuf; use thiserror::Error; #[derive(clap::Parser, Debug, Default)] @@ -30,10 +31,12 @@ fn generate_symlink_path() -> String { ) } +fn symlink_base_dir() -> PathBuf { + crate::directories::multishell_storage().ensure_exists_silently() +} + fn make_symlink(config: &FnmConfig) -> std::path::PathBuf { - let base_dir = std::env::temp_dir() - .join("fnm_multishells") - .ensure_exists_silently(); + let base_dir = symlink_base_dir(); let mut temp_dir = base_dir.join(generate_symlink_path()); while temp_dir.exists() { diff --git a/src/directories.rs b/src/directories.rs new file mode 100644 index 0000000..0f7c8c0 --- /dev/null +++ b/src/directories.rs @@ -0,0 +1,26 @@ +use std::path::PathBuf; + +fn xdg_dir(env: &str) -> Option { + let env_var = std::env::var(env).ok()?; + Some(PathBuf::from(env_var)) +} + +fn state_dir() -> Option { + xdg_dir("XDG_STATE_HOME").or_else(dirs::state_dir) +} + +fn cache_dir() -> Option { + xdg_dir("XDG_CACHE_HOME").or_else(dirs::cache_dir) +} + +fn runtime_dir() -> Option { + xdg_dir("XDG_RUNTIME_DIR").or_else(dirs::runtime_dir) +} + +pub fn multishell_storage() -> PathBuf { + runtime_dir() + .or_else(state_dir) + .or_else(cache_dir) + .unwrap_or_else(std::env::temp_dir) + .join("fnm_multishells") +} diff --git a/src/main.rs b/src/main.rs index 587011e..18cc24e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -34,6 +34,7 @@ mod version_files; #[macro_use] mod log_level; mod default_version; +mod directories; fn main() { env_logger::init();