Skip to main content

tpt_temp_fs/
lib.rs

1use std::fs;
2use std::io;
3use std::path::{Path, PathBuf};
4
5/// An ephemeral temporary directory that is automatically deleted when dropped.
6///
7/// # Example
8/// ```rust
9/// # use tpt_temp_fs::TempDir;
10/// let dir = TempDir::new().unwrap();
11/// dir.write_file("hello.txt", "world").unwrap();
12/// assert!(dir.child("hello.txt").exists());
13/// // deleted automatically when `dir` is dropped
14/// ```
15pub struct TempDir {
16    path: PathBuf,
17    persistent: bool,
18}
19
20impl TempDir {
21    /// Create a new temporary directory with a random name inside `std::env::temp_dir()`.
22    pub fn new() -> io::Result<Self> {
23        Self::with_prefix("tpt-")
24    }
25
26    /// Create a new temporary directory with a specific prefix.
27    pub fn with_prefix(prefix: &str) -> io::Result<Self> {
28        let base = std::env::temp_dir();
29        // Generate a unique suffix using a mix of time + random-ish data.
30        let suffix = unique_suffix();
31        let path = base.join(format!("{prefix}{suffix}"));
32        fs::create_dir_all(&path)?;
33        Ok(Self {
34            path,
35            persistent: false,
36        })
37    }
38
39    /// The root path of this temporary directory.
40    pub fn path(&self) -> &Path {
41        &self.path
42    }
43
44    /// Resolve a relative path inside this directory without creating anything.
45    pub fn child(&self, rel: impl AsRef<Path>) -> PathBuf {
46        self.path.join(rel)
47    }
48
49    /// Write `content` to `rel` path, creating parent directories as needed.
50    pub fn write_file(&self, rel: impl AsRef<Path>, content: impl AsRef<[u8]>) -> io::Result<()> {
51        let dest = self.path.join(rel);
52        if let Some(parent) = dest.parent() {
53            fs::create_dir_all(parent)?;
54        }
55        fs::write(dest, content)
56    }
57
58    /// Create a subdirectory (and any missing parents) inside this temporary directory.
59    pub fn create_dir(&self, rel: impl AsRef<Path>) -> io::Result<()> {
60        fs::create_dir_all(self.path.join(rel))
61    }
62
63    /// Keep the directory on disk after this value is dropped.
64    ///
65    /// Returns the path so callers can reference it after the guard is gone.
66    pub fn into_persistent(mut self) -> PathBuf {
67        self.persistent = true;
68        self.path.clone()
69    }
70
71    /// Scaffold a directory tree from a JSON or YAML string.
72    ///
73    /// The string must be a mapping where:
74    /// - keys are relative paths
75    /// - values are file contents (strings)
76    /// - keys ending in `/` create empty directories
77    ///
78    /// Tries JSON first, falls back to YAML.
79    ///
80    /// # Example (YAML)
81    /// ```ignore
82    /// dir.scaffold_from_str("
83    ///   config.json: '{\"key\":\"value\"}'
84    ///   subdir/:
85    ///   subdir/file.txt: hello
86    /// ").unwrap();
87    /// ```
88    #[cfg(feature = "scaffold")]
89    pub fn scaffold_from_str(&self, s: &str) -> io::Result<()> {
90        let map = parse_scaffold(s).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
91        for (key, value) in map {
92            if key.ends_with('/') {
93                self.create_dir(&key[..key.len() - 1])?;
94            } else {
95                self.write_file(&key, value.as_bytes())?;
96            }
97        }
98        Ok(())
99    }
100}
101
102impl Drop for TempDir {
103    fn drop(&mut self) {
104        if !self.persistent && self.path.exists() {
105            let _ = fs::remove_dir_all(&self.path);
106        }
107    }
108}
109
110fn unique_suffix() -> String {
111    use std::time::{SystemTime, UNIX_EPOCH};
112    let nanos = SystemTime::now()
113        .duration_since(UNIX_EPOCH)
114        .map(|d| d.subsec_nanos())
115        .unwrap_or(0);
116    // Mix in the thread id as a second source of uniqueness.
117    let tid = format!("{:?}", std::thread::current().id());
118    let tid_hash: u64 = tid
119        .bytes()
120        .fold(0u64, |acc, b| acc.wrapping_mul(31).wrapping_add(b as u64));
121    format!("{nanos:08x}{tid_hash:08x}")
122}
123
124#[cfg(feature = "scaffold")]
125fn parse_scaffold(s: &str) -> Result<std::collections::BTreeMap<String, String>, String> {
126    // Try JSON first.
127    if let Ok(val) = serde_json::from_str::<serde_json::Value>(s) {
128        return json_value_to_map(val);
129    }
130    // Fall back to YAML.
131    let val: serde_yaml::Value =
132        serde_yaml::from_str(s).map_err(|e| format!("YAML parse error: {e}"))?;
133    yaml_value_to_map(val)
134}
135
136#[cfg(feature = "scaffold")]
137fn json_value_to_map(
138    val: serde_json::Value,
139) -> Result<std::collections::BTreeMap<String, String>, String> {
140    match val {
141        serde_json::Value::Object(m) => m
142            .into_iter()
143            .map(|(k, v)| {
144                let content = match v {
145                    serde_json::Value::String(s) => s,
146                    serde_json::Value::Null => String::new(),
147                    other => other.to_string(),
148                };
149                Ok((k, content))
150            })
151            .collect(),
152        _ => Err("scaffold JSON must be an object mapping paths to contents".into()),
153    }
154}
155
156#[cfg(feature = "scaffold")]
157fn yaml_value_to_map(
158    val: serde_yaml::Value,
159) -> Result<std::collections::BTreeMap<String, String>, String> {
160    match val {
161        serde_yaml::Value::Mapping(m) => m
162            .into_iter()
163            .map(|(k, v)| {
164                let key = match k {
165                    serde_yaml::Value::String(s) => s,
166                    other => format!("{other:?}"),
167                };
168                let content = match v {
169                    serde_yaml::Value::String(s) => s,
170                    serde_yaml::Value::Null => String::new(),
171                    other => format!("{other:?}"),
172                };
173                Ok((key, content))
174            })
175            .collect(),
176        _ => Err("scaffold YAML must be a mapping of paths to contents".into()),
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183
184    #[test]
185    fn creates_and_cleans_up() {
186        let path = {
187            let dir = TempDir::new().unwrap();
188            let p = dir.path().to_path_buf();
189            assert!(p.exists());
190            p
191        };
192        assert!(!path.exists(), "directory should be deleted on drop");
193    }
194
195    #[test]
196    fn write_and_read_file() {
197        let dir = TempDir::new().unwrap();
198        dir.write_file("hello.txt", "world").unwrap();
199        assert_eq!(fs::read_to_string(dir.child("hello.txt")).unwrap(), "world");
200    }
201
202    #[test]
203    fn nested_write_creates_parents() {
204        let dir = TempDir::new().unwrap();
205        dir.write_file("a/b/c.txt", "deep").unwrap();
206        assert!(dir.child("a/b/c.txt").exists());
207    }
208
209    #[test]
210    fn into_persistent_survives_drop() {
211        let path = TempDir::new().unwrap().into_persistent();
212        assert!(path.exists());
213        fs::remove_dir_all(&path).unwrap();
214    }
215
216    #[test]
217    #[cfg(feature = "scaffold")]
218    fn scaffold_from_yaml() {
219        let dir = TempDir::new().unwrap();
220        dir.scaffold_from_str("config.txt: hello\nsubdir/:\n")
221            .unwrap();
222        assert_eq!(
223            fs::read_to_string(dir.child("config.txt")).unwrap(),
224            "hello"
225        );
226        assert!(dir.child("subdir").is_dir());
227    }
228
229    #[test]
230    #[cfg(feature = "scaffold")]
231    fn scaffold_from_json() {
232        let dir = TempDir::new().unwrap();
233        dir.scaffold_from_str(r#"{"file.txt": "content"}"#).unwrap();
234        assert_eq!(
235            fs::read_to_string(dir.child("file.txt")).unwrap(),
236            "content"
237        );
238    }
239}