temp_dir/
lib.rs

1//! temp-dir
2//! ========
3//! [![crates.io version](https://img.shields.io/crates/v/temp-dir.svg)](https://crates.io/crates/temp-dir)
4//! [![license: Apache 2.0](https://gitlab.com/leonhard-llc/ops/-/raw/main/license-apache-2.0.svg)](https://gitlab.com/leonhard-llc/ops/-/raw/main/temp-dir/LICENSE)
5//! [![unsafe forbidden](https://gitlab.com/leonhard-llc/ops/-/raw/main/unsafe-forbidden.svg)](https://github.com/rust-secure-code/safety-dance/)
6//! [![pipeline status](https://gitlab.com/leonhard-llc/ops/badges/main/pipeline.svg)](https://gitlab.com/leonhard-llc/ops/-/pipelines)
7//!
8//! Provides a `TempDir` struct.
9//!
10//! # Features
11//! - Makes a directory in a system temporary directory
12//! - Recursively deletes the directory and its contents on drop
13//! - Deletes symbolic links and does not follow them
14//! - Optional name prefix
15//! - Depends only on `std`
16//! - `forbid(unsafe_code)`
17//! - 100% test coverage
18//!
19//! # Limitations
20//! - Not security-hardened.
21//!   For example, directory and file names are predictable.
22//! - This crate uses
23//!   [`std::fs::remove_dir_all`](https://doc.rust-lang.org/stable/std/fs/fn.remove_dir_all.html)
24//!   which may be unreliable on Windows.
25//!   See [rust#29497](https://github.com/rust-lang/rust/issues/29497) and
26//!   [`remove_dir_all`](https://crates.io/crates/remove_dir_all) crate.
27//!
28//! # Alternatives
29//! - [`tempdir`](https://crates.io/crates/tempdir)
30//!   - Unmaintained
31//!   - Popular and mature
32//!   - Heavy dependencies (rand, winapi)
33//! - [`tempfile`](https://crates.io/crates/tempfile)
34//!   - Popular and mature
35//!   - Contains `unsafe`, dependencies full of `unsafe`
36//!   - Heavy dependencies (libc, winapi, rand, etc.)
37//! - [`test_dir`](https://crates.io/crates/test_dir)
38//!   - Has a handy `TestDir` struct
39//!   - Incomplete documentation
40//! - [`temp_testdir`](https://crates.io/crates/temp_testdir)
41//!   - Incomplete documentation
42//! - [`mktemp`](https://crates.io/crates/mktemp)
43//!   - Sets directory mode 0700 on unix
44//!   - Contains `unsafe`
45//!   - No readme or online docs
46//!
47//! # Related Crates
48//! - [`temp-file`](https://crates.io/crates/temp-file)
49//!
50//! # Example
51//! ```rust
52//! use temp_dir::TempDir;
53//! let d = TempDir::new().unwrap();
54//! // Prints "/tmp/t1a9b-0".
55//! println!("{:?}", d.path());
56//! let f = d.child("file1");
57//! // Prints "/tmp/t1a9b-0/file1".
58//! println!("{:?}", f);
59//! std::fs::write(&f, b"abc").unwrap();
60//! assert_eq!(
61//!     "abc",
62//!     std::fs::read_to_string(&f).unwrap(),
63//! );
64//! // Prints "/tmp/t1a9b-1".
65//! println!(
66//!     "{:?}", TempDir::new().unwrap().path());
67//! ```
68//!
69//! # Cargo Geiger Safety Report
70//! # Changelog
71//! - v0.1.16 - `dont_delete_on_drop()`.  Thanks to [A L Manning](https://gitlab.com/A-Manning) for [discussion](https://gitlab.com/leonhard-llc/ops/-/merge_requests/5).
72//! - v0.1.15 - Remove a dev dependency.
73//! - v0.1.14 - `AsRef<Path>`
74//! - v0.1.13 - Update docs.
75//! - v0.1.12 - Work when the directory already exists.
76//! - v0.1.11
77//!   - Return `std::io::Error` instead of `String`.
78//!   - Add
79//!     [`cleanup`](https://docs.rs/temp-file/latest/temp_file/struct.TempFile.html#method.cleanup).
80//! - v0.1.10 - Implement `Eq`, `Ord`, `Hash`
81//! - v0.1.9 - Increase test coverage
82//! - v0.1.8 - Add [`leak`](https://docs.rs/temp-dir/latest/temp_dir/struct.TempDir.html#method.leak).
83//! - v0.1.7 - Update docs:
84//!   Warn about `std::fs::remove_dir_all` being unreliable on Windows.
85//!   Warn about predictable directory and file names.
86//!   Thanks to Reddit user
87//!   [burntsushi](https://www.reddit.com/r/rust/comments/ma6y0x/tempdir_simple_temporary_directory_with_cleanup/gruo5iu/).
88//! - v0.1.6 - Add
89//!   [`TempDir::panic_on_cleanup_error`](https://docs.rs/temp-dir/latest/temp_dir/struct.TempDir.html#method.panic_on_cleanup_error).
90//!   Thanks to Reddit users
91//!   [`KhorneLordOfChaos`](https://www.reddit.com/r/rust/comments/ma6y0x/tempdir_simple_temporary_directory_with_cleanup/grsb5s3/)
92//!   and
93//!   [`dpc_pw`](https://www.reddit.com/r/rust/comments/ma6y0x/tempdir_simple_temporary_directory_with_cleanup/gru26df/)
94//!   for their comments.
95//! - v0.1.5 - Explain how it handles symbolic links.
96//!   Thanks to Reddit user Mai4eeze for this
97//!   [idea](https://www.reddit.com/r/rust/comments/ma6y0x/tempdir_simple_temporary_directory_with_cleanup/grsoz2g/).
98//! - v0.1.4 - Update docs
99//! - v0.1.3 - Minor code cleanup, update docs
100//! - v0.1.2 - Update docs
101//! - v0.1.1 - Fix license
102//! - v0.1.0 - Initial version
103#![forbid(unsafe_code)]
104use core::sync::atomic::{AtomicU32, Ordering};
105use std::io::ErrorKind;
106use std::path::{Path, PathBuf};
107use std::sync::atomic::AtomicBool;
108
109#[doc(hidden)]
110pub static INTERNAL_COUNTER: AtomicU32 = AtomicU32::new(0);
111#[doc(hidden)]
112pub static INTERNAL_RETRY: AtomicBool = AtomicBool::new(true);
113
114/// The path of an existing writable directory in a system temporary directory.
115///
116/// Drop the struct to delete the directory and everything under it.
117/// Deletes symbolic links and does not follow them.
118///
119/// Ignores any error while deleting.
120/// See [`TempDir::panic_on_cleanup_error`](struct.TempDir.html#method.panic_on_cleanup_error).
121///
122/// # Example
123/// ```rust
124/// use temp_dir::TempDir;
125/// let d = TempDir::new().unwrap();
126/// // Prints "/tmp/t1a9b-0".
127/// println!("{:?}", d.path());
128/// let f = d.child("file1");
129/// // Prints "/tmp/t1a9b-0/file1".
130/// println!("{:?}", f);
131/// std::fs::write(&f, b"abc").unwrap();
132/// assert_eq!(
133///     "abc",
134///     std::fs::read_to_string(&f).unwrap(),
135/// );
136/// // Prints "/tmp/t1a9b-1".
137/// println!("{:?}", TempDir::new().unwrap().path());
138/// ```
139#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)]
140pub struct TempDir {
141    delete_on_drop: bool,
142    panic_on_delete_err: bool,
143    path_buf: PathBuf,
144}
145impl TempDir {
146    fn remove_dir(path: &Path) -> Result<(), std::io::Error> {
147        match std::fs::remove_dir_all(path) {
148            Ok(()) => Ok(()),
149            Err(e) if e.kind() == ErrorKind::NotFound => Ok(()),
150            Err(e) => Err(std::io::Error::new(
151                e.kind(),
152                format!("error removing directory and contents {path:?}: {e}"),
153            )),
154        }
155    }
156
157    /// Create a new empty directory in a system temporary directory.
158    ///
159    /// Drop the struct to delete the directory and everything under it.
160    /// Deletes symbolic links and does not follow them.
161    ///
162    /// Ignores any error while deleting.
163    /// See [`TempDir::panic_on_cleanup_error`](struct.TempDir.html#method.panic_on_cleanup_error).
164    ///
165    /// # Errors
166    /// Returns `Err` when it fails to create the directory.
167    ///
168    /// # Example
169    /// ```rust
170    /// // Prints "/tmp/t1a9b-0".
171    /// println!("{:?}", temp_dir::TempDir::new().unwrap().path());
172    /// ```
173    pub fn new() -> Result<Self, std::io::Error> {
174        // Prefix with 't' to avoid name collisions with `temp-file` crate.
175        Self::with_prefix("t")
176    }
177
178    /// Create a new empty directory in a system temporary directory.
179    /// Use `prefix` as the first part of the directory's name.
180    ///
181    /// Drop the struct to delete the directory and everything under it.
182    /// Deletes symbolic links and does not follow them.
183    ///
184    /// Ignores any error while deleting.
185    /// See [`TempDir::panic_on_cleanup_error`](struct.TempDir.html#method.panic_on_cleanup_error).
186    ///
187    /// # Errors
188    /// Returns `Err` when it fails to create the directory.
189    ///
190    /// # Example
191    /// ```rust
192    /// // Prints "/tmp/ok1a9b-0".
193    /// println!("{:?}", temp_dir::TempDir::with_prefix("ok").unwrap().path());
194    /// ```
195    pub fn with_prefix(prefix: impl AsRef<str>) -> Result<Self, std::io::Error> {
196        loop {
197            let path_buf = std::env::temp_dir().join(format!(
198                "{}{:x}-{:x}",
199                prefix.as_ref(),
200                std::process::id(),
201                INTERNAL_COUNTER.fetch_add(1, Ordering::AcqRel),
202            ));
203            match std::fs::create_dir(&path_buf) {
204                Err(e)
205                    if e.kind() == ErrorKind::AlreadyExists
206                        && INTERNAL_RETRY.load(Ordering::Acquire) => {}
207                Err(e) => {
208                    return Err(std::io::Error::new(
209                        e.kind(),
210                        format!("error creating directory {path_buf:?}: {e}"),
211                    ))
212                }
213                Ok(()) => {
214                    return Ok(Self {
215                        delete_on_drop: true,
216                        panic_on_delete_err: false,
217                        path_buf,
218                    })
219                }
220            }
221        }
222    }
223
224    /// Remove the directory and its contents now.
225    ///
226    /// # Errors
227    /// Returns an error if the directory exists and we fail to remove it and its contents.
228    #[allow(clippy::missing_panics_doc)]
229    pub fn cleanup(self) -> Result<(), std::io::Error> {
230        Self::remove_dir(&self.path_buf)
231    }
232
233    /// Make the struct panic on drop if it hits an error while
234    /// removing the directory or its contents.
235    #[must_use]
236    pub fn panic_on_cleanup_error(mut self) -> Self {
237        self.panic_on_delete_err = true;
238        self
239    }
240
241    /// Do not delete the directory or its contents.
242    ///
243    /// This is useful when debugging a test.
244    pub fn leak(mut self) {
245        self.delete_on_drop = false;
246    }
247
248    /// Do not delete the directory or its contents on Drop.
249    #[must_use]
250    pub fn dont_delete_on_drop(mut self) -> Self {
251        self.delete_on_drop = false;
252        self
253    }
254
255    /// The path to the directory.
256    #[must_use]
257    #[allow(clippy::missing_panics_doc)]
258    pub fn path(&self) -> &Path {
259        &self.path_buf
260    }
261
262    /// The path to `name` under the directory.
263    #[must_use]
264    #[allow(clippy::missing_panics_doc)]
265    pub fn child(&self, name: impl AsRef<str>) -> PathBuf {
266        let mut result = self.path_buf.clone();
267        result.push(name.as_ref());
268        result
269    }
270}
271impl Drop for TempDir {
272    fn drop(&mut self) {
273        if self.delete_on_drop {
274            let result = Self::remove_dir(&self.path_buf);
275            if self.panic_on_delete_err {
276                if let Err(e) = result {
277                    panic!("{}", e);
278                }
279            }
280        }
281    }
282}
283impl AsRef<Path> for TempDir {
284    fn as_ref(&self) -> &Path {
285        self.path()
286    }
287}