use std::{
collections::BTreeSet,
fs::File,
io,
path::{Path, PathBuf},
sync::Mutex,
time::{Duration, SystemTime},
};
use crate::platform::{self, EntryName, FileKind};
const PREFIX: &str = "fingerprint-";
const LOCK: &str = ".lock";
const UNLOCKED_AGE: Duration = Duration::from_secs(24 * 60 * 60);
pub(super) struct Scratch {
directory: Option<platform::PrivateTempDir>,
lock: PathBuf,
_held: File,
}
impl Scratch {
pub(super) fn create(root: &Path) -> io::Result<Self> {
sweep_once(root);
let (held, lock) = tempfile::Builder::new()
.prefix(PREFIX)
.suffix(LOCK)
.tempfile_in(root)?
.keep()
.map_err(|error| error.error)?;
let directory = (|| {
crate::platform::paths::lock(&held)?;
let name = lock
.file_name()
.and_then(crate::platform::os_text)
.and_then(|name| name.strip_suffix(LOCK))
.expect("the lock was named with its suffix");
platform::private_named_dir(root, name)
})();
match directory {
Ok(directory) => Ok(Self {
directory: Some(directory),
lock,
_held: held,
}),
Err(error) => {
let _ = platform::paths::remove_open_file(&lock);
Err(error)
}
}
}
pub(super) fn path(&self) -> &Path {
self.directory.as_ref().expect("open until closed").path()
}
pub(super) fn close(mut self) -> io::Result<()> {
self.directory.take().expect("closed once").close()
}
}
impl Drop for Scratch {
fn drop(&mut self) {
drop(self.directory.take());
let _ = platform::paths::remove_open_file(&self.lock);
}
}
fn sweep_once(root: &Path) {
static SWEPT: Mutex<BTreeSet<PathBuf>> = Mutex::new(BTreeSet::new());
if SWEPT
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
.insert(root.to_path_buf())
{
let _ = sweep(root, SystemTime::now(), |file| file.metadata()?.modified());
}
}
fn sweep(
root: &Path,
now: SystemTime,
modified_at: impl Fn(&File) -> io::Result<SystemTime>,
) -> io::Result<()> {
let directory = platform::open_directory(root)?;
let mut directories = BTreeSet::new();
let mut locks = BTreeSet::new();
for entry in platform::read_dir(&directory)? {
let entry = entry?;
let Some(name) = entry.file_name().to_str().map(str::to_owned) else {
continue;
};
let Some(rest) = name.strip_prefix(PREFIX) else {
continue;
};
match (rest.strip_suffix(LOCK), entry.file_type()?) {
(Some(_), FileKind::File) => {
locks.insert(name);
}
(None, FileKind::Directory) => {
directories.insert(name);
}
_ => {}
}
}
for lock in &locks {
let path = root.join(lock);
let Ok(file) = platform::open_no_follow(File::options().read(true).write(true), &path)
else {
continue;
};
if crate::platform::paths::try_lock(&file).is_err() {
continue;
}
let owned = lock.strip_suffix(LOCK).expect("a lock's name");
if directories.remove(owned) {
match platform::remove_tree(&root.join(owned)) {
Ok(()) => {}
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
Err(_) => continue,
}
}
let _ = platform::paths::remove_open_file(&path);
}
for name in directories {
if locks.contains(&format!("{name}{LOCK}")) {
continue;
}
let untouched = EntryName::new(name.as_ref())
.ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))
.and_then(|entry| platform::open_entry(&directory, &entry))
.and_then(|opened| modified_at(&opened))
.is_ok_and(|modified| {
now.duration_since(modified)
.is_ok_and(|age| age >= UNLOCKED_AGE)
});
if untouched {
let _ = platform::remove_tree(&root.join(name));
}
}
Ok(())
}
#[cfg(test)]
mod tests;