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
12 #![allow(deprecated)] // rand
15 use iter
::{IteratorExt}
;
16 use old_io
::{fs, IoError, IoErrorKind, IoResult}
;
19 use option
::Option
::{None, Some}
;
21 use old_path
::{Path, GenericPath}
;
22 use rand
::{Rng, thread_rng}
;
23 use result
::Result
::{Ok, Err}
;
27 /// A wrapper for a path to temporary directory implementing automatic
28 /// scope-based deletion.
33 /// use std::old_io::TempDir;
36 /// // create a temporary directory
37 /// let tmpdir = match TempDir::new("myprefix") {
39 /// Err(e) => panic!("couldn't create temporary directory: {}", e)
42 /// // get the path of the temporary directory without affecting the wrapper
43 /// let tmppath = tmpdir.path();
45 /// println!("The path of temporary directory is {}", tmppath.display());
47 /// // the temporary directory is automatically removed when tmpdir goes
48 /// // out of scope at the end of the block
51 /// // create a temporary directory, this time using a custom path
52 /// let tmpdir = match TempDir::new_in(&Path::new("/tmp/best/custom/path"), "myprefix") {
54 /// Err(e) => panic!("couldn't create temporary directory: {}", e)
57 /// // get the path of the temporary directory and disable automatic deletion in the wrapper
58 /// let tmppath = tmpdir.into_inner();
60 /// println!("The path of the not-so-temporary directory is {}", tmppath.display());
62 /// // the temporary directory is not removed here
63 /// // because the directory is detached from the wrapper
66 /// // create a temporary directory
67 /// let tmpdir = match TempDir::new("myprefix") {
69 /// Err(e) => panic!("couldn't create temporary directory: {}", e)
72 /// // close the temporary directory manually and check the result
73 /// match tmpdir.close() {
74 /// Ok(_) => println!("success!"),
75 /// Err(e) => panic!("couldn't remove temporary directory: {}", e)
84 // How many times should we (re)try finding an unused random name? It should be
85 // enough that an attacker will run out of luck before we run out of patience.
86 const NUM_RETRIES
: u32 = 1 << 31;
87 // How many characters should we include in a random file name? It needs to
88 // be enough to dissuade an attacker from trying to preemptively create names
89 // of that length, but not so huge that we unnecessarily drain the random number
90 // generator of entropy.
91 const NUM_RAND_CHARS
: uint
= 12;
94 /// Attempts to make a temporary directory inside of `tmpdir` whose name
95 /// will have the prefix `prefix`. The directory will be automatically
96 /// deleted once the returned wrapper is destroyed.
98 /// If no directory can be created, `Err` is returned.
99 pub fn new_in(tmpdir
: &Path
, prefix
: &str) -> IoResult
<TempDir
> {
100 if !tmpdir
.is_absolute() {
101 let cur_dir
= try
!(env
::current_dir());
102 return TempDir
::new_in(&cur_dir
.join(tmpdir
), prefix
);
105 let mut rng
= thread_rng();
106 for _
in 0..NUM_RETRIES
{
107 let suffix
: String
= rng
.gen_ascii_chars().take(NUM_RAND_CHARS
).collect();
108 let leaf
= if prefix
.len() > 0 {
109 format
!("{}.{}", prefix
, suffix
)
111 // If we're given an empty string for a prefix, then creating a
112 // directory starting with "." would lead to it being
113 // semi-invisible on some systems.
116 let path
= tmpdir
.join(leaf
);
117 match fs
::mkdir(&path
, old_io
::USER_RWX
) {
118 Ok(_
) => return Ok(TempDir { path: Some(path), disarmed: false }
),
119 Err(IoError{kind:IoErrorKind::PathAlreadyExists,..}
) => (),
120 Err(e
) => return Err(e
)
125 kind
: IoErrorKind
::PathAlreadyExists
,
130 /// Attempts to make a temporary directory inside of `os::tmpdir()` whose
131 /// name will have the prefix `prefix`. The directory will be automatically
132 /// deleted once the returned wrapper is destroyed.
134 /// If no directory can be created, `Err` is returned.
135 pub fn new(prefix
: &str) -> IoResult
<TempDir
> {
136 TempDir
::new_in(&env
::temp_dir(), prefix
)
139 /// Unwrap the wrapped `std::path::Path` from the `TempDir` wrapper.
140 /// This discards the wrapper so that the automatic deletion of the
141 /// temporary directory is prevented.
142 pub fn into_inner(self) -> Path
{
143 let mut tmpdir
= self;
144 tmpdir
.path
.take().unwrap()
147 /// Access the wrapped `std::path::Path` to the temporary directory.
148 pub fn path
<'a
>(&'a
self) -> &'a Path
{
149 self.path
.as_ref().unwrap()
152 /// Close and remove the temporary directory
154 /// Although `TempDir` removes the directory on drop, in the destructor
155 /// any errors are ignored. To detect errors cleaning up the temporary
156 /// directory, call `close` instead.
157 pub fn close(mut self) -> IoResult
<()> {
161 fn cleanup_dir(&mut self) -> IoResult
<()> {
162 assert
!(!self.disarmed
);
163 self.disarmed
= true;
166 fs
::rmdir_recursive(p
)
173 impl Drop
for TempDir
{
176 let _
= self.cleanup_dir();
181 // the tests for this module need to change the path using change_dir,
182 // and this doesn't play nicely with other tests so these unit tests are located
183 // in src/test/run-pass/tempfile.rs