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