| 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 |
pub fn override_temp_dir(path: &Path) -> Result<(), PathBuf> { |
| 26 |
let mut we_set = false; |
| 27 |
let val = DEFAULT_TEMPDIR.get_or_init(|| { |
| 28 |
we_set = true; |
| 29 |
path.to_path_buf() |
| 30 |
}); |
| 31 |
if we_set { |
| 32 |
Ok(()) |
| 33 |
} else { |
| 34 |
Err(val.to_owned()) |
| 35 |
} |
| 36 |
} |
| 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 overridden 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 |
pub fn temp_dir() -> PathBuf { |
| 46 |
DEFAULT_TEMPDIR |
| 47 |
.get() |
| 48 |
.map(|p| p.to_owned()) |
| 49 |
// Don't cache this in case the user uses std::env::set to change the temporary directory. |
| 50 |
.unwrap_or_else(env::temp_dir) |
| 51 |
} |