1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
//! This module provides a simple way of creating temporary files and
//! directories where their lifetime is defined by the scope they exist in.
//!
//! Once the variable goes out of scope, the underlying file system resource is removed.
//!
//! # Examples
//!
//! ```
//! use mktemp::Temp;
//! use std::fs;
//!
//! {
//!   let temp_file = Temp::new_file().unwrap();
//!   assert!(fs::File::open(temp_file).is_ok());
//! }
//! // temp_file is cleaned from the fs here
//! ```
//!
extern crate uuid;

use std::env;
use std::fs;
use std::io;
use std::path::{ Path, PathBuf };
use uuid::Uuid;

#[derive(Clone)]
enum TempType {
    File,
    Dir,
}

#[derive(Clone)]
pub struct Temp {
    path: PathBuf,
    _type: TempType,
    _released: bool,
}

fn create_path() -> PathBuf {
    create_path_in(env::temp_dir())
}

fn create_path_in(path: PathBuf) -> PathBuf {
    let mut path = path;
    let dir_uuid = Uuid::new_v4();

    path.push(dir_uuid.to_simple_string());
    path
}

impl Temp {
    /// Create a temporary directory.
    pub fn new_dir() -> io::Result<Self> {
        let temp = Temp {
            path: create_path(),
            _type: TempType::Dir,
            _released: false,
        };

        try!(temp.create_dir());
        Ok(temp)
    }

    /// Create a new temporary directory in an existing directory
    pub fn new_dir_in(directory: &Path) -> io::Result<Self> {
        let temp = Temp {
            path: create_path_in(directory.to_path_buf()),
            _type: TempType::Dir,
            _released: false,
        };

        try!(temp.create_dir());
        Ok(temp)
    }

    /// Create a new temporary file in an existing directory
    pub fn new_file_in(directory: &Path) -> io::Result<Self> {
        let temp = Temp {
            path: create_path_in(directory.to_path_buf()),
            _type: TempType::File,
            _released: false,
        };

        try!(temp.create_file());
        Ok(temp)
    }

    /// Create a temporary file.
    pub fn new_file() -> io::Result<Self> {
        let temp = Temp {
            path: create_path(),
            _type: TempType::File,
            _released: false,
        };

        try!(temp.create_file());
        Ok(temp)
    }

    /// Return this temporary file or directory as a PathBuf.
    ///
    /// # Examples
    ///
    /// ```
    /// use mktemp::Temp;
    ///
    /// let temp_dir = Temp::new_dir().unwrap();
    /// let mut path_buf = temp_dir.to_path_buf();
    /// ```
    pub fn to_path_buf(&self) -> PathBuf {
        PathBuf::from(&self.path)
    }

    /// Release ownership of the temporary file or directory.
    ///
    /// # Examples
    ///
    /// ```
    /// use mktemp::Temp;
    /// let path_buf;
    /// {
    ///   let mut temp_dir = Temp::new_dir().unwrap();
    ///   path_buf = temp_dir.to_path_buf();
    ///   temp_dir.release();
    /// }
    /// assert!(path_buf.exists());
    /// ```
    pub fn release(&mut self) {
      self._released = true;
    }

    fn create_file(&self) -> io::Result<()> {
        fs::File::create(self).map(|_| ())
    }

    fn remove_file(&self) -> io::Result<()> {
        fs::remove_file(self)
    }

    fn create_dir(&self) -> io::Result<()> {
        fs::DirBuilder::new()
                       .recursive(true)
                       .create(self)
    }

    fn remove_dir(&self) -> io::Result<()> {
        fs::remove_dir_all(self)
    }
}

impl AsRef<Path> for Temp {
    fn as_ref(&self) -> &Path {
        &self.path.as_path()
    }
}

impl Drop for Temp {
    fn drop(&mut self) {
        // Drop is blocking (make non-blocking?)
        if !self._released {
          let result = match self._type {
              TempType::File => self.remove_file(),
              TempType::Dir  => self.remove_dir(),
          };

          if let Err(e) = result {
              panic!("Could not remove path {:?}: {}", self.path, e);
          }
        }
    }
}

#[test]
fn it_should_create_file_in_dir() {
    let in_dir;
    {
        let temp_dir = Temp::new_dir().unwrap();

        in_dir = temp_dir.path.clone();

        {
            let temp_file = Temp::new_file_in(in_dir.as_path()).unwrap();
            assert!(fs::metadata(temp_file).unwrap().is_file());
        }
    }
}

#[test]
fn it_should_drop_file_out_of_scope() {
    let path;
    {
        let temp_file = Temp::new_file().unwrap();

        path = temp_file.path.clone();
        assert!(fs::metadata(temp_file).unwrap().is_file());
    }

    if let Err(e) = fs::metadata(path) {
        assert_eq!(e.kind(), io::ErrorKind::NotFound);
    } else {
        panic!("File was not removed");
    }
}

#[test]
fn it_should_drop_dir_out_of_scope() {
    let path;
    {
        let temp_file = Temp::new_dir().unwrap();

        path = temp_file.path.clone();
        assert!(fs::metadata(temp_file).unwrap().is_dir());
    }

    if let Err(e) = fs::metadata(path) {
        assert_eq!(e.kind(), io::ErrorKind::NotFound);
    } else {
        panic!("File was not removed");
    }
}

#[test]
fn it_should_not_drop_released_file() {
    let path_buf;
    {
        let mut temp_file = Temp::new_file().unwrap();
        path_buf = temp_file.to_path_buf();
        temp_file.release();
    }
    assert!(path_buf.exists());
    fs::remove_file(path_buf).unwrap();
}

#[test]
fn it_should_not_drop_released_dir() {
    let path_buf;
    {
        let mut temp_dir = Temp::new_dir().unwrap();
        path_buf = temp_dir.to_path_buf();
        temp_dir.release();
    }
    assert!(path_buf.exists());
    fs::remove_dir_all(path_buf).unwrap();
}