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. |
12 | /// |
13 | /// Only the first call to this function will succeed. All further calls will fail with `Err(path)` |
14 | /// where `path` is previously set default temporary directory override. |
15 | /// |
16 | /// **NOTE:** This function does not check if the specified directory exists and/or is writable. |
17 | pub fn override_temp_dir(path: &Path) -> Result<(), PathBuf> { |
18 | let mut we_set: bool = false; |
19 | let val: &PathBuf = DEFAULT_TEMPDIR.get_or_init(|| { |
20 | we_set = true; |
21 | path.to_path_buf() |
22 | }); |
23 | if we_set { |
24 | Ok(()) |
25 | } else { |
26 | Err(val.to_owned()) |
27 | } |
28 | } |
29 | |
30 | /// Returns the default temporary directory, used for both temporary directories and files if no |
31 | /// directory is explicitly specified. |
32 | /// |
33 | /// This function simply delegates to [`std::env::temp_dir`] unless the default temporary directory |
34 | /// has been override by a call to [`override_temp_dir`]. |
35 | /// |
36 | /// **NOTE:** This function does check if the returned directory exists and/or is writable. |
37 | pub fn temp_dir() -> PathBuf { |
38 | DEFAULT_TEMPDIROption |
39 | .get() |
40 | .map(|p: &PathBuf| p.to_owned()) |
41 | // Don't cache this in case the user uses std::env::set to change the temporary directory. |
42 | .unwrap_or_else(env::temp_dir) |
43 | } |
44 | |