Skip to main content

kevy_tmpdir/
lib.rs

1//! A temporary directory that is actually unique, and cleans up after itself.
2//!
3//! Nine files in this workspace had invented their own, and five different ways
4//! of trying to make the name unique:
5//!
6//! ```text
7//! kevy-persist/feed_meta.rs    process::id() + Instant::now()
8//! kevy-persist/shards_meta.rs  process::id() + process::id()
9//! kevy-persist/reshard.rs      SystemTime
10//! kevy-cli/backup.rs           nanos
11//! kevy-uring/ring_tests.rs     process::id()
12//! …
13//! ```
14//!
15//! None of them is unique. `process::id()` is the SAME for every test in a
16//! binary — cargo runs them as threads, not processes — so two tests in the same
17//! file get the same directory and stamp on each other's files. A clock is
18//! unique only until two threads read it inside the same tick, which under
19//! parallel test execution is exactly what happens. That is a flake: green on a
20//! quiet machine, red under load, and it looks like the code is broken rather
21//! than the fixture.
22//!
23//! A process id and a monotonic counter, together, cannot collide: the counter
24//! separates threads within a process and the pid separates processes. That is
25//! the whole trick, and it is why this is one crate instead of nine copies.
26//!
27//! ```
28//! let dir = kevy_tmpdir::TmpDir::new("readme");
29//! std::fs::write(dir.path().join("data"), b"x")?;
30//! let path = dir.path().to_path_buf();
31//! drop(dir);
32//! assert!(!path.exists(), "gone with the guard");
33//! # Ok::<(), std::io::Error>(())
34//! ```
35
36// Best-effort removal, on paths where the file is being abandoned.
37// A file that will not delete is a stray the next sweep collects,
38// and refusing here would abandon the rest of the cleanup.
39#![expect(clippy::let_underscore_must_use, reason = "removing what is already meant to be gone")]
40#![warn(missing_docs)]
41
42use std::path::{Path, PathBuf};
43use std::sync::atomic::{AtomicU64, Ordering};
44
45static SEQ: AtomicU64 = AtomicU64::new(0);
46
47/// A unique directory as a bare path: created, PRE-CLEARED, and owned by the
48/// caller — for call sites that already carry their own cleanup, and for the
49/// one production path (kevy-cli's embed scratch) where the directory must
50/// outlive the function that made it.
51///
52/// The pre-clear matters more than it looks. The old pid-only scratch dir was
53/// never cleared, so a recycled pid inherited the PREVIOUS run's data files —
54/// `create_dir_all` on an existing directory succeeds silently, and the loader
55/// then read a mix of stale and fresh dumps as though they were one dataset.
56///
57/// # Panics
58///
59/// When the directory cannot be created: a caller with nowhere to put its
60/// files has nothing to do next.
61///
62/// # Examples
63///
64/// Two calls never collide, and the second call for a label does not
65/// inherit what the first one left:
66///
67/// ```
68/// let a = kevy_tmpdir::unique_dir("doc");
69/// let b = kevy_tmpdir::unique_dir("doc");
70/// assert_ne!(a, b);
71/// assert!(a.is_dir() && b.is_dir());
72///
73/// std::fs::write(a.join("stale"), b"old").unwrap();
74/// let again = kevy_tmpdir::unique_dir("doc");
75/// assert!(!again.join("stale").exists());
76///
77/// for d in [a, b, again] { std::fs::remove_dir_all(d).unwrap(); }
78/// ```
79pub fn unique_dir(label: &str) -> PathBuf {
80    let n = SEQ.fetch_add(1, Ordering::Relaxed);
81    let p = std::env::temp_dir().join(format!("kevy-{label}-{}-{n}", std::process::id()));
82    // A leftover from a previous process that reused this pid: it is being
83    // replaced, so its removal failing is not this call's problem.
84    let _ = std::fs::remove_dir_all(&p);
85    std::fs::create_dir_all(&p)
86        .expect("a caller with nowhere to put its files has nothing to do next");
87    p
88}
89
90/// A unique directory under the system temp dir, removed when dropped.
91///
92/// Dropped on unwind too, so a failing test does not leave litter behind for the
93/// next one to trip over.
94#[derive(Debug)]
95/// # Examples
96///
97/// ```
98/// use std::path::Path;
99/// let dir = kevy_tmpdir::TmpDir::new("doctest");
100/// let kept: std::path::PathBuf = dir.path().to_path_buf();
101/// assert!(kept.is_dir());
102/// drop(dir);
103/// assert!(!kept.exists(), "the guard deletes the directory it made");
104/// ```
105pub struct TmpDir(PathBuf);
106
107impl TmpDir {
108    /// `label` shows up in the path, so a directory that somehow survives says
109    /// which test left it.
110    ///
111    /// # Panics
112    ///
113    /// When the directory cannot be created, as [`unique_dir`].
114    ///
115    /// # Examples
116    ///
117    /// ```
118    /// let dir = kevy_tmpdir::TmpDir::new("who-left-this");
119    /// let name = dir.path().file_name().unwrap().to_string_lossy().into_owned();
120    /// assert!(name.contains("who-left-this"), "{name} does not name its owner");
121    /// ```
122    pub fn new(label: &str) -> Self {
123        Self(unique_dir(label))
124    }
125
126    /// The directory itself. Borrowed, not cloned, so the path cannot
127    /// outlive the guard that deletes it — a `PathBuf` handed out here
128    /// would still name the directory after `Drop` removed it.
129    ///
130    /// # Examples
131    ///
132    /// ```
133    /// let dir = kevy_tmpdir::TmpDir::new("write-something");
134    /// std::fs::write(dir.path().join("a.txt"), b"hello").unwrap();
135    /// assert_eq!(std::fs::read(dir.path().join("a.txt")).unwrap(), b"hello");
136    /// ```
137    pub fn path(&self) -> &Path {
138        &self.0
139    }
140
141    /// Remove the directory now and say whether that worked — what `Drop`
142    /// does, for a caller that cares about the answer. Dropping the guard
143    /// cannot report a failure, and removing a large tree blocks for as
144    /// long as it takes.
145    ///
146    /// # Examples
147    ///
148    /// ```
149    /// let dir = kevy_tmpdir::TmpDir::new("close-me");
150    /// let path = dir.path().to_path_buf();
151    /// dir.close()?;
152    /// assert!(!path.exists());
153    /// # Ok::<(), std::io::Error>(())
154    /// ```
155    pub fn close(mut self) -> std::io::Result<()> {
156        // an empty path tells `Drop` there is nothing left to remove
157        let path = std::mem::take(&mut self.0);
158        std::fs::remove_dir_all(path)
159    }
160}
161
162impl AsRef<Path> for TmpDir {
163    fn as_ref(&self) -> &Path {
164        &self.0
165    }
166}
167
168impl Drop for TmpDir {
169    fn drop(&mut self) {
170        // Drop cannot report, and a temp directory that outlives its process
171        // is the OS's to reclaim.
172        if !self.0.as_os_str().is_empty() {
173            let _ = std::fs::remove_dir_all(&self.0);
174        }
175    }
176}
177
178// Send and Sync are part of the public contract: a change that loses
179// either fails to compile here rather than in a caller.
180const _: () = {
181    const fn send_sync<T: Send + Sync>() {}
182    send_sync::<TmpDir>();
183};
184
185#[cfg(test)]
186mod tests {
187    use super::TmpDir;
188    use std::collections::HashSet;
189
190    #[test]
191    fn two_dirs_in_one_process_are_different() {
192        // The bug, stated: process::id() is the same for both of these.
193        let a = TmpDir::new("x");
194        let b = TmpDir::new("x");
195        assert_ne!(a.path(), b.path());
196    }
197
198    #[test]
199    fn threads_racing_for_a_name_all_get_their_own() {
200        let dirs: Vec<_> = std::thread::scope(|s| {
201            let handles: Vec<_> =
202                (0..32).map(|_| s.spawn(|| TmpDir::new("race").path().to_path_buf())).collect();
203            handles.into_iter().map(|h| h.join().expect("thread")).collect()
204        });
205        let uniq: HashSet<_> = dirs.iter().collect();
206        assert_eq!(uniq.len(), 32, "two threads got the same directory");
207    }
208
209    #[test]
210    fn the_directory_exists_and_then_does_not() {
211        let p = {
212            let d = TmpDir::new("drop");
213            assert!(d.path().is_dir());
214            d.path().to_path_buf()
215        };
216        assert!(!p.exists(), "TmpDir did not clean up after itself");
217    }
218
219    #[test]
220    fn close_removes_the_tree_and_reports_a_failure() {
221        let d = TmpDir::new("close");
222        let p = d.path().to_path_buf();
223        std::fs::create_dir(p.join("sub")).unwrap();
224        std::fs::write(p.join("sub/f"), b"x").unwrap();
225        d.close().unwrap();
226        assert!(!p.exists(), "close left the directory behind");
227
228        let gone = TmpDir::new("close-gone");
229        std::fs::remove_dir_all(gone.path()).unwrap();
230        let err = gone.close().unwrap_err();
231        assert_eq!(err.kind(), std::io::ErrorKind::NotFound);
232    }
233}