1use std::fmt;
6use std::io;
7use std::path::{Path, PathBuf};
8
9use crate::{CunoError, ExitClass};
10
11const TRIES: u32 = 100;
14
15fn name(command: &str, id: u32, n: u32) -> String {
18 format!("cuno-{command}-{id}-{n}")
19}
20
21pub fn longest_name(command: &str) -> String {
25 name(command, u32::MAX, TRIES - 1)
26}
27
28#[derive(Debug)]
30pub struct Scratch {
31 dir: PathBuf,
32}
33
34impl Scratch {
35 pub fn new(parent: &Path, command: &str) -> Result<Scratch, (PathBuf, io::Error)> {
42 let id = std::process::id();
45 for n in 0..TRIES {
46 let dir = parent.join(name(command, id, n));
47 match std::fs::create_dir(&dir) {
48 Ok(()) => return Ok(Scratch { dir }),
49 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
50 Err(e) => return Err((dir, e)),
51 }
52 }
53 Err((
54 parent.to_owned(),
55 io::Error::other("every scratch name is taken"),
56 ))
57 }
58
59 pub fn path(&self) -> &Path {
61 &self.dir
62 }
63}
64
65impl Drop for Scratch {
66 fn drop(&mut self) {
67 let _ = std::fs::remove_dir_all(&self.dir);
69 }
70}
71
72pub fn in_temp(temp: &Path, command: &str, purpose: &str) -> Result<Scratch, TempError> {
75 Scratch::new(temp, command).map_err(|(dir, e)| TempError {
76 dir,
77 purpose: purpose.to_owned(),
78 reason: e.to_string(),
79 })
80}
81
82#[derive(Debug)]
85pub struct TempError {
86 pub dir: PathBuf,
88 pub purpose: String,
90 pub reason: String,
92}
93
94impl fmt::Display for TempError {
95 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
96 write!(
97 f,
98 "cannot create {} to {}: {}",
99 self.dir.display(),
100 self.purpose,
101 self.reason
102 )
103 }
104}
105
106impl std::error::Error for TempError {}
107
108impl CunoError for TempError {
109 fn exit_class(&self) -> ExitClass {
110 ExitClass::Setup
111 }
112
113 fn help(&self) -> Option<String> {
114 Some("set TMP and TEMP to a directory that exists and can be written".to_owned())
115 }
116}
117
118#[cfg(test)]
119mod tests {
120 use super::*;
121
122 #[test]
128 fn a_scratch_directory_is_made_and_removed() {
129 let parent = tempfile::tempdir().unwrap();
130 let scratch = Scratch::new(parent.path(), "fmt").unwrap();
131 let dir = scratch.path().to_owned();
132 assert!(dir.is_dir());
133 assert_eq!(dir.parent(), Some(parent.path()));
134 let name = dir.file_name().unwrap().to_string_lossy().into_owned();
135 assert_eq!(name, format!("cuno-fmt-{}-0", std::process::id()));
136 std::fs::write(dir.join("file"), "").unwrap();
137 drop(scratch);
138 assert!(!dir.exists(), "the scratch directory was left behind");
139 }
140
141 #[test]
146 fn a_taken_name_is_passed_over() {
147 let parent = tempfile::tempdir().unwrap();
148 let left = parent
149 .path()
150 .join(format!("cuno-lint-{}-0", std::process::id()));
151 std::fs::create_dir(&left).unwrap();
152 std::fs::write(left.join("theirs"), "").unwrap();
153 let scratch = Scratch::new(parent.path(), "lint").unwrap();
154 assert_ne!(scratch.path(), left);
155 drop(scratch);
156 assert!(left.join("theirs").is_file());
157 }
158
159 #[test]
165 fn a_missing_temporary_directory_is_a_setup_problem() {
166 let temp = tempfile::tempdir().unwrap();
167 let missing = temp.path().join("missing");
168 let err = in_temp(&missing, "fmt", "format").unwrap_err();
169 assert_eq!(err.exit_class(), ExitClass::Setup);
170 let shown = err.to_string();
171 let start = format!(
172 "cannot create {} to format: ",
173 missing
174 .join(format!("cuno-fmt-{}-0", std::process::id()))
175 .display()
176 );
177 assert!(shown.starts_with(&start), "{shown}");
178 assert_eq!(
179 err.help().as_deref(),
180 Some("set TMP and TEMP to a directory that exists and can be written")
181 );
182 assert!(!missing.exists());
183 }
184
185 #[test]
192 fn every_name_taken_is_an_error_that_takes_nothing_over() {
193 let parent = tempfile::tempdir().unwrap();
194 for n in 0..TRIES {
195 let dir = parent
196 .path()
197 .join(format!("cuno-test-{}-{n}", std::process::id()));
198 std::fs::create_dir(&dir).unwrap();
199 std::fs::write(dir.join("theirs"), "").unwrap();
200 }
201 let (dir, e) = Scratch::new(parent.path(), "test").unwrap_err();
202 assert_eq!(dir, parent.path());
203 assert_eq!(e.to_string(), "every scratch name is taken");
204 let first = parent
205 .path()
206 .join(format!("cuno-test-{}-0", std::process::id()));
207 assert!(first.join("theirs").is_file());
208 }
209}