about summary refs log tree commit diff
path: root/pkgs/sternenseemann/rust/temp.rs
blob: de8627ca1ab5a4d11e82beb3f9c5b1ae8579708d (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
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
//! Tiny temp dir/file crate.
//!
//! This crate implements a tiny rust wrapper around libc's
//! `mkdtemp(3)` and `mkstemp(3)` which has the following
//! notable features:
//!
//! * Temporary files and directories are distinguished on
//!   the type level: [`TempDir`] and [`TempFile`] are different
//!   types to ensure the right kind of temporary artifact
//!   is passed to a function and dealt with accordingly.
//! * The killer feature: Temporary artifacts are automatically
//!   deleted as soon as the associated value goes out of
//!   scope using the [`Drop`] trait, meaning a) it is impossible
//!   to forget to delete a temporary artifact and b) temporary
//!   artifact are cleaned up as soon as possible.
//!
//! The intended use of this crate is to create the desired
//! artifact via [`TempDir::new()`] or [`TempFile::new()`].
//! Interfacing with the rest of rust's `std` is possible by using
//! the [`AsRef`] trait to get a [`Path`] reference for a given
//! temporary artifact.
//!
//! Note that you need to take care not to let the [`TempDir`] or
//! [`TempFile`] get dropped early while you are still using a copy
//! of the represented path which can easily happen when using
//! `temp_dir.as_ref().join("foo.txt")` to work with a temporary
//! directory.
use std::ffi::OsStr;
use std::io::{Error, ErrorKind};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::path::Path;

// libc interaction

#[link(name = "c")]
extern {
    fn mkdtemp(template: *mut u8) -> *mut u8;
    fn mkstemp(template: *mut u8) -> *mut u8;
}

fn template(prefix: &str) -> std::io::Result<Vec<u8>> {
    if prefix.contains('/') {
        return Err(Error::new(ErrorKind::Other, "prefix may not contain any slashes"));
    }

    // TODO(sterni): systemd support
    let mut template = std::env::temp_dir();
    template.push(prefix);

    // mkdtemp and mkstemp require the template to end in 6 or more 'X's
    template.set_extension("XXXXXX");

    Ok(template.into_os_string().into_vec())
}

// internal implementation for files and directories

enum TempKind {
    File,
    Dir,
}

struct Temp {
    path: Vec<u8>,
    kind: TempKind,
}

impl AsRef<Path> for Temp {
    fn as_ref(&self) -> &Path {
        OsStr::from_bytes(&self.path[..]).as_ref()
    }
}

impl Drop for Temp {
    fn drop(&mut self) {
        let _ = match self.kind {
            TempKind::File => std::fs::remove_file(self.as_ref()),
            TempKind::Dir => std::fs::remove_dir_all(self.as_ref()),
        };
    }
}

fn temp(kind: TempKind, prefix: &str) -> std::io::Result<Temp> {
    let mut tpl = template(prefix)?;
    tpl.push(0);
    let tpl_ptr: *mut u8 = tpl.as_mut_ptr();


    let res: *mut u8 = match kind {
        TempKind::Dir => unsafe { mkdtemp(tpl_ptr) },
        TempKind::File => unsafe { mkstemp(tpl_ptr) },
    };

    if res.is_null() {
        Err(Error::last_os_error())
    } else {
        // get rid of NUL byte
        tpl.pop();

        Ok(Temp {
            path: tpl,
            kind: kind,
        })
    }
}

// public, type safe API which wraps the internal one

pub struct TempDir(Temp);

impl TempDir {
    /// Create a temporary directory in the directory returned
    /// by [`std::env::temp_dir()`]. The temporary directory's
    /// name will have the following form: `<prefix>.XXXXXX`.
    /// The six `X`s are replaced by random characters.
    ///
    /// See `mkdtemp(3)` for details of the underlying
    /// implementation and possible errors.
    pub fn new(prefix: &str) -> std::io::Result<TempDir> {
        temp(TempKind::Dir, prefix).map(|t| TempDir(t))
    }
}

impl AsRef<Path> for TempDir {
    fn as_ref(&self) -> &Path {
        self.0.as_ref()
    }
}

pub struct TempFile(Temp);

impl TempFile {
    /// Create a temporary file in the directory returned
    /// by [`std::env::temp_dir()`]. The temporary file's
    /// name will have the following form: `<prefix>.XXXXXX`.
    /// The six `X`s are replaced by random characters.
    ///
    /// See `mkstemp(3)` for details of the underlying
    /// implementation and possible errors.
    pub fn new(prefix: &str) -> std::io::Result<TempFile> {
        temp(TempKind::File, prefix).map(|t| TempFile(t))
    }
}

impl AsRef<Path> for TempFile {
    fn as_ref(&self) -> &Path {
        self.0.as_ref()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Check that the temporary artifact is
    //
    //   * created as expected
    //   * deleted after it goes out of scope
    //
    // for both temp files and temp dirs.

    #[test]
    fn tempdir_exists() {
        let temp = TempDir::new("temp-dir-test");
        assert!(temp.map(|p| p.as_ref().exists()).unwrap())
    }

    #[test]
    fn tempdir_cleaned() {
        let temp_copy = {
            let temp = TempDir::new("temp-dir-test").unwrap();
            temp.as_ref().to_path_buf()
        };
        assert!(!temp_copy.exists())
    }

    #[test]
    fn tempfile_exists() {
        let temp = TempFile::new("temp-file-test");
        assert!(temp.map(|p| p.as_ref().exists()).unwrap())
    }

    #[test]
    fn tempfile_cleaned() {
        let temp_copy = {
            let temp = TempFile::new("temp-file-test").unwrap();
            temp.as_ref().to_path_buf()
        };
        assert!(!temp_copy.exists())
    }
}