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.15 - Remove a dev dependency.
72//! - v0.1.14 - `AsRef<Path>`
73//! - v0.1.13 - Update docs.
74//! - v0.1.12 - Work when the directory already exists.
75//! - v0.1.11
76//!   - Return `std::io::Error` instead of `String`.
77//!   - Add
78//!     [`cleanup`](https://docs.rs/temp-file/latest/temp_file/struct.TempFile.html#method.cleanup).
79//! - v0.1.10 - Implement `Eq`, `Ord`, `Hash`
80//! - v0.1.9 - Increase test coverage
81//! - v0.1.8 - Add [`leak`](https://docs.rs/temp-dir/latest/temp_dir/struct.TempDir.html#method.leak).
82//! - v0.1.7 - Update docs:
83//!   Warn about `std::fs::remove_dir_all` being unreliable on Windows.
84//!   Warn about predictable directory and file names.
85//!   Thanks to Reddit user
86//!   [burntsushi](https://www.reddit.com/r/rust/comments/ma6y0x/tempdir_simple_temporary_directory_with_cleanup/gruo5iu/).
87//! - v0.1.6 - Add
88//!     [`TempDir::panic_on_cleanup_error`](https://docs.rs/temp-dir/latest/temp_dir/struct.TempDir.html#method.panic_on_cleanup_error).
89//!     Thanks to Reddit users
90//!     [`KhorneLordOfChaos`](https://www.reddit.com/r/rust/comments/ma6y0x/tempdir_simple_temporary_directory_with_cleanup/grsb5s3/)
91//!     and
92//!     [`dpc_pw`](https://www.reddit.com/r/rust/comments/ma6y0x/tempdir_simple_temporary_directory_with_cleanup/gru26df/)
93//!     for their comments.
94//! - v0.1.5 - Explain how it handles symbolic links.
95//!   Thanks to Reddit user Mai4eeze for this
96//!   [idea](https://www.reddit.com/r/rust/comments/ma6y0x/tempdir_simple_temporary_directory_with_cleanup/grsoz2g/).
97//! - v0.1.4 - Update docs
98//! - v0.1.3 - Minor code cleanup, update docs
99//! - v0.1.2 - Update docs
100//! - v0.1.1 - Fix license
101//! - v0.1.0 - Initial version
102#![forbid(unsafe_code)]
103use core::sync::atomic::{AtomicU32, Ordering};
104use std::io::ErrorKind;
105use std::path::{Path, PathBuf};
106use std::sync::atomic::AtomicBool;
107
108#[doc(hidden)]
109pub static INTERNAL_COUNTER: AtomicU32 = AtomicU32::new(0);
110#[doc(hidden)]
111pub static INTERNAL_RETRY: AtomicBool = AtomicBool::new(true);
112
113/// The path of an existing writable directory in a system temporary directory.
114///
115/// Drop the struct to delete the directory and everything under it.
116/// Deletes symbolic links and does not follow them.
117///
118/// Ignores any error while deleting.
119/// See [`TempDir::panic_on_cleanup_error`](struct.TempDir.html#method.panic_on_cleanup_error).
120///
121/// # Example
122/// ```rust
123/// use temp_dir::TempDir;
124/// let d = TempDir::new().unwrap();
125/// // Prints "/tmp/t1a9b-0".
126/// println!("{:?}", d.path());
127/// let f = d.child("file1");
128/// // Prints "/tmp/t1a9b-0/file1".
129/// println!("{:?}", f);
130/// std::fs::write(&f, b"abc").unwrap();
131/// assert_eq!(
132///     "abc",
133///     std::fs::read_to_string(&f).unwrap(),
134/// );
135/// // Prints "/tmp/t1a9b-1".
136/// println!("{:?}", TempDir::new().unwrap().path());
137/// ```
138#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Debug)]
139pub struct TempDir {
140    path_buf: Option<PathBuf>,
141    panic_on_delete_err: bool,
142}
143impl TempDir {
144    fn remove_dir(path: &Path) -> Result<(), std::io::Error> {
145        match std::fs::remove_dir_all(path) {
146            Ok(()) => Ok(()),
147            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
148            Err(e) => Err(std::io::Error::new(
149                e.kind(),
150                format!("error removing directory and contents {path:?}: {e}"),
151            )),
152        }
153    }
154
155    /// Create a new empty directory in a system temporary directory.
156    ///
157    /// Drop the struct to delete the directory and everything under it.
158    /// Deletes symbolic links and does not follow them.
159    ///
160    /// Ignores any error while deleting.
161    /// See [`TempDir::panic_on_cleanup_error`](struct.TempDir.html#method.panic_on_cleanup_error).
162    ///
163    /// # Errors
164    /// Returns `Err` when it fails to create the directory.
165    ///
166    /// # Example
167    /// ```rust
168    /// // Prints "/tmp/t1a9b-0".
169    /// println!("{:?}", temp_dir::TempDir::new().unwrap().path());
170    /// ```
171    pub fn new() -> Result<Self, std::io::Error> {
172        // Prefix with 't' to avoid name collisions with `temp-file` crate.
173        Self::with_prefix("t")
174    }
175
176    /// Create a new empty directory in a system temporary directory.
177    /// Use `prefix` as the first part of the directory's name.
178    ///
179    /// Drop the struct to delete the directory and everything under it.
180    /// Deletes symbolic links and does not follow them.
181    ///
182    /// Ignores any error while deleting.
183    /// See [`TempDir::panic_on_cleanup_error`](struct.TempDir.html#method.panic_on_cleanup_error).
184    ///
185    /// # Errors
186    /// Returns `Err` when it fails to create the directory.
187    ///
188    /// # Example
189    /// ```rust
190    /// // Prints "/tmp/ok1a9b-0".
191    /// println!("{:?}", temp_dir::TempDir::with_prefix("ok").unwrap().path());
192    /// ```
193    pub fn with_prefix(prefix: impl AsRef<str>) -> Result<Self, std::io::Error> {
194        loop {
195            let path_buf = std::env::temp_dir().join(format!(
196                "{}{:x}-{:x}",
197                prefix.as_ref(),
198                std::process::id(),
199                INTERNAL_COUNTER.fetch_add(1, Ordering::AcqRel),
200            ));
201            match std::fs::create_dir(&path_buf) {
202                Err(e)
203                    if e.kind() == ErrorKind::AlreadyExists
204                        && INTERNAL_RETRY.load(Ordering::Acquire) => {}
205                Err(e) => {
206                    return Err(std::io::Error::new(
207                        e.kind(),
208                        format!("error creating directory {path_buf:?}: {e}"),
209                    ))
210                }
211                Ok(()) => {
212                    return Ok(Self {
213                        path_buf: Some(path_buf),
214                        panic_on_delete_err: false,
215                    })
216                }
217            }
218        }
219    }
220
221    /// Remove the directory and its contents now.
222    ///
223    /// # Errors
224    /// Returns an error if the directory exists and we fail to remove it and its contents.
225    #[allow(clippy::missing_panics_doc)]
226    pub fn cleanup(mut self) -> Result<(), std::io::Error> {
227        Self::remove_dir(&self.path_buf.take().unwrap())
228    }
229
230    /// Make the struct panic on drop if it hits an error while
231    /// removing the directory or its contents.
232    #[must_use]
233    pub fn panic_on_cleanup_error(mut self) -> Self {
234        self.panic_on_delete_err = true;
235        self
236    }
237
238    /// Do not delete the directory or its contents.
239    ///
240    /// This is useful when debugging a test.
241    pub fn leak(mut self) {
242        self.path_buf.take();
243    }
244
245    /// The path to the directory.
246    #[must_use]
247    #[allow(clippy::missing_panics_doc)]
248    pub fn path(&self) -> &Path {
249        self.path_buf.as_ref().unwrap()
250    }
251
252    /// The path to `name` under the directory.
253    #[must_use]
254    #[allow(clippy::missing_panics_doc)]
255    pub fn child(&self, name: impl AsRef<str>) -> PathBuf {
256        let mut result = self.path_buf.as_ref().unwrap().clone();
257        result.push(name.as_ref());
258        result
259    }
260}
261impl Drop for TempDir {
262    fn drop(&mut self) {
263        if let Some(path) = self.path_buf.take() {
264            let result = Self::remove_dir(&path);
265            if self.panic_on_delete_err {
266                if let Err(e) = result {
267                    panic!("{}", e);
268                }
269            }
270        }
271    }
272}
273impl AsRef<Path> for TempDir {
274    fn as_ref(&self) -> &Path {
275        self.path()
276    }
277}