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.
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.
11 use remove_dir_all
::remove_dir_all
;
12 use std
::path
::{self, Path, PathBuf}
;
13 use std
::{fmt, fs, io}
;
15 use crate::error
::IoResultExt
;
18 /// Create a new temporary directory.
20 /// The `tempdir` function creates a directory in the file system
21 /// and returns a [`TempDir`].
22 /// The directory will be automatically deleted when the `TempDir`s
23 /// desctructor is run.
25 /// # Resource Leaking
27 /// See [the resource leaking][resource-leaking] docs on `TempDir`.
31 /// If the directory can not be created, `Err` is returned.
36 /// use tempfile::tempdir;
37 /// use std::fs::File;
38 /// use std::io::{self, Write};
41 /// # if let Err(_) = run() {
42 /// # ::std::process::exit(1);
45 /// # fn run() -> Result<(), io::Error> {
46 /// // Create a directory inside of `std::env::temp_dir()`
47 /// let dir = tempdir()?;
49 /// let file_path = dir.path().join("my-temporary-note.txt");
50 /// let mut file = File::create(file_path)?;
51 /// writeln!(file, "Brian was here. Briefly.")?;
53 /// // `tmp_dir` goes out of scope, the directory as well as
54 /// // `tmp_file` will be deleted here.
61 /// [`TempDir`]: struct.TempDir.html
62 /// [resource-leaking]: struct.TempDir.html#resource-leaking
63 pub fn tempdir() -> io
::Result
<TempDir
> {
67 /// Create a new temporary directory.
69 /// The `tempdir` function creates a directory in the file system
70 /// and returns a [`TempDir`].
71 /// The directory will be automatically deleted when the `TempDir`s
72 /// desctructor is run.
74 /// # Resource Leaking
76 /// See [the resource leaking][resource-leaking] docs on `TempDir`.
80 /// If the directory can not be created, `Err` is returned.
85 /// use tempfile::tempdir;
86 /// use std::fs::File;
87 /// use std::io::{self, Write};
90 /// # if let Err(_) = run() {
91 /// # ::std::process::exit(1);
94 /// # fn run() -> Result<(), io::Error> {
95 /// // Create a directory inside of `std::env::temp_dir()`,
96 /// let dir = tempdir()?;
98 /// let file_path = dir.path().join("my-temporary-note.txt");
99 /// let mut file = File::create(file_path)?;
100 /// writeln!(file, "Brian was here. Briefly.")?;
102 /// // `tmp_dir` goes out of scope, the directory as well as
103 /// // `tmp_file` will be deleted here.
110 /// [`TempDir`]: struct.TempDir.html
111 /// [resource-leaking]: struct.TempDir.html#resource-leaking
112 pub fn tempdir_in
<P
: AsRef
<Path
>>(dir
: P
) -> io
::Result
<TempDir
> {
116 /// A directory in the filesystem that is automatically deleted when
117 /// it goes out of scope.
119 /// The [`TempDir`] type creates a directory on the file system that
120 /// is deleted once it goes out of scope. At construction, the
121 /// `TempDir` creates a new directory with a randomly generated name.
123 /// The default constructor, [`TempDir::new()`], creates directories in
124 /// the location returned by [`std::env::temp_dir()`], but `TempDir`
125 /// can be configured to manage a temporary directory in any location
126 /// by constructing with a [`Builder`].
128 /// After creating a `TempDir`, work with the file system by doing
129 /// standard [`std::fs`] file system operations on its [`Path`],
130 /// which can be retrieved with [`TempDir::path()`]. Once the `TempDir`
131 /// value is dropped, the directory at the path will be deleted, along
132 /// with any files and directories it contains. It is your responsibility
133 /// to ensure that no further file system operations are attempted
134 /// inside the temporary directory once it has been deleted.
136 /// # Resource Leaking
138 /// Various platform-specific conditions may cause `TempDir` to fail
139 /// to delete the underlying directory. It's important to ensure that
140 /// handles (like [`File`] and [`ReadDir`]) to files inside the
141 /// directory are dropped before the `TempDir` goes out of scope. The
142 /// `TempDir` destructor will silently ignore any errors in deleting
143 /// the directory; to instead handle errors call [`TempDir::close()`].
145 /// Note that if the program exits before the `TempDir` destructor is
146 /// run, such as via [`std::process::exit()`], by segfaulting, or by
147 /// receiving a signal like `SIGINT`, then the temporary directory
148 /// will not be deleted.
152 /// Create a temporary directory with a generated name:
155 /// use std::fs::File;
156 /// use std::io::Write;
157 /// use tempfile::TempDir;
160 /// # fn run() -> Result<(), io::Error> {
161 /// // Create a directory inside of `std::env::temp_dir()`
162 /// let tmp_dir = TempDir::new()?;
167 /// Create a temporary directory with a prefix in its name:
170 /// use std::fs::File;
171 /// use std::io::Write;
172 /// use tempfile::Builder;
175 /// # fn run() -> Result<(), io::Error> {
176 /// // Create a directory inside of `std::env::temp_dir()`,
177 /// // whose name will begin with 'example'.
178 /// let tmp_dir = Builder::new().prefix("example").tempdir()?;
183 /// [`File`]: http://doc.rust-lang.org/std/fs/struct.File.html
184 /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
185 /// [`ReadDir`]: http://doc.rust-lang.org/std/fs/struct.ReadDir.html
186 /// [`Builder`]: struct.Builder.html
187 /// [`TempDir::close()`]: struct.TempDir.html#method.close
188 /// [`TempDir::new()`]: struct.TempDir.html#method.new
189 /// [`TempDir::path()`]: struct.TempDir.html#method.path
190 /// [`TempDir`]: struct.TempDir.html
191 /// [`std::env::temp_dir()`]: https://doc.rust-lang.org/std/env/fn.temp_dir.html
192 /// [`std::fs`]: http://doc.rust-lang.org/std/fs/index.html
193 /// [`std::process::exit()`]: http://doc.rust-lang.org/std/process/fn.exit.html
195 path
: Option
<PathBuf
>,
199 /// Attempts to make a temporary directory inside of `env::temp_dir()`.
201 /// See [`Builder`] for more configuration.
203 /// The directory and everything inside it will be automatically deleted
204 /// once the returned `TempDir` is destroyed.
208 /// If the directory can not be created, `Err` is returned.
213 /// use std::fs::File;
214 /// use std::io::Write;
215 /// use tempfile::TempDir;
218 /// # fn run() -> Result<(), io::Error> {
219 /// // Create a directory inside of `std::env::temp_dir()`
220 /// let tmp_dir = TempDir::new()?;
222 /// let file_path = tmp_dir.path().join("my-temporary-note.txt");
223 /// let mut tmp_file = File::create(file_path)?;
224 /// writeln!(tmp_file, "Brian was here. Briefly.")?;
226 /// // `tmp_dir` goes out of scope, the directory as well as
227 /// // `tmp_file` will be deleted here.
232 /// [`Builder`]: struct.Builder.html
233 pub fn new() -> io
::Result
<TempDir
> {
234 Builder
::new().tempdir()
237 /// Attempts to make a temporary directory inside of `dir`.
238 /// The directory and everything inside it will be automatically
239 /// deleted once the returned `TempDir` is destroyed.
243 /// If the directory can not be created, `Err` is returned.
248 /// use std::fs::{self, File};
249 /// use std::io::Write;
250 /// use tempfile::TempDir;
253 /// # fn run() -> Result<(), io::Error> {
254 /// // Create a directory inside of the current directory
255 /// let tmp_dir = TempDir::new_in(".")?;
256 /// let file_path = tmp_dir.path().join("my-temporary-note.txt");
257 /// let mut tmp_file = File::create(file_path)?;
258 /// writeln!(tmp_file, "Brian was here. Briefly.")?;
262 pub fn new_in
<P
: AsRef
<Path
>>(dir
: P
) -> io
::Result
<TempDir
> {
263 Builder
::new().tempdir_in(dir
)
266 /// Accesses the [`Path`] to the temporary directory.
268 /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
273 /// use tempfile::TempDir;
276 /// # fn run() -> Result<(), io::Error> {
280 /// let tmp_dir = TempDir::new()?;
281 /// tmp_path = tmp_dir.path().to_owned();
283 /// // Check that the temp directory actually exists.
284 /// assert!(tmp_path.exists());
286 /// // End of `tmp_dir` scope, directory will be deleted
289 /// // Temp directory should be deleted by now
290 /// assert_eq!(tmp_path.exists(), false);
294 pub fn path(&self) -> &path
::Path
{
295 self.path
.as_ref().unwrap()
298 /// Persist the temporary directory to disk, returning the [`PathBuf`] where it is located.
300 /// This consumes the [`TempDir`] without deleting directory on the filesystem, meaning that
301 /// the directory will no longer be automatically deleted.
303 /// [`TempDir`]: struct.TempDir.html
304 /// [`PathBuf`]: http://doc.rust-lang.org/std/path/struct.PathBuf.html
310 /// use tempfile::TempDir;
313 /// # fn run() -> Result<(), io::Error> {
314 /// let tmp_dir = TempDir::new()?;
316 /// // Persist the temporary directory to disk,
317 /// // getting the path where it is.
318 /// let tmp_path = tmp_dir.into_path();
320 /// // Delete the temporary directory ourselves.
321 /// fs::remove_dir_all(tmp_path)?;
325 pub fn into_path(mut self) -> PathBuf
{
326 self.path
.take().unwrap()
329 /// Closes and removes the temporary directory, returing a `Result`.
331 /// Although `TempDir` removes the directory on drop, in the destructor
332 /// any errors are ignored. To detect errors cleaning up the temporary
333 /// directory, call `close` instead.
337 /// This function may return a variety of [`std::io::Error`]s that result from deleting
338 /// the files and directories contained with the temporary directory,
339 /// as well as from deleting the temporary directory itself. These errors
340 /// may be platform specific.
342 /// [`std::io::Error`]: http://doc.rust-lang.org/std/io/struct.Error.html
347 /// use std::fs::File;
348 /// use std::io::Write;
349 /// use tempfile::TempDir;
352 /// # fn run() -> Result<(), io::Error> {
353 /// // Create a directory inside of `std::env::temp_dir()`.
354 /// let tmp_dir = TempDir::new()?;
355 /// let file_path = tmp_dir.path().join("my-temporary-note.txt");
356 /// let mut tmp_file = File::create(file_path)?;
357 /// writeln!(tmp_file, "Brian was here. Briefly.")?;
359 /// // By closing the `TempDir` explicitly we can check that it has
360 /// // been deleted successfully. If we don't close it explicitly,
361 /// // the directory will still be deleted when `tmp_dir` goes out
362 /// // of scope, but we won't know whether deleting the directory
365 /// tmp_dir.close()?;
369 pub fn close(mut self) -> io
::Result
<()> {
370 let result
= remove_dir_all(self.path()).with_err_path(|| self.path());
372 // Prevent the Drop impl from removing the dir a second time.
379 impl AsRef
<Path
> for TempDir
{
380 fn as_ref(&self) -> &Path
{
385 impl fmt
::Debug
for TempDir
{
386 fn fmt(&self, f
: &mut fmt
::Formatter
<'_
>) -> fmt
::Result
{
387 f
.debug_struct("TempDir")
388 .field("path", &self.path())
393 impl Drop
for TempDir
{
395 // Path is `None` if `close()` or `into_path()` has been called.
396 if let Some(ref p
) = self.path
{
397 let _
= remove_dir_all(p
);
402 pub(crate) fn create(path
: PathBuf
) -> io
::Result
<TempDir
> {
403 fs
::create_dir(&path
)
404 .with_err_path(|| &path
)
405 .map(|_
| TempDir { path: Some(path) }
)