tempfs 0.13.11

A lightweight Rust crate for managing temporary files and directories with automatic cleanup.
Documentation
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
#[cfg(feature = "rand_gen")]
use crate::global_consts::{num_retry, rand_fn_len, valid_chars};
#[cfg(feature = "mmap_support")]
use memmap2::{Mmap, MmapMut, MmapOptions};
#[cfg(feature = "rand_gen")]
use rand::Rng;
#[cfg(feature = "display_files")]
use std::fmt::Display;
use std::fmt::{Debug, Formatter};
#[cfg(unix)]
use std::fs::Permissions;
use std::fs::{File, OpenOptions};
use std::io::{self, IoSlice, IoSliceMut, Read, Seek, SeekFrom, Write};
use std::ops::{Deref, DerefMut};
#[cfg(unix)]
use std::os::fd::{AsRawFd, RawFd};
use std::path::{Path, PathBuf};
use std::{env, fs};

use crate::error::{TempError, TempResult};
use crate::helpers::normalize_path;

/// A temporary file that is automatically deleted when dropped unless explicitly closed.
///
/// The file is opened with read and write permissions. When the instance is dropped,
/// the underlying file is removed unless deletion is disarmed (for example, by calling
/// [`close`](TempFile::close) or [`into_inner`](TempFile::into_inner)).
pub struct TempFile {
    /// The full path to the temporary file.
    pub(crate) path: Option<PathBuf>,
    /// The underlying file handle.
    file: Option<File>,
    /// Directories created to hold the temporary file that did not exist.
    created_parent: Option<PathBuf>,
}

impl TempFile {
    /// Creates a new temporary file at the specified path.
    ///
    /// The file is created with read and write permissions.
    ///
    /// # Arguments
    ///
    /// * `path` - The path at which to create the file. If a relative path is provided, it is resolved relative to the system temporary directory.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be created.
    pub fn new<P: AsRef<Path>>(path: P) -> TempResult<TempFile> {
        let path_ref = normalize_path(path.as_ref());
        let path_buf = if path_ref.is_absolute() {
            path_ref
        } else {
            env::temp_dir().join(path_ref)
        };
        let (created, file) = Self::open(&path_buf)?;
        Ok(Self {
            path: Some(path_buf),
            file: Some(file),
            created_parent: created,
        })
    }

    /// Creates a new temporary file at the specified path.
    ///
    /// The file is created with read and write permissions.
    ///
    /// # Arguments
    ///
    /// * `path` - The path at which to create the file. If a relative path is provided, it is resolved relative to the current working directory.
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be created.
    pub fn new_here<P: AsRef<Path>>(path: P) -> TempResult<TempFile> {
        let path_ref = normalize_path(path.as_ref());
        let path_buf = if path_ref.is_absolute() {
            path_ref
        } else {
            env::current_dir()?.join(path_ref)
        };
        let (created, file) = Self::open(&path_buf)?;
        Ok(Self {
            path: Some(path_buf),
            file: Some(file),
            created_parent: created,
        })
    }

    /// Converts the `TempFile` into a permanent file.
    ///
    /// # Errors
    ///
    /// Returns an error if the inner file is `None`.
    pub fn persist(&mut self) -> TempResult<File> {
        self.path = None;
        self.file.take().ok_or(TempError::FileIsNone)
    }

    /// Renames the temporary file and then persists it.
    ///
    /// # Errors
    ///
    /// Returns an error if renaming or persisting the file fails.
    pub fn persist_name<S: AsRef<str>>(&mut self, name: S) -> TempResult<File> {
        self.rename(name.as_ref())?;
        self.persist()
    }

    /// Renames the temporary file (in the current directory) and persists it.
    ///
    /// # Errors
    ///
    /// Returns an error if renaming or persisting the file fails.
    pub fn persist_here<S: AsRef<str>>(&mut self, name: S) -> TempResult<File> {
        self.rename(env::current_dir()?.join(name.as_ref()))?;
        self.persist()
    }

