use std::{
ops::Deref,
path::{Path, PathBuf},
};
use crate::{error::OxenError, model::LocalRepository, test::maybe_cleanup_repo};
#[derive(Debug)]
pub struct RepoDirGuard {
repo_dir: PathBuf,
}
impl RepoDirGuard {
pub fn new(repo_dir: PathBuf) -> Self {
Self { repo_dir }
}
}
impl Drop for RepoDirGuard {
fn drop(&mut self) {
if let Err(e) = maybe_cleanup_repo(&self.repo_dir) {
log::warn!("RepoDirGuard cleanup failed for {:?}: {e}", self.repo_dir);
}
}
}
impl Deref for RepoDirGuard {
type Target = Path;
fn deref(&self) -> &Self::Target {
&self.repo_dir
}
}
#[derive(Debug)]
pub struct TestLocalRepo {
repo: LocalRepository,
_guard: RepoDirGuard,
}
impl TestLocalRepo {
pub fn new<R>(make_repo: R) -> Result<Self, OxenError>
where
R: FnOnce() -> Result<LocalRepository, OxenError>,
{
let repo = make_repo()?;
let repo_dir = repo.path.clone();
Ok(Self {
repo,
_guard: RepoDirGuard::new(repo_dir),
})
}
pub fn drop_local_repo(self) -> RepoDirGuard {
let TestLocalRepo { repo, _guard } = self;
drop(repo);
_guard
}
}
impl Deref for TestLocalRepo {
type Target = LocalRepository;
fn deref(&self) -> &Self::Target {
&self.repo
}
}
impl TryFrom<RepoDirGuard> for TestLocalRepo {
type Error = OxenError;
fn try_from(repo_dir: RepoDirGuard) -> Result<Self, Self::Error> {
let repo = LocalRepository::from_dir(&repo_dir as &Path)?;
Ok(TestLocalRepo {
repo,
_guard: repo_dir,
})
}
}