1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
//! A temporary directory that owns the thing built inside it.
//!
//! Three test helpers need a scratch directory and something that points into it — an empty
//! `SessionStore`, a cron root — and each one used to create the directory by hand and leave it
//! behind: `std::env::temp_dir().join(format!("…-{}", process::id()))`, `create_dir_all`, and no
//! removal, because a `OnceLock<PathBuf>` never drops. A full `cargo test` run left ~100
//! directories in `$TMPDIR`, one of them per cron test, each holding a `cron/jobs.toml`.
//!
//! `Scratch` keeps the `TempDir` next to the value and derefs to it, so a helper can return the
//! value exactly as before — `&scratch_store()`, `let root = temp_root(); root.join("cron")` — and
//! the directory goes away when the value does. The inline form works because a temporary lives
//! until the end of the statement that borrowed it: the directory outlives the call, and dies with
//! it.
use std::ops::{Deref, DerefMut};
/// A `TempDir` and the value built inside it. Derefs to the value.
pub struct Scratch<T> {
// Field order matters for the reader, not the compiler: the directory must not be dropped
// before the value that points into it, and `Drop` runs fields in declaration order.
value: T,
dir: tempfile::TempDir,
}
impl<T> Scratch<T> {
/// A fresh directory, and `build`'s result living in it.
pub fn new(prefix: &str, build: impl FnOnce(&std::path::Path) -> T) -> Self {
let dir = tempfile::Builder::new()
.prefix(prefix)
.tempdir()
.expect("a scratch directory under the system temp dir");
let value = build(dir.path());
Self { value, dir }
}
/// A fresh directory, as a path.
pub fn dir(prefix: &str) -> Self
where
T: From<std::path::PathBuf>,
{
Self::new(prefix, |path| T::from(path.to_path_buf()))
}
}
impl std::fmt::Debug for Scratch<std::path::PathBuf> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.dir.path().fmt(f)
}
}
/// `std::fs::remove_dir_all(&root)` and friends ask for `AsRef<Path>`, which deref coercion does
/// not satisfy, so a path-shaped `Scratch` says it directly.
impl AsRef<std::path::Path> for Scratch<std::path::PathBuf> {
fn as_ref(&self) -> &std::path::Path {
self.dir.path()
}
}
impl<T> Deref for Scratch<T> {
type Target = T;
fn deref(&self) -> &T {
&self.value
}
}
impl<T> DerefMut for Scratch<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.value
}
}