Coverage Report

Created: 2025-02-21 07:11

/rust/registry/src/index.crates.io-6f17d22bba15001f/tempfile-3.16.0/src/env.rs
Line
Count
Source (jump to first uncovered line)
1
use std::env;
2
use std::path::{Path, PathBuf};
3
4
// Once rust 1.70 is wide-spread (Debian stable), we can use OnceLock from stdlib.
5
use once_cell::sync::OnceCell as OnceLock;
6
7
static DEFAULT_TEMPDIR: OnceLock<PathBuf> = OnceLock::new();
8
9
/// Override the default temporary directory (defaults to [`std::env::temp_dir`]). This function
10
/// changes the _global_ default temporary directory for the entire program and should not be called
11
/// except in exceptional cases where it's not configured correctly by the platform. Applications
12
/// should first check if the path returned by [`env::temp_dir`] is acceptable.
13
///
14
/// Only the first call to this function will succeed. All further calls will fail with `Err(path)`
15
/// where `path` is previously set default temporary directory override.
16
///
17
/// **NOTE:** This function does not check if the specified directory exists and/or is writable.
18
0
pub fn override_temp_dir(path: &Path) -> Result<(), PathBuf> {
19
0
    let mut we_set = false;
20
0
    let val = DEFAULT_TEMPDIR.get_or_init(|| {
21
0
        we_set = true;
22
0
        path.to_path_buf()
23
0
    });
24
0
    if we_set {
25
0
        Ok(())
26
    } else {
27
0
        Err(val.to_owned())
28
    }
29
0
}
30
31
/// Returns the default temporary directory, used for both temporary directories and files if no
32
/// directory is explicitly specified.
33
///
34
/// This function simply delegates to [`std::env::temp_dir`] unless the default temporary directory
35
/// has been override by a call to [`override_temp_dir`].
36
///
37
/// **NOTE:** This function does check if the returned directory exists and/or is writable.
38
0
pub fn temp_dir() -> PathBuf {
39
0
    DEFAULT_TEMPDIR
40
0
        .get()
41
0
        .map(|p| p.to_owned())
42
0
        // Don't cache this in case the user uses std::env::set to change the temporary directory.
43
0
        .unwrap_or_else(env::temp_dir)
44
0
}