summary refs log tree commit diff
path: root/tempfile/src/lib.rs
blob: c04f0f7d9f898e0e1ce6bc509939f36a7f89e2fe (plain) (blame)
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
// Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! Simplified tempfile which doesn't depend on the `rand` crate, instead using
//! /dev/urandom as a source of entropy

extern crate rand_ish;

use rand_ish::urandom_str;
use std::env;
use std::fs;
use std::io::{Error, ErrorKind, Result};
use std::path::{Path, PathBuf};

pub struct Builder {
    prefix: String,
}

impl Builder {
    pub fn new() -> Self {
        Builder {
            prefix: ".tmp".to_owned(),
        }
    }

    /// Set a custom filename prefix.
    ///
    /// Default: `.tmp`
    pub fn prefix(&mut self, prefix: &str) -> &mut Self {
        self.prefix = prefix.to_owned();
        self
    }

    /// Tries to make a tempdir inside of `env::temp_dir()` with a specified
    /// prefix. The directory and it's content is destroyed when TempDir is
    /// dropped.
    /// If the directory can not be created, `Err` is returned.
    pub fn tempdir(&self) -> Result<TempDir> {
        for _ in 0..NUM_RETRIES {
            let suffix = urandom_str(12)?;
            let path = env::temp_dir().join(format!("{}.{}", self.prefix, suffix));

            match fs::create_dir(&path) {
                Ok(_) => return Ok(TempDir { path }),
                Err(ref e) if e.kind() == ErrorKind::AlreadyExists => {}
                Err(e) => return Err(e),
            }
        }

        Err(Error::new(
            ErrorKind::AlreadyExists,
            "too many tempdirs exist",
        ))
    }
}

pub struct TempDir {
    path: PathBuf,
}

const NUM_RETRIES: u32 = 4;

impl TempDir {
    /// Accesses the tempdir's [`Path`].
    ///
    /// [`Path`]: http://doc.rust-lang.org/std/path/struct.Path.html
    pub fn path(&self) -> &Path {
        self.path.as_ref()
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.path);
    }
}