1 // Copyright 2013 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 //! Temporary files and directories
13 use io::{fs, IoResult};
18 use option::Option::{None, Some};
20 use path::{Path, GenericPath};
21 use result::Result::{Ok, Err};
24 /// A wrapper for a path to temporary directory implementing automatic
25 /// scope-based deletion.
30 /// use std::io::TempDir;
33 /// // create a temporary directory
34 /// let tmpdir = match TempDir::new("mysuffix") {
36 /// Err(e) => panic!("couldn't create temporary directory: {}", e)
39 /// // get the path of the temporary directory without affecting the wrapper
40 /// let tmppath = tmpdir.path();
42 /// println!("The path of temporary directory is {}", tmppath.display());
44 /// // the temporary directory is automatically removed when tmpdir goes
45 /// // out of scope at the end of the block
48 /// // create a temporary directory, this time using a custom path
49 /// let tmpdir = match TempDir::new_in(&Path::new("/tmp/best/custom/path"), "mysuffix") {
51 /// Err(e) => panic!("couldn't create temporary directory: {}", e)
54 /// // get the path of the temporary directory and disable automatic deletion in the wrapper
55 /// let tmppath = tmpdir.into_inner();
57 /// println!("The path of the not-so-temporary directory is {}", tmppath.display());
59 /// // the temporary directory is not removed here
60 /// // because the directory is detached from the wrapper
63 /// // create a temporary directory
64 /// let tmpdir = match TempDir::new("mysuffix") {
66 /// Err(e) => panic!("couldn't create temporary directory: {}", e)
69 /// // close the temporary directory manually and check the result
70 /// match tmpdir.close() {
71 /// Ok(_) => println!("success!"),
72 /// Err(e) => panic!("couldn't remove temporary directory: {}", e)
82 /// Attempts to make a temporary directory inside of `tmpdir` whose name
83 /// will have the suffix `suffix`. The directory will be automatically
84 /// deleted once the returned wrapper is destroyed.
86 /// If no directory can be created, `Err` is returned.
87 pub fn new_in(tmpdir: &Path, suffix: &str) -> IoResult<TempDir> {
88 if !tmpdir.is_absolute() {
89 let abs_tmpdir = try!(os::make_absolute(tmpdir));
90 return TempDir::new_in(&abs_tmpdir, suffix);
93 static CNT: atomic::AtomicUint = atomic::ATOMIC_UINT_INIT;
95 let mut attempts = 0u;
98 format!("rs-{}-{}-{}",
99 unsafe { libc::getpid() },
100 CNT.fetch_add(1, atomic::SeqCst),
102 let p = tmpdir.join(filename);
103 match fs::mkdir(&p, io::USER_RWX) {
105 if attempts >= 1000 {
110 Ok(()) => return Ok(TempDir { path: Some(p), disarmed: false })
115 /// Attempts to make a temporary directory inside of `os::tmpdir()` whose
116 /// name will have the suffix `suffix`. The directory will be automatically
117 /// deleted once the returned wrapper is destroyed.
119 /// If no directory can be created, `Err` is returned.
120 pub fn new(suffix: &str) -> IoResult<TempDir> {
121 TempDir::new_in(&os::tmpdir(), suffix)
124 /// Unwrap the wrapped `std::path::Path` from the `TempDir` wrapper.
125 /// This discards the wrapper so that the automatic deletion of the
126 /// temporary directory is prevented.
127 pub fn into_inner(self) -> Path {
128 let mut tmpdir = self;
129 tmpdir.path.take().unwrap()
132 /// Deprecated, use into_inner() instead
133 #[deprecated = "renamed to into_inner()"]
134 pub fn unwrap(self) -> Path { self.into_inner() }
136 /// Access the wrapped `std::path::Path` to the temporary directory.
137 pub fn path<'a>(&'a self) -> &'a Path {
138 self.path.as_ref().unwrap()
141 /// Close and remove the temporary directory
143 /// Although `TempDir` removes the directory on drop, in the destructor
144 /// any errors are ignored. To detect errors cleaning up the temporary
145 /// directory, call `close` instead.
146 pub fn close(mut self) -> IoResult<()> {
150 fn cleanup_dir(&mut self) -> IoResult<()> {
151 assert!(!self.disarmed);
152 self.disarmed = true;
155 fs::rmdir_recursive(p)
162 impl Drop for TempDir {
165 let _ = self.cleanup_dir();
170 // the tests for this module need to change the path using change_dir,
171 // and this doesn't play nicely with other tests so these unit tests are located
172 // in src/test/run-pass/tempfile.rs