]> git.lizzy.rs Git - rust.git/blob - src/libstd/fs/tempdir.rs
check: Reword the warning to be more prescriptive
[rust.git] / src / libstd / fs / tempdir.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 #![unstable(feature = "tempdir", reason = "needs an RFC before stabilization")]
12 #![deprecated(since = "1.0.0",
13               reason = "use the `tempdir` crate from crates.io instead")]
14 #![allow(deprecated)]
15
16 use prelude::v1::*;
17
18 use env;
19 use io::{self, Error, ErrorKind};
20 use fs;
21 use path::{self, PathBuf};
22 use rand::{thread_rng, Rng};
23
24 /// A wrapper for a path to temporary directory implementing automatic
25 /// scope-based deletion.
26 pub struct TempDir {
27     path: Option<PathBuf>,
28 }
29
30 // How many times should we (re)try finding an unused random name? It should be
31 // enough that an attacker will run out of luck before we run out of patience.
32 const NUM_RETRIES: u32 = 1 << 31;
33 // How many characters should we include in a random file name? It needs to
34 // be enough to dissuade an attacker from trying to preemptively create names
35 // of that length, but not so huge that we unnecessarily drain the random number
36 // generator of entropy.
37 const NUM_RAND_CHARS: uint = 12;
38
39 impl TempDir {
40     /// Attempts to make a temporary directory inside of `tmpdir` whose name
41     /// will have the prefix `prefix`. The directory will be automatically
42     /// deleted once the returned wrapper is destroyed.
43     ///
44     /// If no directory can be created, `Err` is returned.
45     #[allow(deprecated)] // rand usage
46     pub fn new_in<P: AsRef<path::Path>>(tmpdir: P, prefix: &str) -> io::Result<TempDir> {
47         let storage;
48         let mut tmpdir = tmpdir.as_ref();
49         if !tmpdir.is_absolute() {
50             let cur_dir = try!(env::current_dir());
51             storage = cur_dir.join(tmpdir);
52             tmpdir = &storage;
53             // return TempDir::new_in(&cur_dir.join(tmpdir), prefix);
54         }
55
56         let mut rng = thread_rng();
57         for _ in 0..NUM_RETRIES {
58             let suffix: String = rng.gen_ascii_chars().take(NUM_RAND_CHARS).collect();
59             let leaf = if prefix.len() > 0 {
60                 format!("{}.{}", prefix, suffix)
61             } else {
62                 // If we're given an empty string for a prefix, then creating a
63                 // directory starting with "." would lead to it being
64                 // semi-invisible on some systems.
65                 suffix
66             };
67             let path = tmpdir.join(&leaf);
68             match fs::create_dir(&path) {
69                 Ok(_) => return Ok(TempDir { path: Some(path) }),
70                 Err(ref e) if e.kind() == ErrorKind::AlreadyExists => {}
71                 Err(e) => return Err(e)
72             }
73         }
74
75         Err(Error::new(ErrorKind::AlreadyExists,
76                        "too many temporary directories already exist",
77                        None))
78     }
79
80     /// Attempts to make a temporary directory inside of `env::temp_dir()` whose
81     /// name will have the prefix `prefix`. The directory will be automatically
82     /// deleted once the returned wrapper is destroyed.
83     ///
84     /// If no directory can be created, `Err` is returned.
85     #[allow(deprecated)]
86     pub fn new(prefix: &str) -> io::Result<TempDir> {
87         TempDir::new_in(&env::temp_dir(), prefix)
88     }
89
90     /// Unwrap the wrapped `std::path::Path` from the `TempDir` wrapper.
91     /// This discards the wrapper so that the automatic deletion of the
92     /// temporary directory is prevented.
93     pub fn into_path(mut self) -> PathBuf {
94         self.path.take().unwrap()
95     }
96
97     /// Access the wrapped `std::path::Path` to the temporary directory.
98     pub fn path(&self) -> &path::Path {
99         self.path.as_ref().unwrap()
100     }
101
102     /// Close and remove the temporary directory
103     ///
104     /// Although `TempDir` removes the directory on drop, in the destructor
105     /// any errors are ignored. To detect errors cleaning up the temporary
106     /// directory, call `close` instead.
107     pub fn close(mut self) -> io::Result<()> {
108         self.cleanup_dir()
109     }
110
111     fn cleanup_dir(&mut self) -> io::Result<()> {
112         match self.path {
113             Some(ref p) => fs::remove_dir_all(p),
114             None => Ok(())
115         }
116     }
117 }
118
119 impl Drop for TempDir {
120     fn drop(&mut self) {
121         let _ = self.cleanup_dir();
122     }
123 }
124
125 // the tests for this module need to change the path using change_dir,
126 // and this doesn't play nicely with other tests so these unit tests are located
127 // in src/test/run-pass/tempfile.rs