tempdir/
lib.rs

1// Copyright 2015 The Rust Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11#![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk-v2.png",
12       html_favicon_url = "https://www.rust-lang.org/favicon.ico",
13       html_root_url = "https://docs.rs/tempdir/0.3.7")]
14#![cfg_attr(test, deny(warnings))]
15
16//! Temporary directories of files.
17//!
18//! The [`TempDir`] type creates a directory on the file system that
19//! is deleted once it goes out of scope. At construction, the
20//! `TempDir` creates a new directory with a randomly generated name
21//! and a prefix of your choosing.
22//!
23//! [`TempDir`]: struct.TempDir.html
24//! [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html
25//!
26//! # Examples
27//!
28//! ```
29//! extern crate tempdir;
30//!
31//! use std::fs::File;
32//! use std::io::{self, Write};
33//! use tempdir::TempDir;
34//!
35//! fn main() {
36//!     if let Err(_) = run() {
37//!         ::std::process::exit(1);
38//!     }
39//! }
40//!
41//! fn run() -> Result<(), io::Error> {
42//!     // Create a directory inside of `std::env::temp_dir()`, named with
43//!     // the prefix "example".
44//!     let tmp_dir = TempDir::new("example")?;
45//!     let file_path = tmp_dir.path().join("my-temporary-note.txt");
46//!     let mut tmp_file = File::create(file_path)?;
47//!     writeln!(tmp_file, "Brian was here. Briefly.")?;
48//!
49//!     // By closing the `TempDir` explicitly, we can check that it has
50//!     // been deleted successfully. If we don't close it explicitly,
51//!     // the directory will still be deleted when `tmp_dir` goes out
52//!     // of scope, but we won't know whether deleting the directory
53//!     // succeeded.
54//!     drop(tmp_file);
55//!     tmp_dir.close()?;
56//!     Ok(())
57//! }
58//! ```
59
60extern crate rand;
61extern crate remove_dir_all;
62
63use std::env;
64use std::io::{self, Error, ErrorKind};
65use std::fmt;
66use std::fs;
67use std::path::{self, PathBuf, Path};
68use rand::{thread_rng, Rng};
69use remove_dir_all::remove_dir_all;
70
71/// A directory in the filesystem that is automatically deleted when
72/// it goes out of scope.
73///
74/// The [`TempDir`] type creates a directory on the file system that
75/// is deleted once it goes out of scope. At construction, the
76/// `TempDir` creates a new directory with a randomly generated name,
77/// and with a prefix of your choosing.
78///
79/// The default constructor, [`TempDir::new`], creates directories in
80/// the location returned by [`std::env::temp_dir()`], but `TempDir`
81/// can be configured to manage a temporary directory in any location
82/// by constructing with [`TempDir::new_in`].
83///
84/// After creating a `TempDir`, work with the file system by doing
85/// standard [`std::fs`] file system operations on its [`Path`],
86/// which can be retrieved with [`TempDir::path`]. Once the `TempDir`
87/// value is dropped, the directory at the path will be deleted, along
88/// with any files and directories it contains. It is your responsibility
89/// to ensure that no further file system operations are attempted
90/// inside the temporary directory once it has been deleted.
91///
92/// Various platform-specific conditions may cause `TempDir` to fail
93/// to delete the underlying directory. It's important to ensure that
94/// handles (like [`File`] and [`ReadDir`]) to files inside the
95/// directory are dropped before the `TempDir` goes out of scope. The
96/// `TempDir` destructor will silently ignore any errors in deleting
97/// the directory; to instead handle errors call [`TempDir::close`].
98///
99/// Note that if the program exits before the `TempDir` destructor is
100/// run, such as via [`std::process::exit`], by segfaulting, or by
101/// receiving a signal like `SIGINT`, then the temporary directory
102/// will not be deleted.
103/// 
104/// [`File`]: http://doc.rust-lang.org/std/fs/struct.File.html
105/// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
106/// [`ReadDir`]: http://doc.rust-lang.org/std/fs/struct.ReadDir.html
107/// [`TempDir::close`]: struct.TempDir.html#method.close
108/// [`TempDir::new`]: struct.TempDir.html#method.new
109/// [`TempDir::new_in`]: struct.TempDir.html#method.new_in
110/// [`TempDir::path`]: struct.TempDir.html#method.path
111/// [`TempDir`]: struct.TempDir.html
112/// [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html
113/// [`std::fs`]: http://doc.rust-lang.org/std/fs/index.html
114/// [`std::process::exit`]: http://doc.rust-lang.org/std/process/fn.exit.html
115pub struct TempDir {
116    path: Option<PathBuf>,
117}
118
119// How many times should we (re)try finding an unused random name? It should be
120// enough that an attacker will run out of luck before we run out of patience.
121const NUM_RETRIES: u32 = 1 << 31;
122// How many characters should we include in a random file name? It needs to
123// be enough to dissuade an attacker from trying to preemptively create names
124// of that length, but not so huge that we unnecessarily drain the random number
125// generator of entropy.
126const NUM_RAND_CHARS: usize = 12;
127
128impl TempDir {
129    /// Attempts to make a temporary directory inside of `env::temp_dir()` whose
130    /// name will have the prefix, `prefix`. The directory and
131    /// everything inside it will be automatically deleted once the
132    /// returned `TempDir` is destroyed.
133    ///
134    /// # Errors
135    ///
136    /// If the directory can not be created, `Err` is returned.
137    ///
138    /// # Examples
139    ///
140    /// ```
141    /// use std::fs::File;
142    /// use std::io::Write;
143    /// use tempdir::TempDir;
144    ///
145    /// # use std::io;
146    /// # fn run() -> Result<(), io::Error> {
147    /// // Create a directory inside of `std::env::temp_dir()`, named with
148    /// // the prefix, "example".
149    /// let tmp_dir = TempDir::new("example")?;
150    /// let file_path = tmp_dir.path().join("my-temporary-note.txt");
151    /// let mut tmp_file = File::create(file_path)?;
152    /// writeln!(tmp_file, "Brian was here. Briefly.")?;
153    ///
154    /// // `tmp_dir` goes out of scope, the directory as well as
155    /// // `tmp_file` will be deleted here.
156    /// # Ok(())
157    /// # }
158    /// ```
159    pub fn new(prefix: &str) -> io::Result<TempDir> {
160        TempDir::new_in(&env::temp_dir(), prefix)
161    }
162
163    /// Attempts to make a temporary directory inside of `tmpdir`
164    /// whose name will have the prefix `prefix`. The directory and
165    /// everything inside it will be automatically deleted once the
166    /// returned `TempDir` is destroyed.
167    ///
168    /// # Errors
169    ///
170    /// If the directory can not be created, `Err` is returned.
171    ///
172    /// # Examples
173    ///
174    /// ```
175    /// use std::fs::{self, File};
176    /// use std::io::Write;
177    /// use tempdir::TempDir;
178    ///
179    /// # use std::io;
180    /// # fn run() -> Result<(), io::Error> {
181    /// // Create a directory inside of the current directory, named with
182    /// // the prefix, "example".
183    /// let tmp_dir = TempDir::new_in(".", "example")?;
184    /// let file_path = tmp_dir.path().join("my-temporary-note.txt");
185    /// let mut tmp_file = File::create(file_path)?;
186    /// writeln!(tmp_file, "Brian was here. Briefly.")?;
187    /// # Ok(())
188    /// # }
189    /// ```
190    pub fn new_in<P: AsRef<Path>>(tmpdir: P, prefix: &str) -> io::Result<TempDir> {
191        let storage;
192        let mut tmpdir = tmpdir.as_ref();
193        if !tmpdir.is_absolute() {
194            let cur_dir = env::current_dir()?;
195            storage = cur_dir.join(tmpdir);
196            tmpdir = &storage;
197            // return TempDir::new_in(&cur_dir.join(tmpdir), prefix);
198        }
199
200        let mut rng = thread_rng();
201        for _ in 0..NUM_RETRIES {
202            let suffix: String = rng.gen_ascii_chars().take(NUM_RAND_CHARS).collect();
203            let leaf = if !prefix.is_empty() {
204                format!("{}.{}", prefix, suffix)
205            } else {
206                // If we're given an empty string for a prefix, then creating a
207                // directory starting with "." would lead to it being
208                // semi-invisible on some systems.
209                suffix
210            };
211            let path = tmpdir.join(&leaf);
212            match fs::create_dir(&path) {
213                Ok(_) => return Ok(TempDir { path: Some(path) }),
214                Err(ref e) if e.kind() == ErrorKind::AlreadyExists => {}
215                Err(e) => return Err(e),
216            }
217        }
218
219        Err(Error::new(ErrorKind::AlreadyExists,
220                       "too many temporary directories already exist"))
221    }
222
223    /// Accesses the [`Path`] to the temporary directory.
224    ///
225    /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
226    ///
227    /// # Examples
228    ///
229    /// ```
230    /// use tempdir::TempDir;
231    ///
232    /// # use std::io;
233    /// # fn run() -> Result<(), io::Error> {
234    /// let tmp_path;
235    ///
236    /// {
237    ///    let tmp_dir = TempDir::new("example")?;
238    ///    tmp_path = tmp_dir.path().to_owned();
239    ///
240    ///    // Check that the temp directory actually exists.
241    ///    assert!(tmp_path.exists());
242    ///
243    ///    // End of `tmp_dir` scope, directory will be deleted
244    /// }
245    ///
246    /// // Temp directory should be deleted by now
247    /// assert_eq!(tmp_path.exists(), false);
248    /// # Ok(())
249    /// # }
250    /// ```
251    pub fn path(&self) -> &path::Path {
252        self.path.as_ref().unwrap()
253    }
254
255    /// Unwraps the [`Path`] contained in the `TempDir` and
256    /// returns it. This destroys the `TempDir` without deleting the
257    /// directory represented by the returned `Path`.
258    ///
259    /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
260    ///
261    /// # Examples
262    ///
263    /// ```
264    /// use std::fs;
265    /// use tempdir::TempDir;
266    ///
267    /// # use std::io;
268    /// # fn run() -> Result<(), io::Error> {
269    /// let tmp_dir = TempDir::new("example")?;
270    ///
271    /// // Convert `tmp_dir` into a `Path`, destroying the `TempDir`
272    /// // without deleting the directory.
273    /// let tmp_path = tmp_dir.into_path();
274    ///
275    /// // Delete the temporary directory ourselves.
276    /// fs::remove_dir_all(tmp_path)?;
277    /// # Ok(())
278    /// # }
279    /// ```
280    pub fn into_path(mut self) -> PathBuf {
281        self.path.take().unwrap()
282    }
283
284    /// Closes and removes the temporary directory, returing a `Result`.
285    ///
286    /// Although `TempDir` removes the directory on drop, in the destructor
287    /// any errors are ignored. To detect errors cleaning up the temporary
288    /// directory, call `close` instead.
289    ///
290    /// # Errors
291    ///
292    /// This function may return a variety of [`std::io::Error`]s that result from deleting
293    /// the files and directories contained with the temporary directory,
294    /// as well as from deleting the temporary directory itself. These errors
295    /// may be platform specific.
296    ///
297    /// [`std::io::Error`]: http://doc.rust-lang.org/std/io/struct.Error.html
298    ///
299    /// # Examples
300    ///
301    /// ```
302    /// use std::fs::File;
303    /// use std::io::Write;
304    /// use tempdir::TempDir;
305    ///
306    /// # use std::io;
307    /// # fn run() -> Result<(), io::Error> {
308    /// // Create a directory inside of `std::env::temp_dir()`, named with
309    /// // the prefix, "example".
310    /// let tmp_dir = TempDir::new("example")?;
311    /// let file_path = tmp_dir.path().join("my-temporary-note.txt");
312    /// let mut tmp_file = File::create(file_path)?;
313    /// writeln!(tmp_file, "Brian was here. Briefly.")?;
314    ///
315    /// // By closing the `TempDir` explicitly we can check that it has
316    /// // been deleted successfully. If we don't close it explicitly,
317    /// // the directory will still be deleted when `tmp_dir` goes out
318    /// // of scope, but we won't know whether deleting the directory
319    /// // succeeded.
320    /// drop(tmp_file);
321    /// tmp_dir.close()?;
322    /// # Ok(())
323    /// # }
324    /// ```
325    pub fn close(mut self) -> io::Result<()> {
326        let result = remove_dir_all(self.path());
327
328        // Prevent the Drop impl from removing the dir a second time.
329        self.path = None;
330
331        result
332    }
333}
334
335impl AsRef<Path> for TempDir {
336    fn as_ref(&self) -> &Path {
337        self.path()
338    }
339}
340
341impl fmt::Debug for TempDir {
342    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
343        f.debug_struct("TempDir")
344            .field("path", &self.path())
345            .finish()
346    }
347}
348
349impl Drop for TempDir {
350    fn drop(&mut self) {
351        // Path is `None` if `close()` or `into_path()` has been called.
352        if let Some(ref p) = self.path {
353            let _ =  remove_dir_all(p);
354        }
355    }
356}
357
358// the tests for this module need to change the path using change_dir,
359// and this doesn't play nicely with other tests so these unit tests are located
360// in src/test/run-pass/tempfile.rs