use std::fs;
use std::path::PathBuf;
use std::time;
use std::sync::atomic::{AtomicUsize, Ordering};
static WORKSPACE_COUNTER: AtomicUsize = AtomicUsize::new(0);
pub struct TempWorkspace {
root: PathBuf,
}
impl TempWorkspace {
pub fn new(test_name: &str) -> Self {
let unique = time::SystemTime::now()
.duration_since(time::UNIX_EPOCH)
.unwrap()
.as_nanos();
let count = WORKSPACE_COUNTER.fetch_add(1, Ordering::SeqCst);
let cwd = std::env::current_dir().unwrap();
let root = cwd.join("target").join(format!(
"test-{}-{}-{}-{}",
test_name,
std::process::id(),
unique,
count
));
fs::create_dir_all(&root).unwrap();
Self { root }
}
pub fn create_dir(&self, rel_path: &str) -> PathBuf {
let path = self.root.join(rel_path);
fs::create_dir_all(&path).unwrap();
path
}
pub fn create_file(&self, rel_path: &str, contents: &str) -> PathBuf {
let path = self.root.join(rel_path);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(&path, contents).unwrap();
path
}
}
impl Drop for TempWorkspace {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.root);
}
}