Coverage Report

Created: 2025-10-10 06:06

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/tempfile-3.23.0/src/env.rs
Line
Count
Source
1
use std::env;
2
use std::path::{Path, PathBuf};
3
4
#[cfg(doc)]
5
use crate::{tempdir_in, tempfile_in, Builder};
6
7
// Once rust 1.70 is wide-spread (Debian stable), we can use OnceLock from stdlib.
8
use once_cell::sync::OnceCell as OnceLock;
9
10
static DEFAULT_TEMPDIR: OnceLock<PathBuf> = OnceLock::new();
11
12
/// Override the default temporary directory (defaults to [`std::env::temp_dir`]). This function
13
/// changes the _global_ default temporary directory for the entire program and should not be called
14
/// except in exceptional cases where it's not configured correctly by the platform. Applications
15
/// should first check if the path returned by [`env::temp_dir`] is acceptable.
16
///
17
/// If you're writing a library and want to control where your temporary files are placed, you
18
/// should instead use the `_in` variants of the various temporary file/directory constructors
19
/// ([`tempdir_in`], [`tempfile_in`], the so-named functions on [`Builder`], etc.).
20
///
21
/// Only the first call to this function will succeed. All further calls will fail with `Err(path)`
22
/// where `path` is previously set default temporary directory override.
23
///
24
/// **NOTE:** This function does not check if the specified directory exists and/or is writable.
25
0
pub fn override_temp_dir(path: &Path) -> Result<(), PathBuf> {
26
0
    let mut we_set = false;
27
0
    let val = DEFAULT_TEMPDIR.get_or_init(|| {
28
0
        we_set = true;
29
0
        path.to_path_buf()
30
0
    });
31
0
    if we_set {
32
0
        Ok(())
33
    } else {
34
0
        Err(val.to_owned())
35
    }
36
0
}
37
38
/// Returns the default temporary directory, used for both temporary directories and files if no
39
/// directory is explicitly specified.
40
///
41
/// This function simply delegates to [`std::env::temp_dir`] unless the default temporary directory
42
/// has been override by a call to [`override_temp_dir`].
43
///
44
/// **NOTE:** This function does not check if the returned directory exists and/or is writable.
45
7.29k
pub fn temp_dir() -> PathBuf {
46
7.29k
    DEFAULT_TEMPDIR
47
7.29k
        .get()
48
7.29k
        .map(|p| p.to_owned())
49
        // Don't cache this in case the user uses std::env::set to change the temporary directory.
50
7.29k
        .unwrap_or_else(env::temp_dir)
51
7.29k
}