use std::path::PathBuf;
use std::sync::{Mutex, MutexGuard};
static CWD_MUTEX: Mutex<()> = Mutex::new(());
pub fn lock_cwd() -> CwdGuard {
let lock = CWD_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
let original = std::env::current_dir().expect("failed to get current dir");
CwdGuard {
_lock: lock,
original,
}
}
pub struct CwdGuard {
_lock: MutexGuard<'static, ()>,
original: PathBuf,
}
impl Drop for CwdGuard {
fn drop(&mut self) {
if let Err(err) = std::env::set_current_dir(&self.original) {
if std::thread::panicking() {
eprintln!(
"CwdGuard: failed to restore original working directory {:?}: {}",
self.original, err
);
} else {
panic!(
"CwdGuard: failed to restore original working directory {:?}: {}",
self.original, err
);
}
}
}
}