Skip to main content

cuno_core/
scratch.rs

1//! A directory for one run only, shared with nothing else and removed when
2//! the run is done (`docs/en/specs/architecture.md`, "What goes in
3//! `cuno-core`").
4
5use std::fmt;
6use std::io;
7use std::path::{Path, PathBuf};
8
9use crate::{CunoError, ExitClass};
10
11/// How many names are tried before giving up: far more than a run that
12/// does not leak directories ever meets.
13const TRIES: u32 = 100;
14
15/// A directory of this run's own, removed when dropped.
16#[derive(Debug)]
17pub struct Scratch {
18    dir: PathBuf,
19}
20
21impl Scratch {
22    /// Makes `parent/cuno-<command>-<process id>-<n>`, the first `n` whose
23    /// name is not taken. A name that exists, whoever made it, is passed
24    /// over: a killed run leaves its directory behind and its process id is
25    /// reused. `parent` is not created: a missing parent is the caller's
26    /// problem to report. The error names the directory that could not be
27    /// made.
28    pub fn new(parent: &Path, command: &str) -> Result<Scratch, (PathBuf, io::Error)> {
29        // The process id keeps two cuno processes apart. It is the
30        // process's identity, not its environment, so a library may ask.
31        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    /// The directory.
47    pub fn path(&self) -> &Path {
48        &self.dir
49    }
50}
51
52impl Drop for Scratch {
53    fn drop(&mut self) {
54        // Left behind only if it cannot be removed; nothing else uses it.
55        let _ = std::fs::remove_dir_all(&self.dir);
56    }
57}
58
59/// A scratch directory of `command`'s, for `purpose` (`check clang`,
60/// `format`), in `temp`, the temporary directory.
61pub 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/// The temporary directory cannot hold a scratch directory: `TEMP` names one
70/// that does not exist or cannot be written. Every command says it alike.
71#[derive(Debug)]
72pub struct TempError {
73    /// The directory that could not be made.
74    pub dir: PathBuf,
75    /// What it was for (`check clang`, `format`).
76    pub purpose: String,
77    /// Why, as the system said.
78    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    /// The directory is made under the parent given, named for the command
110    /// and this process, and is gone once dropped.
111    ///
112    /// Mutation: leave the process id out of the name, or skip the removal;
113    /// this test fails.
114    #[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    /// A name a killed run left behind is passed over and left alone.
129    ///
130    /// Mutation: fail on a name already taken, or take it over; this test
131    /// fails.
132    #[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    /// A missing temporary directory is a setup problem that says what the
147    /// directory was for and how to fix it, and is not created.
148    ///
149    /// Mutation: create the parent with `create_dir_all`, or drop the help;
150    /// this test fails.
151    #[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    /// When every name is taken, nothing is taken over: an error, and the
173    /// directories already there are left as they were. A run that took one
174    /// over would read another run's leftovers, and remove them when done.
175    ///
176    /// Mutation: take over the first name when all are taken; this test
177    /// fails.
178    #[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}