| 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 |
pub fn override_temp_dir(path: &Path) -> Result<(), PathBuf> { |
| 19 |
let mut we_set = false; |
| 20 |
let val = DEFAULT_TEMPDIR.get_or_init(|| { |
| 21 |
we_set = true; |
| 22 |
path.to_path_buf() |
| 23 |
}); |
| 24 |
if we_set { |
| 25 |
Ok(()) |
| 26 |
} else { |
| 27 |
Err(val.to_owned()) |
| 28 |
} |
| 29 |
} |
| 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 |
pub fn temp_dir() -> PathBuf { |
| 39 |
DEFAULT_TEMPDIR |
| 40 |
.get() |
| 41 |
.map(|p| p.to_owned()) |
| 42 |
// Don't cache this in case the user uses std::env::set to change the temporary directory. |
| 43 |
.unwrap_or_else(env::temp_dir) |
| 44 |
} |