]> git.proxmox.com Git - rustc.git/blob - src/libstd/old_io/tempfile.rs
42317c7a2d4316be452817d5b0988bc00a667cad
[rustc.git] / src / libstd / old_io / tempfile.rs
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.
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 //! Temporary files and directories
12 #![allow(deprecated)] // rand
13
14 use env;
15 use iter::{IteratorExt};
16 use old_io::{fs, IoError, IoErrorKind, IoResult};
17 use old_io;
18 use ops::Drop;
19 use option::Option::{None, Some};
20 use option::Option;
21 use old_path::{Path, GenericPath};
22 use rand::{Rng, thread_rng};
23 use result::Result::{Ok, Err};
24 use str::StrExt;
25 use string::String;
26
27 /// A wrapper for a path to temporary directory implementing automatic
28 /// scope-based deletion.
29 ///
30 /// # Examples
31 ///
32 /// ```no_run
33 /// use std::old_io::TempDir;
34 ///
35 /// {
36 /// // create a temporary directory
37 /// let tmpdir = match TempDir::new("myprefix") {
38 /// Ok(dir) => dir,
39 /// Err(e) => panic!("couldn't create temporary directory: {}", e)
40 /// };
41 ///
42 /// // get the path of the temporary directory without affecting the wrapper
43 /// let tmppath = tmpdir.path();
44 ///
45 /// println!("The path of temporary directory is {}", tmppath.display());
46 ///
47 /// // the temporary directory is automatically removed when tmpdir goes
48 /// // out of scope at the end of the block
49 /// }
50 /// {
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") {
53 /// Ok(dir) => dir,
54 /// Err(e) => panic!("couldn't create temporary directory: {}", e)
55 /// };
56 ///
57 /// // get the path of the temporary directory and disable automatic deletion in the wrapper
58 /// let tmppath = tmpdir.into_inner();
59 ///
60 /// println!("The path of the not-so-temporary directory is {}", tmppath.display());
61 ///
62 /// // the temporary directory is not removed here
63 /// // because the directory is detached from the wrapper
64 /// }
65 /// {
66 /// // create a temporary directory
67 /// let tmpdir = match TempDir::new("myprefix") {
68 /// Ok(dir) => dir,
69 /// Err(e) => panic!("couldn't create temporary directory: {}", e)
70 /// };
71 ///
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)
76 /// };
77 /// }
78 /// ```
79 pub struct TempDir {
80 path: Option<Path>,
81 disarmed: bool
82 }
83
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;
92
93 impl TempDir {
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.
97 ///
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);
103 }
104
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)
110 } else {
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.
114 suffix
115 };
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)
121 }
122 }
123
124 return Err(IoError{
125 kind: IoErrorKind::PathAlreadyExists,
126 desc:"Exhausted",
127 detail: None});
128 }
129
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.
133 ///
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)
137 }
138
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()
145 }
146
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()
150 }
151
152 /// Close and remove the temporary directory
153 ///
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<()> {
158 self.cleanup_dir()
159 }
160
161 fn cleanup_dir(&mut self) -> IoResult<()> {
162 assert!(!self.disarmed);
163 self.disarmed = true;
164 match self.path {
165 Some(ref p) => {
166 fs::rmdir_recursive(p)
167 }
168 None => Ok(())
169 }
170 }
171 }
172
173 impl Drop for TempDir {
174 fn drop(&mut self) {
175 if !self.disarmed {
176 let _ = self.cleanup_dir();
177 }
178 }
179 }
180
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