use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use crate::{CunoError, ExitClass};
const TRIES: u32 = 100;
#[derive(Debug)]
pub struct Scratch {
dir: PathBuf,
}
impl Scratch {
pub fn new(parent: &Path, command: &str) -> Result<Scratch, (PathBuf, io::Error)> {
let id = std::process::id();
for n in 0..TRIES {
let dir = parent.join(format!("cuno-{command}-{id}-{n}"));
match std::fs::create_dir(&dir) {
Ok(()) => return Ok(Scratch { dir }),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
Err(e) => return Err((dir, e)),
}
}
Err((
parent.to_owned(),
io::Error::other("every scratch name is taken"),
))
}
pub fn path(&self) -> &Path {
&self.dir
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.dir);
}
}
pub fn in_temp(temp: &Path, command: &str, purpose: &str) -> Result<Scratch, TempError> {
Scratch::new(temp, command).map_err(|(dir, e)| TempError {
dir,
purpose: purpose.to_owned(),
reason: e.to_string(),
})
}
#[derive(Debug)]
pub struct TempError {
pub dir: PathBuf,
pub purpose: String,
pub reason: String,
}
impl fmt::Display for TempError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"cannot create {} to {}: {}",
self.dir.display(),
self.purpose,
self.reason
)
}
}
impl std::error::Error for TempError {}
impl CunoError for TempError {
fn exit_class(&self) -> ExitClass {
ExitClass::Setup
}
fn help(&self) -> Option<String> {
Some("set TMP and TEMP to a directory that exists and can be written".to_owned())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_scratch_directory_is_made_and_removed() {
let parent = tempfile::tempdir().unwrap();
let scratch = Scratch::new(parent.path(), "fmt").unwrap();
let dir = scratch.path().to_owned();
assert!(dir.is_dir());
assert_eq!(dir.parent(), Some(parent.path()));
let name = dir.file_name().unwrap().to_string_lossy().into_owned();
assert_eq!(name, format!("cuno-fmt-{}-0", std::process::id()));
std::fs::write(dir.join("file"), "").unwrap();
drop(scratch);
assert!(!dir.exists(), "the scratch directory was left behind");
}
#[test]
fn a_taken_name_is_passed_over() {
let parent = tempfile::tempdir().unwrap();
let left = parent
.path()
.join(format!("cuno-lint-{}-0", std::process::id()));
std::fs::create_dir(&left).unwrap();
std::fs::write(left.join("theirs"), "").unwrap();
let scratch = Scratch::new(parent.path(), "lint").unwrap();
assert_ne!(scratch.path(), left);
drop(scratch);
assert!(left.join("theirs").is_file());
}
#[test]
fn a_missing_temporary_directory_is_a_setup_problem() {
let temp = tempfile::tempdir().unwrap();
let missing = temp.path().join("missing");
let err = in_temp(&missing, "fmt", "format").unwrap_err();
assert_eq!(err.exit_class(), ExitClass::Setup);
let shown = err.to_string();
let start = format!(
"cannot create {} to format: ",
missing
.join(format!("cuno-fmt-{}-0", std::process::id()))
.display()
);
assert!(shown.starts_with(&start), "{shown}");
assert_eq!(
err.help().as_deref(),
Some("set TMP and TEMP to a directory that exists and can be written")
);
assert!(!missing.exists());
}
#[test]
fn every_name_taken_is_an_error_that_takes_nothing_over() {
let parent = tempfile::tempdir().unwrap();
for n in 0..TRIES {
let dir = parent
.path()
.join(format!("cuno-test-{}-{n}", std::process::id()));
std::fs::create_dir(&dir).unwrap();
std::fs::write(dir.join("theirs"), "").unwrap();
}
let (dir, e) = Scratch::new(parent.path(), "test").unwrap_err();
assert_eq!(dir, parent.path());
assert_eq!(e.to_string(), "every scratch name is taken");
let first = parent
.path()
.join(format!("cuno-test-{}-0", std::process::id()));
assert!(first.join("theirs").is_file());
}
}