use once_cell::sync::Lazy;
use std::{
collections::HashMap,
path::{Path, PathBuf},
sync::Mutex,
};
static TEMPS: Lazy<Mutex<HashMap<PathBuf, TempKind>>> = Lazy::new(<_>::default);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TempKind {
NotKeepable,
Keepable,
}
pub fn add(file: impl Into<PathBuf>, kind: TempKind) {
TEMPS.lock().unwrap().insert(file.into(), kind);
}
pub fn unadd(file: &Path) -> bool {
TEMPS.lock().unwrap().remove(file).is_some()
}
pub async fn clean(keep_keepables: bool) {
match keep_keepables {
true => clean_non_keepables().await,
false => clean_all().await,
}
}
pub async fn clean_all() {
let files = std::mem::take(&mut *TEMPS.lock().unwrap());
for (file, _) in files {
let _ = tokio::fs::remove_file(file).await;
}
}
async fn clean_non_keepables() {
let matching: Vec<_> = TEMPS
.lock()
.unwrap()
.iter()
.filter(|(_, k)| **k == TempKind::NotKeepable)
.map(|(f, _)| f.clone())
.collect();
for file in matching {
let _ = tokio::fs::remove_file(&file).await;
TEMPS.lock().unwrap().remove(&file);
}
}