1use std::fmt;
6use std::io;
7use std::path::{Path, PathBuf};
8
9use crate::{CunoError, ExitClass};
10
11const TRIES: u32 = 100;
14
15#[derive(Debug)]
17pub struct Scratch {
18 dir: PathBuf,
19}
20
21impl Scratch {
22 pub fn new(parent: &Path, command: &str) -> Result<Scratch, (PathBuf, io::Error)> {
29 let id = std::process::id();
32 for n in 0..TRIES {
33 let dir = parent.join(format!("cuno-{command}-{id}-{n}"));
34 match std::fs::create_dir(&dir) {
35 Ok(()) => return Ok(Scratch { dir }),
36 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
37 Err(e) => return Err((dir, e)),
38 }
39 }
40 Err((
41 parent.to_owned(),
42 io::Error::other("every scratch name is taken"),
43 ))
44 }
45
46 pub fn path(&self) -> &Path {
48 &self.dir
49 }
50}
51
52impl Drop for Scratch {
53 fn drop(&mut self) {
54 let _ = std::fs::remove_dir_all(&self.dir);
56 }
57}
58
59pub fn in_temp(temp: &Path, command: &str, purpose: &str) -> Result<Scratch, TempError> {
62 Scratch::new(temp, command).map_err(|(dir, e)| TempError {
63 dir,
64 purpose: purpose.to_owned(),
65 reason: e.to_string(),
66 })
67}
68
69#[derive(Debug)]
72pub struct TempError {
73 pub dir: PathBuf,
75 pub purpose: String,
77 pub reason: String,
79}
80
81impl fmt::Display for TempError {
82 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83 write!(
84 f,
85 "cannot create {} to {}: {}",
86 self.dir.display(),
87 self.purpose,
88 self.reason
89 )
90 }
91}
92
93impl std::error::Error for TempError {}
94
95impl CunoError for TempError {
96 fn exit_class(&self) -> ExitClass {
97 ExitClass::Setup
98 }
99
100 fn help(&self) -> Option<String> {
101 Some("set TMP and TEMP to a directory that exists and can be written".to_owned())
102 }
103}
104
105#[cfg(test)]
106mod tests {
107 use super::*;
108
109 #[test]
115 fn a_scratch_directory_is_made_and_removed() {
116 let parent = tempfile::tempdir().unwrap();
117 let scratch = Scratch::new(parent.path(), "fmt").unwrap();
118 let dir = scratch.path().to_owned();
119 assert!(dir.is_dir());
120 assert_eq!(dir.parent(), Some(parent.path()));
121 let name = dir.file_name().unwrap().to_string_lossy().into_owned();
122 assert_eq!(name, format!("cuno-fmt-{}-0", std::process::id()));
123 std::fs::write(dir.join("file"), "").unwrap();
124 drop(scratch);
125 assert!(!dir.exists(), "the scratch directory was left behind");
126 }
127
128 #[test]
133 fn a_taken_name_is_passed_over() {
134 let parent = tempfile::tempdir().unwrap();
135 let left = parent
136 .path()
137 .join(format!("cuno-lint-{}-0", std::process::id()));
138 std::fs::create_dir(&left).unwrap();
139 std::fs::write(left.join("theirs"), "").unwrap();
140 let scratch = Scratch::new(parent.path(), "lint").unwrap();
141 assert_ne!(scratch.path(), left);
142 drop(scratch);
143 assert!(left.join("theirs").is_file());
144 }
145
146 #[test]
152 fn a_missing_temporary_directory_is_a_setup_problem() {
153 let temp = tempfile::tempdir().unwrap();
154 let missing = temp.path().join("missing");
155 let err = in_temp(&missing, "fmt", "format").unwrap_err();
156 assert_eq!(err.exit_class(), ExitClass::Setup);
157 let shown = err.to_string();
158 let start = format!(
159 "cannot create {} to format: ",
160 missing
161 .join(format!("cuno-fmt-{}-0", std::process::id()))
162 .display()
163 );
164 assert!(shown.starts_with(&start), "{shown}");
165 assert_eq!(
166 err.help().as_deref(),
167 Some("set TMP and TEMP to a directory that exists and can be written")
168 );
169 assert!(!missing.exists());
170 }
171
172 #[test]
179 fn every_name_taken_is_an_error_that_takes_nothing_over() {
180 let parent = tempfile::tempdir().unwrap();
181 for n in 0..TRIES {
182 let dir = parent
183 .path()
184 .join(format!("cuno-test-{}-{n}", std::process::id()));
185 std::fs::create_dir(&dir).unwrap();
186 std::fs::write(dir.join("theirs"), "").unwrap();
187 }
188 let (dir, e) = Scratch::new(parent.path(), "test").unwrap_err();
189 assert_eq!(dir, parent.path());
190 assert_eq!(e.to_string(), "every scratch name is taken");
191 let first = parent
192 .path()
193 .join(format!("cuno-test-{}-0", std::process::id()));
194 assert!(first.join("theirs").is_file());
195 }
196}