    #[cfg(feature = "rand_gen")]
    /// Creates a new temporary file with a random name in the given directory.
    ///
    /// The file name is generated using random ASCII characters.
    ///
    /// # Arguments
    ///
    /// * `dir` - The directory in which to create the file. If `None`, the system temporary directory is used. If a relative directory is provided, it is resolved relative to the system temporary directory.
    ///
    /// # Errors
    ///
    /// Returns an error if a unique filename cannot be generated or if file creation fails.
    pub fn new_random<P: AsRef<Path>>(dir: Option<P>) -> TempResult<Self> {
        let dir_buf = if let Some(d) = dir {
            let path_ref = normalize_path(d.as_ref());
            if path_ref.is_absolute() {
                path_ref
            } else {
                env::temp_dir().join(path_ref)
            }
        } else {
            env::temp_dir()
        };
        let mut rng = rand::rng();
        for _ in 0..num_retry() {
            let name: String = (0..rand_fn_len())
                .map(|_| {
                    let idx = rng.random_range(0..valid_chars().len());
                    valid_chars()[idx] as char
                })
                .collect();
            let full_path = dir_buf.join(&name);
            if !full_path.exists() {
                let (created, file) = Self::open(&full_path)?;
                return Ok(Self {
                    path: Some(full_path),
                    file: Some(file),
                    created_parent: created,
                });
            }
        }
        Err(io::Error::new(
            io::ErrorKind::AlreadyExists,
            "Could not generate a unique filename",
        )
        .into())
    }

    #[cfg(feature = "rand_gen")]
    /// Creates a new temporary file with a random name in the given directory.
    ///
    /// The file name is generated using random ASCII characters.
    ///
    /// # Arguments
    ///
    /// * `dir` - The directory in which to create the file. If `None`, the current working directory is used. If a relative directory is provided, it is resolved relative to the current directory.
    ///
    /// # Errors
    ///
    /// Returns an error if a unique filename cannot be generated or if file creation fails.
    pub fn new_random_here<P: AsRef<Path>>(dir: Option<P>) -> TempResult<Self> {
        if let Some(dir) = dir {
            let d_ref = normalize_path(dir.as_ref());
            if d_ref.is_absolute() {
                Self::new_random(Some(d_ref))
            } else {
                Self::new_random(Some(env::current_dir()?.join(d_ref)))
            }
        } else {
            Self::new_random(Some(&env::current_dir()?))
        }
    }

    /// Opens a new file at the specified path, creating any missing parent directories if necessary.
    ///
    /// If the file already exists, an error is returned. On success, this function returns a tuple containing:
    /// - An `Option<PathBuf>` representing the created directory (if any),
    /// - The newly created file handle.
    fn open(path: &Path) -> TempResult<(Option<PathBuf>, File)> {
        #[cfg(unix)]
        use std::os::unix::fs::PermissionsExt;
        let mut created = None;
        let par = path.parent();
        if path.exists() {
            return Err(TempError::FileExists(path.to_path_buf()));
        } else if let Some(c) = crate::helpers::first_missing_directory_component(path) {
            fs::create_dir_all(par.unwrap())?;
            created = Some(c);
        }
        let file = OpenOptions::new()
            .create_new(true)
            .read(true)
            .write(true)
            .open(path)
            .map_err(Into::into);
        if file.is_err() && created.is_some() {
            fs::remove_dir_all(created.clone().unwrap())?;
        }
        #[cfg(unix)]
        fs::set_permissions(path, Permissions::from_mode(0o700))?;
        file.map(|file| (created, file))
    }

    /// Returns a mutable reference to the file handle.
    ///
    /// # Errors
    ///
    /// Returns `Err(TempError::FileIsNone)` if the file handle is not available.
    pub fn file_mut(&mut self) -> TempResult<&mut File> {
        self.file.as_mut().ok_or(TempError::FileIsNone)
    }

    /// Returns an immutable reference to the file handle.
    ///
    /// # Errors
    ///
    /// Returns `Err(TempError::FileIsNone)` if the file handle is not available.
    pub fn file(&self) -> TempResult<&File> {
        self.file.as_ref().ok_or(TempError::FileIsNone)
    }

