use std::path::{Path, PathBuf};
use std::sync::{Mutex, Once, PoisonError};
const INTERRUPTED: i32 = 130;
static LEFTOVERS: Leftovers = Leftovers::new();
pub(crate) fn remove_on_interrupt(path: &Path) {
LEFTOVERS.add(path);
static HANDLER: Once = Once::new();
HANDLER.call_once(|| {
let installed = ctrlc::set_handler(|| {
LEFTOVERS.remove_all();
std::process::exit(INTERRUPTED);
});
if let Err(e) = installed {
eprintln!("[cargo-telar] could not watch for interruptions: {e}");
}
});
}
pub(crate) fn keep_on_interrupt(path: &Path) {
LEFTOVERS.keep(path);
}
struct Leftovers(Mutex<Vec<PathBuf>>);
impl Leftovers {
const fn new() -> Self {
Self(Mutex::new(Vec::new()))
}
fn add(&self, path: &Path) {
self.paths().push(path.to_path_buf());
}
fn keep(&self, path: &Path) {
self.paths().retain(|held| held != path);
}
fn remove_all(&self) {
for path in std::mem::take(&mut *self.paths()) {
let _ = std::fs::remove_file(path);
}
}
#[cfg(test)]
fn holds(&self, path: &Path) -> bool {
self.paths().iter().any(|held| held == path)
}
fn paths(&self) -> std::sync::MutexGuard<'_, Vec<PathBuf>> {
self.0.lock().unwrap_or_else(PoisonError::into_inner)
}
}
#[cfg(test)]
pub(crate) fn removes_on_interrupt(path: &Path) -> bool {
LEFTOVERS.holds(path)
}
#[cfg(test)]
#[path = "interrupt.test.rs"]
mod tests;