6b863d2d2d
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
56 lines
1.6 KiB
Rust
56 lines
1.6 KiB
Rust
//! Shared test helpers: unique temporary directories without a dev-dependency.
|
|
#![allow(dead_code)]
|
|
|
|
use std::fs;
|
|
use std::path::{Path, PathBuf};
|
|
use std::sync::atomic::{AtomicU64, Ordering};
|
|
|
|
use notescraft_vault::Vault;
|
|
|
|
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
|
|
|
/// A directory under the system temp dir, removed when dropped.
|
|
pub struct TempDir {
|
|
path: PathBuf,
|
|
}
|
|
|
|
impl TempDir {
|
|
/// Creates a fresh, empty, uniquely named directory.
|
|
pub fn new(tag: &str) -> Self {
|
|
let n = COUNTER.fetch_add(1, Ordering::Relaxed);
|
|
let path = std::env::temp_dir().join(format!("notescraft-vault-{tag}-{}-{n}", std::process::id()));
|
|
let _ = fs::remove_dir_all(&path);
|
|
fs::create_dir_all(&path).expect("temp dir");
|
|
Self { path }
|
|
}
|
|
|
|
/// The directory path.
|
|
pub fn path(&self) -> &Path {
|
|
&self.path
|
|
}
|
|
}
|
|
|
|
impl Drop for TempDir {
|
|
fn drop(&mut self) {
|
|
#[cfg(unix)]
|
|
{
|
|
use std::os::unix::fs::PermissionsExt;
|
|
let _ = fs::set_permissions(&self.path, fs::Permissions::from_mode(0o755));
|
|
}
|
|
let _ = fs::remove_dir_all(&self.path);
|
|
}
|
|
}
|
|
|
|
/// A vault opened read-write in a fresh temp directory. The directory outlives the vault,
|
|
/// which releases its lock on drop.
|
|
pub fn vault(tag: &str) -> (TempDir, Vault) {
|
|
let dir = TempDir::new(tag);
|
|
let vault = Vault::open(dir.path()).expect("open vault");
|
|
(dir, vault)
|
|
}
|
|
|
|
/// Reads a vault-relative file, for assertions.
|
|
pub fn read(vault: &Vault, rel: &str) -> Vec<u8> {
|
|
vault.read(rel).expect("read vault file")
|
|
}
|