    /// Returns the path to the temporary file.
    #[must_use]
    pub fn path(&self) -> Option<&Path> {
        self.path.as_deref()
    }

    /// Copies the temporary file to a new path and deletes the original file, "renaming" it.
    ///
    /// # Arguments
    ///
    /// * `new_path` - The new path for the file. If `new_path` is relative, it is appended to the old file's parent directory.
    ///
    /// # Errors
    ///
    /// Returns an error if the file copy or deletion operation fails, or if the old file's parent directory cannot be determined when `new_path` is relative.
    pub fn rename<P: AsRef<Path>>(&mut self, new_path: P) -> TempResult<()> {
        let mut new_path = normalize_path(new_path.as_ref());
        let pat = new_path.to_str().unwrap_or("");
        let mut mod_path = false;
        if !pat.contains('/') && !pat.contains('\\') {
            mod_path = true;
        }
        if let Some(ref old_path) = self.path {
            if mod_path {
                new_path = old_path
                    .parent()
                    .ok_or(TempError::IO(io::Error::new(
                        io::ErrorKind::NotFound,
                        "Old path parent not found",
                    )))?
                    .join(new_path);
            }
            fs::copy(old_path, new_path.clone())?;
            fs::remove_file(old_path)?;
            self.path = Some(new_path);
        }
        Ok(())
    }

    /// Copies the temporary file to a new path in the current directory and deletes the original file, "renaming" it.
    ///
    /// # Arguments
    ///
    /// * `new_path` - The new path for the file. If `new_path` is relative, it is resolved relative to the current working directory.
    ///
    /// # Errors
    ///
    /// Returns an error if the file copy or deletion operation fails.
    pub fn rename_here<P: AsRef<Path>>(&mut self, new_path: P) -> TempResult<()> {
        let mut new_path = normalize_path(new_path.as_ref());
        let pat = new_path.to_str().unwrap_or("");
        let mut mod_path = false;
        if !pat.contains('/') && !pat.contains('\\') {
            mod_path = true;
        }
        if let Some(ref old_path) = self.path {
            if mod_path {
                new_path = env::current_dir()?.join(new_path);
            }
            fs::copy(old_path, new_path.clone())?;
            fs::remove_file(old_path)?;
            self.path = Some(new_path);
        }
        Ok(())
    }

    /// Synchronizes the file’s state with the storage device.
    ///
    /// This is generally not needed. See [`File::sync_all`] for its purpose.
    ///
    /// # Errors
    ///
    /// Returns `Err(TempError::FileIsNone)` if the file handle is not available, or if syncing fails.
    pub fn sync_all(&self) -> TempResult<()> {
        self.file()?.sync_all().map_err(Into::into)
    }

    /// Flushes the file and disarms automatic deletion.
    ///
    /// After calling this method, the file will not be deleted when the `TempFile` is dropped.
    ///
    /// # Errors
    ///
    /// Returns an error if flushing fails or if the file handle is not available.
    pub fn disarm(mut self) -> TempResult<()> {
        self.file_mut()?.flush().map_err(Into::<TempError>::into)?;
        self.path = None;
        Ok(())
    }

    /// Flushes and closes the file, disarming deletion.
    ///
    /// After calling this method, the file will not be deleted when the `TempFile` is dropped.
    ///
    /// # Errors
    ///
    /// Returns an error if flushing fails or if the file handle is not available.
    pub fn close(mut self) -> TempResult<()> {
        self.file_mut()?.flush().map_err(Into::<TempError>::into)?;
        self.path = None;
        self.file = None;
        Ok(())
    }

    /// Consumes the `TempFile` and returns the inner file handle.
    ///
    /// This method disarms automatic deletion.
    ///
    /// # Errors
    ///
    /// Returns `Err(TempError::FileIsNone)` if the file handle has already been taken.
    pub fn into_inner(mut self) -> TempResult<File> {
        self.path = None;
        self.file.take().ok_or(TempError::FileIsNone)
    }

