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/// The name of the `n`th directory `Scratch::new` tries for `command` in
16/// the process `id`.
17fn name(command: &str, id: u32, n: u32) -> String {
18    format!("cuno-{command}-{id}-{n}")
19}
20
21/// The longest name `Scratch::new` can give a directory for `command`: the
22/// largest process id and the last name it tries. A check of how long the
23/// paths under it can grow measures this.
24pub fn longest_name(command: &str) -> String {
25    name(command, u32::MAX, TRIES - 1)
26}
27
28/// A directory of this run's own, removed when dropped.
29#[derive(Debug)]
30pub struct Scratch {
31    dir: PathBuf,
32}
33
34impl Scratch {
35    /// Makes `parent/cuno-<command>-<process id>-<n>`, the first `n` whose
36    /// name is not taken. A name that exists, whoever made it, is passed
37    /// over: a killed run leaves its directory behind and its process id is
38    /// reused. `parent` is not created: a missing parent is the caller's
39    /// problem to report. The error names the directory that could not be
40    /// made.
41    pub fn new(parent: &Path, command: &str) -> Result<Scratch, (PathBuf, io::Error)> {
42        // The process id keeps two cuno processes apart. It is the
43        // process's identity, not its environment, so a library may ask.
44        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    /// The directory.
60    pub fn path(&self) -> &Path {
61        &self.dir
62    }
63}
64
65impl Drop for Scratch {
66    fn drop(&mut self) {
67        // Left behind only if it cannot be removed; nothing else uses it.
68        let _ = std::fs::remove_dir_all(&self.dir);
69    }
70}
71
72/// A scratch directory of `command`'s, for `purpose` (`check clang`,
73/// `format`), in `temp`, the temporary directory.
74pub 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/// The temporary directory cannot hold a scratch directory: `TEMP` names one
83/// that does not exist or cannot be written. Every command says it alike.
84#[derive(Debug)]
85pub struct TempError {
86    /// The directory that could not be made.
87    pub dir: PathBuf,
88    /// What it was for (`check clang`, `format`).
89    pub purpose: String,
90    /// Why, as the system said.
91    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    /// The directory is made under the parent given, named for the command
123    /// and this process, and is gone once dropped.
124    ///
125    /// Mutation: leave the process id out of the name, or skip the removal;
126    /// this test fails.
127    #[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    /// A name a killed run left behind is passed over and left alone.
142    ///
143    /// Mutation: fail on a name already taken, or take it over; this test
144    /// fails.
145    #[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    /// A missing temporary directory is a setup problem that says what the
160    /// directory was for and how to fix it, and is not created.
161    ///
162    /// Mutation: create the parent with `create_dir_all`, or drop the help;
163    /// this test fails.
164    #[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    /// When every name is taken, nothing is taken over: an error, and the
186    /// directories already there are left as they were. A run that took one
187    /// over would read another run's leftovers, and remove them when done.
188    ///
189    /// Mutation: take over the first name when all are taken; this test
190    /// fails.
191    #[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}