use std::collections::HashMap;
use std::path::{Path, PathBuf};
pub fn dir() -> PathBuf {
let env: HashMap<String, String> = std::env::vars().collect();
resolve(&env)
}
pub fn resolve(env: &HashMap<String, String>) -> PathBuf {
if let Some(dir) = env.get("RIGHTSIZE_CACHE_DIR") {
return PathBuf::from(dir);
}
default_dir(env)
}
pub fn default_dir(env: &HashMap<String, String>) -> PathBuf {
if std::env::consts::OS == "windows" {
let local_app_data = env.get("LOCALAPPDATA").cloned().unwrap_or_else(|| {
let user_profile = env
.get("USERPROFILE")
.cloned()
.unwrap_or_else(|| ".".to_string());
Path::new(&user_profile)
.join("AppData")
.join("Local")
.to_string_lossy()
.to_string()
});
return Path::new(&local_app_data).join("rightsize");
}
let home = env.get("HOME").cloned().unwrap_or_else(|| ".".to_string());
Path::new(&home).join(".cache").join("rightsize")
}
pub(crate) fn unique_tmp_suffix() -> String {
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{SystemTime, UNIX_EPOCH};
static SEQ: AtomicU64 = AtomicU64::new(0);
let seq = SEQ.fetch_add(1, Ordering::SeqCst);
let nanos = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_nanos())
.unwrap_or(0);
format!("{}-{seq}-{nanos}", std::process::id())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn resolve_prefers_the_cache_dir_override() {
let mut env = HashMap::new();
env.insert("RIGHTSIZE_CACHE_DIR".to_string(), "/tmp/custom".to_string());
env.insert("HOME".to_string(), "/home/testuser".to_string());
assert_eq!(resolve(&env), PathBuf::from("/tmp/custom"));
}
#[test]
fn resolve_falls_back_to_default_dir_when_unset() {
let mut env = HashMap::new();
env.insert("HOME".to_string(), "/home/testuser".to_string());
if std::env::consts::OS != "windows" {
assert_eq!(
resolve(&env),
PathBuf::from("/home/testuser/.cache/rightsize")
);
}
}
#[test]
fn default_dir_on_this_runners_platform_uses_the_expected_root() {
let mut env = HashMap::new();
env.insert("HOME".to_string(), "/home/testuser".to_string());
if std::env::consts::OS != "windows" {
assert_eq!(
default_dir(&env),
PathBuf::from("/home/testuser/.cache/rightsize")
);
}
}
}