    /// Checks if the file is still active.
    #[must_use]
    pub fn is_active(&self) -> bool {
        self.path.is_some()
    }

    /// Deletes the temporary file immediately.
    ///
    /// This method flushes the file, removes it from the filesystem, and disarms automatic deletion.
    ///
    /// # Errors
    ///
    /// Returns an error if flushing fails, if the file handle is not available, or if file removal fails.
    pub fn delete(mut self) -> TempResult<()> {
        self.file_mut()?.flush().map_err(Into::<TempError>::into)?;
        if let Some(ref path) = self.path {
            fs::remove_file(path)?;
            self.path = None;
        }
        Ok(())
    }

    /// Retrieves metadata of the file.
    ///
    /// # Errors
    ///
    /// Returns an error if the metadata cannot be accessed or if the file has been closed.
    pub fn metadata(&self) -> TempResult<fs::Metadata> {
        if let Some(ref path) = self.path {
            fs::metadata(path).map_err(Into::into)
        } else {
            Err(Into::into(io::Error::new(
                io::ErrorKind::NotFound,
                "File has been closed",
            )))
        }
    }

    /// A function to convert a normal File and its path into a `TempFile`.
    ///
    /// # Errors
    ///
    /// Returns an error if the Path and File do not point to the same file.
    #[cfg(unix)]
    pub fn from_fp<P: AsRef<Path>>(file: File, path: P) -> TempResult<Self> {
        if !Self::are_same_file(path.as_ref(), &file)? {
            return Err(TempError::InvalidFileOrPath);
        }
        Ok(Self {
            path: Some(path.as_ref().to_path_buf()),
            file: Some(file),
            created_parent: None,
        })
    }

    /// Helper function to validate that a given &Path and File both point to the same file.
    #[cfg(unix)]
    fn are_same_file(path: &Path, file: &File) -> io::Result<bool> {
        use std::fs::metadata;
        use std::os::unix::fs::MetadataExt;
        let path_metadata = metadata(path)?;
        let file_metadata = file.metadata()?;

        #[cfg(unix)]
        {
            // Compare device and inode
            Ok(path_metadata.dev() == file_metadata.dev()
                && path_metadata.ino() == file_metadata.ino())
        }
    }
}

#[cfg(feature = "mmap_support")]
impl TempFile {
    /// Creates a read-only memory map of the file.
    ///
    /// # Safety
    ///
    /// This operation is unsafe because it relies on the underlying file not changing unexpectedly.
    ///
    /// # Errors
    ///
    /// Returns an error if mapping the file fails.
    pub unsafe fn mmap(&self) -> TempResult<Mmap> {
        let file = self.file()?;
        unsafe { MmapOptions::new().map(file).map_err(Into::into) }
    }

    /// Creates a mutable memory map of the file.
    ///
    /// # Safety
    ///
    /// This operation is unsafe because it allows mutable access to the file's contents.
    ///
    /// # Errors
    ///
    /// Returns an error if mapping the file fails.
    pub unsafe fn mmap_mut(&mut self) -> TempResult<MmapMut> {
        let file = self.file_mut()?;
        unsafe {
            MmapOptions::new()
                .map_mut(Self::immut(file))
                .map_err(Into::into)
        }
    }

    // Workaround for memmap2 API quirks... but seriously, why does it work like this?
    /// Converts a mutable file reference into a static immutable reference for use with memory mapping.
    ///
    /// # Safety
    ///
    /// This function intentionally leaks the provided file reference to extend its lifetime, satisfying the API requirements of the memory mapping library.
    fn immut(file: &mut File) -> &File {
        Box::leak(Box::new(file))
    }
}

