use std::fs;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU32, Ordering};
use blubat_core::Paths;
static NEXT: AtomicU32 = AtomicU32::new(0);
#[derive(Debug)]
pub struct Scratch(PathBuf);
impl Scratch {
pub fn new() -> Self {
let path = std::env::temp_dir().join(format!(
"blubat-tests-{}-{}",
std::process::id(),
NEXT.fetch_add(1, Ordering::SeqCst)
));
let _ = fs::remove_dir_all(&path);
fs::create_dir_all(&path).expect("a scratch directory");
Self(path)
}
pub fn dir(&self) -> &Path {
&self.0
}
pub fn join(&self, name: &str) -> PathBuf {
self.0.join(name)
}
pub fn paths(&self) -> Paths {
Paths::rooted(&self.0)
}
pub fn config_file(&self) -> PathBuf {
self.paths().config_file().to_path_buf()
}
pub fn write_config(&self, contents: &str) -> PathBuf {
let path = self.config_file();
fs::write(&path, contents).expect("a written config");
path
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}