impl Write for TempFile {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        if let Some(ref mut file) = self.file {
            file.write(buf)
        } else {
            Err(io::Error::new(
                io::ErrorKind::NotFound,
                TempError::FileIsNone,
            ))
        }
    }
    fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> io::Result<usize> {
        if let Some(ref mut file) = self.file {
            file.write_vectored(bufs)
        } else {
            Err(io::Error::new(
                io::ErrorKind::NotFound,
                TempError::FileIsNone,
            ))
        }
    }
    fn flush(&mut self) -> io::Result<()> {
        if let Some(ref mut file) = self.file {
            file.flush()
        } else {
            Err(io::Error::new(
                io::ErrorKind::NotFound,
                TempError::FileIsNone,
            ))
        }
    }
}

impl Read for TempFile {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if let Some(ref mut file) = self.file {
            file.read(buf)
        } else {
            Err(io::Error::new(
                io::ErrorKind::NotFound,
                TempError::FileIsNone,
            ))
        }
    }
    fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> io::Result<usize> {
        if let Some(ref mut file) = self.file {
            file.read_vectored(bufs)
        } else {
            Err(io::Error::new(
                io::ErrorKind::NotFound,
                TempError::FileIsNone,
            ))
        }
    }
    fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
        if let Some(ref mut file) = self.file {
            file.read_to_end(buf)
        } else {
            Err(io::Error::new(
                io::ErrorKind::NotFound,
                TempError::FileIsNone,
            ))
        }
    }
    fn read_to_string(&mut self, buf: &mut String) -> io::Result<usize> {
        if let Some(ref mut file) = self.file {
            file.read_to_string(buf)
        } else {
            Err(io::Error::new(
                io::ErrorKind::NotFound,
                TempError::FileIsNone,
            ))
        }
    }
}

impl Seek for TempFile {
    fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
        if let Some(ref mut file) = self.file {
            file.seek(pos)
        } else {
            Err(io::Error::new(
                io::ErrorKind::NotFound,
                TempError::FileIsNone,
            ))
        }
    }
}

impl Debug for TempFile {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TempFile")
            .field("path", &self.path)
            .field("file", &self.file)
            .field("created_dir", &self.created_parent)
            .finish()
    }
}

impl Drop for TempFile {
    fn drop(&mut self) {
        match (self.path.take(), self.created_parent.take()) {
            (Some(p), None) => {
                let _ = fs::remove_file(p);
            }
            (Some(_), Some(d)) => {
                let _ = fs::remove_dir_all(d);
            }
            _ => {}
        }
    }
}

impl AsRef<Path> for TempFile {
    fn as_ref(&self) -> &Path {
        // Instead of panicking if the path is None, we return an empty path.
        self.path.as_deref().unwrap_or_else(|| Path::new(""))
    }
}

impl AsRef<File> for TempFile {
    fn as_ref(&self) -> &File {
        self.file().expect("TempFile inner File is None")
    }
}

impl AsMut<File> for TempFile {
    fn as_mut(&mut self) -> &mut File {
        self.file_mut().expect("TempFile inner File is None")
    }
}

impl Deref for TempFile {
    type Target = File;
    fn deref(&self) -> &Self::Target {
        self.file().expect("TempFile inner File is None")
    }
}

impl DerefMut for TempFile {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.file_mut().expect("TempFile inner File is None")
    }
}

#[cfg(windows)]
impl std::os::windows::io::AsRawHandle for TempFile {
    fn as_raw_handle(&self) -> std::os::windows::io::RawHandle {
        // Return a null handle if the file is not available.
        self.file
            .as_ref()
            .map(|f| f.as_raw_handle())
            .unwrap_or(std::ptr::null_mut())
    }
}

#[cfg(unix)]
impl AsRawFd for TempFile {
    fn as_raw_fd(&self) -> RawFd {
        // Return -1 if the file is not available.
        self.file.as_ref().map_or(-1, AsRawFd::as_raw_fd)
    }
}

#[cfg(feature = "display_files")]
impl Display for TempFile {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.file {
            None => writeln!(f, "No file"),
            Some(ref file) => {
                let mut buf = Vec::new();
                file.try_clone()
                    .expect("Failed to get new file handle")
                    .read_to_end(&mut buf)
                    .expect("Failed to read from file");
                writeln!(f, "{}", sew::infallible::InfallibleString::from(buf))
            }
        }
    }
}